From 2363ad544979adf32207fa927f106fadb784f1fb Mon Sep 17 00:00:00 2001 From: redSpoutnik <15638041+redSpoutnik@users.noreply.github.com> Date: Fri, 8 May 2020 21:53:38 +0200 Subject: [PATCH 0001/1930] Add Post subtitle in API --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 55 +++++++++++++++ .../Subtitles/ISubtitleManager.cs | 6 ++ .../Subtitles/SubtitleManager.cs | 70 ++++++++++++------- 3 files changed, 104 insertions(+), 27 deletions(-) diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index f2968c6b5c..ed2533f6d4 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -37,6 +37,31 @@ namespace MediaBrowser.Api.Subtitles public int Index { get; set; } } + [Route("/Videos/{Id}/Subtitles", "POST", Summary = "Upload an external subtitle file")] + [Authenticated(Roles = "admin")] + public class PostSubtitle : IReturnVoid + { + /// + /// Gets or sets the id. + /// + /// The id. + [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string Id { get; set; } + + [ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string Language { get; set; } + + [ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string Format { get; set; } + + [ApiMember(Name = "IsForced", Description = "IsForced", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string IsForced { get; set; } + + [ApiMember(Name = "Data", Description = "Data", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] + public string Data { get; set; } + + } + [Route("/Items/{Id}/RemoteSearch/Subtitles/{Language}", "GET")] [Authenticated] public class SearchRemoteSubtitles : IReturn @@ -270,6 +295,36 @@ namespace MediaBrowser.Api.Subtitles return _subtitleManager.DeleteSubtitles(item, request.Index); } + public void Post(PostSubtitle request) + { + var video = (Video)_libraryManager.GetItemById(request.Id); + + var bytes = Convert.FromBase64String(request.Data); + var memoryStream = new MemoryStream(bytes) + { + Position = 0 + }; + + Task.Run(async () => + { + try + { + await _subtitleManager.UploadSubtitle(video, new SubtitleResponse { + Format = request.Format, + Language = request.Language, + IsForced = Convert.ToBoolean(request.IsForced), + Stream = memoryStream + }).ConfigureAwait(false); + + _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error uploading subtitle"); + } + }); + } + public async Task Get(GetRemoteSubtitles request) { var result = await _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs index 39538aacd7..556e2f66c8 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; @@ -50,6 +51,11 @@ namespace MediaBrowser.Controller.Subtitles /// Task DownloadSubtitles(Video video, LibraryOptions libraryOptions, string subtitleId, CancellationToken cancellationToken); + /// + /// Upload new subtitle. + /// + Task UploadSubtitle(Video video, SubtitleResponse response); + /// /// Gets the remote subtitles. /// diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 127d29c04e..2b55618a8e 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -147,37 +147,11 @@ namespace MediaBrowser.Providers.Subtitles var parts = subtitleId.Split(new[] { '_' }, 2); var provider = GetProvider(parts.First()); - var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia; - try { var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false); - using (var stream = response.Stream) - using (var memoryStream = new MemoryStream()) - { - await stream.CopyToAsync(memoryStream).ConfigureAwait(false); - memoryStream.Position = 0; - - var savePaths = new List(); - var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant(); - - if (response.IsForced) - { - saveFileName += ".forced"; - } - - saveFileName += "." + response.Format.ToLowerInvariant(); - - if (saveInMediaFolder) - { - savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName)); - } - - savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); - - await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); - } + await TrySaveSubtitle(video, libraryOptions, response); } catch (RateLimitExceededException) { @@ -196,6 +170,48 @@ namespace MediaBrowser.Providers.Subtitles } } + /// + public async Task UploadSubtitle(Video video, SubtitleResponse response) + { + var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video); + + await TrySaveSubtitle(video, libraryOptions, response); + } + + private async Task TrySaveSubtitle( + Video video, + LibraryOptions libraryOptions, + SubtitleResponse response) + { + var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia; + + using (var stream = response.Stream) + using (var memoryStream = new MemoryStream()) + { + await stream.CopyToAsync(memoryStream).ConfigureAwait(false); + memoryStream.Position = 0; + + var savePaths = new List(); + var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant(); + + if (response.IsForced) + { + saveFileName += ".forced"; + } + + saveFileName += "." + response.Format.ToLowerInvariant(); + + if (saveInMediaFolder) + { + savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName)); + } + + savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); + + await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); + } + } + private async Task TrySaveToFiles(Stream stream, List savePaths) { Exception exceptionToThrow = null; From ba03ed65fe64b724b3e8b5b94b9cbe1075c61da2 Mon Sep 17 00:00:00 2001 From: ferferga Date: Wed, 27 May 2020 19:13:41 +0200 Subject: [PATCH 0002/1930] Remove "download images in advance" option --- .../Configuration/LibraryOptions.cs | 1 - .../Manager/ItemImageProvider.cs | 12 +---------- .../Manager/MetadataService.cs | 21 ++++++++----------- 3 files changed, 10 insertions(+), 24 deletions(-) diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs index 4342ccd8ae..01d6665621 100644 --- a/MediaBrowser.Model/Configuration/LibraryOptions.cs +++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs @@ -12,7 +12,6 @@ namespace MediaBrowser.Model.Configuration public bool EnableRealtimeMonitor { get; set; } public bool EnableChapterImageExtraction { get; set; } public bool ExtractChapterImagesDuringLibraryScan { get; set; } - public bool DownloadImagesInAdvance { get; set; } public MediaPathInfo[] PathInfos { get; set; } public bool SaveLocalMetadata { get; set; } diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index 6ef0e44a2b..60270d80cb 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -495,17 +495,7 @@ namespace MediaBrowser.Providers.Manager } } - if (libraryOptions.DownloadImagesInAdvance) - { - return false; - } - - //if (!item.IsSaveLocalMetadataEnabled()) - //{ - // return true; - //} - - return true; + return false; } private void SaveImageStub(BaseItem item, ImageType imageType, IEnumerable urls) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index c49aa407aa..dffdc468ad 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -252,18 +252,15 @@ namespace MediaBrowser.Providers.Manager private void AddPersonImage(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken) { - //if (libraryOptions.DownloadImagesInAdvance) - //{ - // try - // { - // await ProviderManager.SaveImage(personEntity, imageUrl, ImageType.Primary, null, cancellationToken).ConfigureAwait(false); - // return; - // } - // catch (Exception ex) - // { - // Logger.LogError(ex, "Error in AddPersonImage"); - // } - //} + try + { + await ProviderManager.SaveImage(personEntity, imageUrl, ImageType.Primary, null, cancellationToken).ConfigureAwait(false); + return; + } + catch (Exception ex) + { + Logger.LogError(ex, "Error in AddPersonImage"); + } personEntity.SetImage(new ItemImageInfo { From 82ff3fa75d7da1d160ee5b774bd2238b5727d5ea Mon Sep 17 00:00:00 2001 From: Erik Rigtorp Date: Sun, 3 May 2020 20:44:18 -0700 Subject: [PATCH 0003/1930] Add additional resolver tests --- .../Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs | 1 + .../Jellyfin.Naming.Tests/Video/VideoResolverTests.cs | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs index 917d8fb3a9..49820df629 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs @@ -47,6 +47,7 @@ namespace Jellyfin.Naming.Tests.Video // FIXME: [InlineData("Robin Hood [Multi-Subs] [2018].mkv", "Robin Hood", 2018)] [InlineData(@"3.Days.to.Kill.2014.720p.BluRay.x264.YIFY.mkv", "3.Days.to.Kill", 2014)] // In this test case, running CleanDateTime first produces no date, so it will attempt to run CleanString first and then CleanDateTime again [InlineData("3 days to kill (2005).mkv", "3 days to kill", 2005)] + [InlineData(@"Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", "Rain Man", 1988)] public void CleanDateTimeTest(string input, string expectedName, int? expectedYear) { input = Path.GetFileName(input); diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index 99828b2eb7..096ebb836a 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -174,6 +174,16 @@ namespace Jellyfin.Naming.Tests.Video Year = 2006, } }; + yield return new object[] + { + new VideoFileInfo() + { + Path = @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", + Container = "mp4", + Name = "Rain Man", + Year = 1988, + } + }; } [Theory] From 75efb8f52d4234bfdefa2a0ac48f7261aa9ef58b Mon Sep 17 00:00:00 2001 From: Erik Rigtorp Date: Sun, 3 May 2020 21:29:52 -0700 Subject: [PATCH 0004/1930] Use additional unicode chars for year extraction --- Emby.Naming/Common/NamingOptions.cs | 4 +++- Emby.Naming/Video/CleanDateTimeParser.cs | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 1b343790e8..c727681a65 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -137,7 +137,9 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19\d{2}|20\d{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19\d{2}|20\d{2})*", - @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19\d{2}|20\d{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19\d{2}|20\d{2})*" + @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19\d{2}|20\d{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19\d{2}|20\d{2})*", + @"(.+\w)\W+\p{Ps}(19[0-9]{2}|20[0-9]{2})\p{Pe}", // Prefer year enclosed in parenthesis (){}[] + @"(.+\w)\W+(19[0-9]{2}|20[0-9]{2})(\W|$)", // Secondary year surrounded by non-word chars }; CleanStrings = new[] diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 579c9e91e1..7c18ab039c 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -32,7 +32,6 @@ namespace Emby.Naming.Video var match = expression.Match(name); if (match.Success - && match.Groups.Count == 5 && match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) From c888b34a6219be0c06331e568d66a8fdf17bceaa Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Fri, 24 Jul 2020 21:19:56 +0800 Subject: [PATCH 0005/1930] add a method to use custom fallback fonts for subtitle rendering --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 53 +++++++++++++++++++ .../Configuration/EncodingOptions.cs | 5 ++ 2 files changed, 58 insertions(+) diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index a70da8e56c..198e459482 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -122,8 +123,15 @@ namespace MediaBrowser.Api.Subtitles public int SegmentLength { get; set; } } + [Route("/FallbackFont/Font", "GET", Summary = "Gets the fallback font file")] + [Authenticated] + public class GetFallbackFont + { + } + public class SubtitleService : BaseApiService { + private readonly IServerConfigurationManager _serverConfigurationManager; private readonly ILibraryManager _libraryManager; private readonly ISubtitleManager _subtitleManager; private readonly ISubtitleEncoder _subtitleEncoder; @@ -145,6 +153,7 @@ namespace MediaBrowser.Api.Subtitles IAuthorizationContext authContext) : base(logger, serverConfigurationManager, httpResultFactory) { + _serverConfigurationManager = serverConfigurationManager; _libraryManager = libraryManager; _subtitleManager = subtitleManager; _subtitleEncoder = subtitleEncoder; @@ -298,5 +307,49 @@ namespace MediaBrowser.Api.Subtitles } }); } + + public async Task Get(GetFallbackFont request) + { + var fallbackFontPath = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager).FallbackFontPath; + + if (!string.IsNullOrEmpty(fallbackFontPath)) + { + var directoryService = new DirectoryService(_fileSystem); + + try + { + // 10 Megabytes + var maxSize = 10485760; + var fontFile = directoryService.GetFile(fallbackFontPath); + var fileSize = fontFile?.Length; + + if (fileSize != null && fileSize > 0) + { + Logger.LogInformation("Fallback font size is {0} Bytes", fileSize); + + if (fileSize <= maxSize) + { + return await ResultFactory.GetStaticFileResult(Request, fontFile.FullName); + } + + Logger.LogInformation("The selected font is too large. Maximum allowed size is 10 Megabytes"); + } + else + { + Logger.LogInformation("The selected font is null or empty"); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Error reading fallback font file"); + } + } + else + { + Logger.LogInformation("The path of fallback font has not been set"); + } + + return string.Empty; + } } } diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index 9a30f7e9f0..aa6ed5bb9f 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -9,6 +9,10 @@ namespace MediaBrowser.Model.Configuration public string TranscodingTempPath { get; set; } + public string FallbackFontPath { get; set; } + + public bool EnableFallbackFont { get; set; } + public double DownMixAudioBoost { get; set; } public bool EnableThrottling { get; set; } @@ -49,6 +53,7 @@ namespace MediaBrowser.Model.Configuration public EncodingOptions() { + EnableFallbackFont = false; DownMixAudioBoost = 2; EnableThrottling = false; ThrottleDelaySeconds = 180; From a78c8e38544a974f07c6efce1af4e7fbef83b2be Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Sat, 25 Jul 2020 01:50:18 +0800 Subject: [PATCH 0006/1930] change loglevels --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index 198e459482..b06ffd1851 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -325,18 +325,18 @@ namespace MediaBrowser.Api.Subtitles if (fileSize != null && fileSize > 0) { - Logger.LogInformation("Fallback font size is {0} Bytes", fileSize); + Logger.LogDebug("Fallback font size is {0} Bytes", fileSize); if (fileSize <= maxSize) { return await ResultFactory.GetStaticFileResult(Request, fontFile.FullName); } - Logger.LogInformation("The selected font is too large. Maximum allowed size is 10 Megabytes"); + Logger.LogWarning("The selected font is too large. Maximum allowed size is 10 Megabytes"); } else { - Logger.LogInformation("The selected font is null or empty"); + Logger.LogWarning("The selected font is null or empty"); } } catch (Exception ex) @@ -346,7 +346,7 @@ namespace MediaBrowser.Api.Subtitles } else { - Logger.LogInformation("The path of fallback font has not been set"); + Logger.LogWarning("The path of fallback font has not been set"); } return string.Empty; From 45a97056ea9fe7bc247f205931f5b0e0f2a1ab75 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Wed, 29 Jul 2020 02:44:11 +0800 Subject: [PATCH 0007/1930] allows to provide multiple fonts --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 83 +++++++++++++++++-- MediaBrowser.Model/Subtitles/FontFile.cs | 34 ++++++++ 2 files changed, 108 insertions(+), 9 deletions(-) create mode 100644 MediaBrowser.Model/Subtitles/FontFile.cs diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index b06ffd1851..b5f5213fe3 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -18,6 +18,7 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Services; +using MediaBrowser.Model.Subtitles; using Microsoft.Extensions.Logging; using MimeTypes = MediaBrowser.Model.Net.MimeTypes; @@ -123,10 +124,18 @@ namespace MediaBrowser.Api.Subtitles public int SegmentLength { get; set; } } + [Route("/FallbackFont/FontList", "GET", Summary = "Gets the fallback font list")] + [Authenticated] + public class GetFallbackFontList + { + } + [Route("/FallbackFont/Font", "GET", Summary = "Gets the fallback font file")] [Authenticated] public class GetFallbackFont { + [ApiMember(Name = "Name", Description = "The font file name.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)] + public string Name { get; set; } } public class SubtitleService : BaseApiService @@ -308,19 +317,74 @@ namespace MediaBrowser.Api.Subtitles }); } - public async Task Get(GetFallbackFont request) + public object Get(GetFallbackFontList request) { - var fallbackFontPath = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager).FallbackFontPath; + IEnumerable fontFiles = Enumerable.Empty(); + + var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var fallbackFontPath = encodingOptions.FallbackFontPath; if (!string.IsNullOrEmpty(fallbackFontPath)) { - var directoryService = new DirectoryService(_fileSystem); - try { - // 10 Megabytes + fontFiles = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false); + + var result = fontFiles.Select(i => new FontFile + { + Name = i.Name, + Size = i.Length, + DateCreated = _fileSystem.GetCreationTimeUtc(i), + DateModified = _fileSystem.GetLastWriteTimeUtc(i) + }).OrderBy(i => i.Size) + .ThenBy(i => i.Name) + .ThenByDescending(i => i.DateModified) + .ThenByDescending(i => i.DateCreated) + .ToArray(); + + // max total size 20M + var maxSize = 20971520; + var sizeCounter = 0L; + for (int i = 0; i < result.Length; i++) + { + sizeCounter += result[i].Size; + if (sizeCounter >= maxSize) + { + Logger.LogWarning("Some fonts will not be sent due to size limitations"); + Array.Resize(ref result, i); + break; + } + } + + return ToOptimizedResult(result); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error getting fallback font list"); + } + } + else + { + Logger.LogWarning("The path of fallback font folder has not been set"); + encodingOptions.EnableFallbackFont = false; + } + + return ResultFactory.GetResult(Request, "[]", "application/json"); + } + + public async Task Get(GetFallbackFont request) + { + var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var fallbackFontPath = encodingOptions.FallbackFontPath; + + if (!string.IsNullOrEmpty(fallbackFontPath)) + { + try + { + // max single font size 10M var maxSize = 10485760; - var fontFile = directoryService.GetFile(fallbackFontPath); + var fontFile = _fileSystem.GetFiles(fallbackFontPath) + .First(i => string.Equals(i.Name, request.Name, StringComparison.OrdinalIgnoreCase)); var fileSize = fontFile?.Length; if (fileSize != null && fileSize > 0) @@ -341,15 +405,16 @@ namespace MediaBrowser.Api.Subtitles } catch (Exception ex) { - Logger.LogError(ex, "Error reading fallback font file"); + Logger.LogError(ex, "Error reading fallback font"); } } else { - Logger.LogWarning("The path of fallback font has not been set"); + Logger.LogWarning("The path of fallback font folder has not been set"); + encodingOptions.EnableFallbackFont = false; } - return string.Empty; + return ResultFactory.GetResult(Request, string.Empty, "text/plain"); } } } diff --git a/MediaBrowser.Model/Subtitles/FontFile.cs b/MediaBrowser.Model/Subtitles/FontFile.cs new file mode 100644 index 0000000000..13963a9cb5 --- /dev/null +++ b/MediaBrowser.Model/Subtitles/FontFile.cs @@ -0,0 +1,34 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; + +namespace MediaBrowser.Model.Subtitles +{ + public class FontFile + { + /// + /// Gets or sets the name. + /// + /// The name. + public string Name { get; set; } + + /// + /// Gets or sets the size. + /// + /// The size. + public long Size { get; set; } + + /// + /// Gets or sets the date created. + /// + /// The date created. + public DateTime DateCreated { get; set; } + + /// + /// Gets or sets the date modified. + /// + /// The date modified. + public DateTime DateModified { get; set; } + } +} From 893bc7400bc2dadf2a789ba439d9a469c13b05df Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 30 Jul 2020 16:30:49 +0800 Subject: [PATCH 0008/1930] update as per suggestions --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index b5f5213fe3..e275d3a285 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Mime; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -124,13 +125,13 @@ namespace MediaBrowser.Api.Subtitles public int SegmentLength { get; set; } } - [Route("/FallbackFont/FontList", "GET", Summary = "Gets the fallback font list")] + [Route("/FallbackFont/Fonts", "GET", Summary = "Gets the fallback font list")] [Authenticated] public class GetFallbackFontList { } - [Route("/FallbackFont/Font", "GET", Summary = "Gets the fallback font file")] + [Route("/FallbackFont/Fonts/{Name}", "GET", Summary = "Gets the fallback font file")] [Authenticated] public class GetFallbackFont { @@ -369,7 +370,7 @@ namespace MediaBrowser.Api.Subtitles encodingOptions.EnableFallbackFont = false; } - return ResultFactory.GetResult(Request, "[]", "application/json"); + return ResultFactory.GetResult(Request, "[]", MediaTypeNames.Application.Json); } public async Task Get(GetFallbackFont request) @@ -414,7 +415,7 @@ namespace MediaBrowser.Api.Subtitles encodingOptions.EnableFallbackFont = false; } - return ResultFactory.GetResult(Request, string.Empty, "text/plain"); + return ResultFactory.GetResult(Request, string.Empty, MediaTypeNames.Text.Plain); } } } From 8165c3bb21a1ac4869dafa951f8a3ca3d21dda1e Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 30 Jul 2020 17:36:38 +0800 Subject: [PATCH 0009/1930] total font size limit 20M --- MediaBrowser.Api/Subtitles/SubtitleService.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs index e275d3a285..bd4da04f90 100644 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ b/MediaBrowser.Api/Subtitles/SubtitleService.cs @@ -382,8 +382,6 @@ namespace MediaBrowser.Api.Subtitles { try { - // max single font size 10M - var maxSize = 10485760; var fontFile = _fileSystem.GetFiles(fallbackFontPath) .First(i => string.Equals(i.Name, request.Name, StringComparison.OrdinalIgnoreCase)); var fileSize = fontFile?.Length; @@ -391,13 +389,7 @@ namespace MediaBrowser.Api.Subtitles if (fileSize != null && fileSize > 0) { Logger.LogDebug("Fallback font size is {0} Bytes", fileSize); - - if (fileSize <= maxSize) - { - return await ResultFactory.GetStaticFileResult(Request, fontFile.FullName); - } - - Logger.LogWarning("The selected font is too large. Maximum allowed size is 10 Megabytes"); + return await ResultFactory.GetStaticFileResult(Request, fontFile.FullName); } else { From 988e76d4c7df48370a6cb1de59c4909d140f96e2 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Wed, 19 Aug 2020 17:30:22 +0800 Subject: [PATCH 0010/1930] update endpoints as AspNet controllers --- .../Controllers/SubtitleController.cs | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 988acccc3a..387c9b0953 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -10,6 +10,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Constants; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -20,6 +22,7 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; +using MediaBrowser.Model.Subtitles; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -33,6 +36,7 @@ namespace Jellyfin.Api.Controllers [Route("")] public class SubtitleController : BaseJellyfinApiController { + private readonly IServerConfigurationManager _serverConfigurationManager; private readonly ILibraryManager _libraryManager; private readonly ISubtitleManager _subtitleManager; private readonly ISubtitleEncoder _subtitleEncoder; @@ -45,6 +49,7 @@ namespace Jellyfin.Api.Controllers /// /// Initializes a new instance of the class. /// + /// Instance of interface. /// Instance of interface. /// Instance of interface. /// Instance of interface. @@ -54,6 +59,7 @@ namespace Jellyfin.Api.Controllers /// Instance of interface. /// Instance of interface. public SubtitleController( + IServerConfigurationManager serverConfigurationManager, ILibraryManager libraryManager, ISubtitleManager subtitleManager, ISubtitleEncoder subtitleEncoder, @@ -63,6 +69,7 @@ namespace Jellyfin.Api.Controllers IAuthorizationContext authContext, ILogger logger) { + _serverConfigurationManager = serverConfigurationManager; _libraryManager = libraryManager; _subtitleManager = subtitleManager; _subtitleEncoder = subtitleEncoder; @@ -346,5 +353,116 @@ namespace Jellyfin.Api.Controllers copyTimestamps, CancellationToken.None); } + + /// + /// Gets a list of available fallback font files. + /// + /// Information retrieved. + /// An array of with the available font files. + [HttpGet("/FallbackFont/Fonts")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult GetFallbackFontList() + { + IEnumerable fontFiles = Enumerable.Empty(); + + var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var fallbackFontPath = encodingOptions.FallbackFontPath; + + if (!string.IsNullOrEmpty(fallbackFontPath)) + { + try + { + fontFiles = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false); + + var result = fontFiles.Select(i => new FontFile + { + Name = i.Name, + Size = i.Length, + DateCreated = _fileSystem.GetCreationTimeUtc(i), + DateModified = _fileSystem.GetLastWriteTimeUtc(i) + }).OrderBy(i => i.Size) + .ThenBy(i => i.Name) + .ThenByDescending(i => i.DateModified) + .ThenByDescending(i => i.DateCreated) + .ToArray(); + + // max total size 20M + var maxSize = 20971520; + var sizeCounter = 0L; + for (int i = 0; i < result.Length; i++) + { + sizeCounter += result[i].Size; + if (sizeCounter >= maxSize) + { + _logger.LogWarning("Some fonts will not be sent due to size limitations"); + Array.Resize(ref result, i); + break; + } + } + + return result; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error getting fallback font list"); + } + } + else + { + _logger.LogWarning("The path of fallback font folder has not been set"); + encodingOptions.EnableFallbackFont = false; + } + + return File(Encoding.UTF8.GetBytes("[]"), MediaTypeNames.Application.Json); + } + + /// + /// Gets a fallback font file. + /// + /// The name of the fallback font file to get. + /// Fallback font file retrieved. + /// The fallback font file. + [HttpGet("/FallbackFont/Fonts/{name}")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult GetFallbackFont([FromRoute, Required] string? name) + { + var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var fallbackFontPath = encodingOptions.FallbackFontPath; + + if (!string.IsNullOrEmpty(fallbackFontPath)) + { + try + { + var fontFile = _fileSystem.GetFiles(fallbackFontPath) + .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)); + var fileSize = fontFile?.Length; + + if (fontFile != null && fileSize != null && fileSize > 0) + { + _logger.LogDebug("Fallback font size is {0} Bytes", fileSize); + + FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); + return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); + } + else + { + _logger.LogWarning("The selected font is null or empty"); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error reading fallback font"); + } + } + else + { + _logger.LogWarning("The path of fallback font folder has not been set"); + encodingOptions.EnableFallbackFont = false; + } + + return File(Encoding.UTF8.GetBytes(string.Empty), MediaTypeNames.Text.Plain); + } } } From 53861db45139022907c24a43bea43225f34c6a6d Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 20 Aug 2020 00:04:55 +0800 Subject: [PATCH 0011/1930] Apply suggestions from code review Co-authored-by: Cody Robibero --- .../Controllers/SubtitleController.cs | 69 +++++++++---------- 1 file changed, 33 insertions(+), 36 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 387c9b0953..0795f8f649 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -359,53 +359,52 @@ namespace Jellyfin.Api.Controllers /// /// Information retrieved. /// An array of with the available font files. - [HttpGet("/FallbackFont/Fonts")] + [HttpGet("FallbackFont/Fonts")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult GetFallbackFontList() + /// + /// Gets a list of available fallback font files. + /// + /// Information retrieved. + /// An array of with the available font files. + [HttpGet("FallbackFont/Fonts")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [ProducesResponseType(StatusCodes.Status200OK)] + public IEnumerable GetFallbackFontList() { - IEnumerable fontFiles = Enumerable.Empty(); - - var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); var fallbackFontPath = encodingOptions.FallbackFontPath; if (!string.IsNullOrEmpty(fallbackFontPath)) { - try - { - fontFiles = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false); + var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false); - var result = fontFiles.Select(i => new FontFile + var fontFiles = files + .Select(i => new FontFile { Name = i.Name, Size = i.Length, DateCreated = _fileSystem.GetCreationTimeUtc(i), DateModified = _fileSystem.GetLastWriteTimeUtc(i) - }).OrderBy(i => i.Size) - .ThenBy(i => i.Name) - .ThenByDescending(i => i.DateModified) - .ThenByDescending(i => i.DateCreated) - .ToArray(); + }) + .OrderBy(i => i.Size) + .ThenBy(i => i.Name) + .ThenByDescending(i => i.DateModified) + .ThenByDescending(i => i.DateCreated); - // max total size 20M - var maxSize = 20971520; - var sizeCounter = 0L; - for (int i = 0; i < result.Length; i++) + // max total size 20M + const int MaxSize = 20971520; + var sizeCounter = 0L; + foreach (var fontFile in fontFiles) + { + sizeCounter += fontFile.Size; + if (sizeCounter >= MaxSize) { - sizeCounter += result[i].Size; - if (sizeCounter >= maxSize) - { - _logger.LogWarning("Some fonts will not be sent due to size limitations"); - Array.Resize(ref result, i); - break; - } + _logger.LogWarning("Some fonts will not be sent due to size limitations"); + yield break; } - return result; - } - catch (Exception ex) - { - _logger.LogError(ex, "Error getting fallback font list"); + yield return fontFile; } } else @@ -413,8 +412,6 @@ namespace Jellyfin.Api.Controllers _logger.LogWarning("The path of fallback font folder has not been set"); encodingOptions.EnableFallbackFont = false; } - - return File(Encoding.UTF8.GetBytes("[]"), MediaTypeNames.Application.Json); } /// @@ -423,12 +420,12 @@ namespace Jellyfin.Api.Controllers /// The name of the fallback font file to get. /// Fallback font file retrieved. /// The fallback font file. - [HttpGet("/FallbackFont/Fonts/{name}")] + [HttpGet("FallbackFont/Fonts/{name}")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult GetFallbackFont([FromRoute, Required] string? name) + public ActionResult GetFallbackFont([FromRoute, Required] string name) { - var encodingOptions = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager); + var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); var fallbackFontPath = encodingOptions.FallbackFontPath; if (!string.IsNullOrEmpty(fallbackFontPath)) @@ -441,7 +438,7 @@ namespace Jellyfin.Api.Controllers if (fontFile != null && fileSize != null && fileSize > 0) { - _logger.LogDebug("Fallback font size is {0} Bytes", fileSize); + _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); From 16658c92fe1baeb23909001525008208cfc82f75 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 20 Aug 2020 00:08:44 +0800 Subject: [PATCH 0012/1930] fix SubtitlesOctopus --- .../Controllers/SubtitleController.cs | 41 ++++++------------- 1 file changed, 12 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 0795f8f649..6c9d1beecd 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -354,14 +354,6 @@ namespace Jellyfin.Api.Controllers CancellationToken.None); } - /// - /// Gets a list of available fallback font files. - /// - /// Information retrieved. - /// An array of with the available font files. - [HttpGet("FallbackFont/Fonts")] - [Authorize(Policy = Policies.DefaultAuthorization)] - [ProducesResponseType(StatusCodes.Status200OK)] /// /// Gets a list of available fallback font files. /// @@ -378,7 +370,6 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(fallbackFontPath)) { var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false); - var fontFiles = files .Select(i => new FontFile { @@ -391,7 +382,6 @@ namespace Jellyfin.Api.Controllers .ThenBy(i => i.Name) .ThenByDescending(i => i.DateModified) .ThenByDescending(i => i.DateCreated); - // max total size 20M const int MaxSize = 20971520; var sizeCounter = 0L; @@ -403,7 +393,6 @@ namespace Jellyfin.Api.Controllers _logger.LogWarning("Some fonts will not be sent due to size limitations"); yield break; } - yield return fontFile; } } @@ -430,27 +419,20 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(fallbackFontPath)) { - try + var fontFile = _fileSystem.GetFiles(fallbackFontPath) + .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)); + var fileSize = fontFile?.Length; + + if (fontFile != null && fileSize != null && fileSize > 0) { - var fontFile = _fileSystem.GetFiles(fallbackFontPath) - .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)); - var fileSize = fontFile?.Length; + _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); - if (fontFile != null && fileSize != null && fileSize > 0) - { - _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); - - FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); - return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); - } - else - { - _logger.LogWarning("The selected font is null or empty"); - } + FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); + return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); } - catch (Exception ex) + else { - _logger.LogError(ex, "Error reading fallback font"); + _logger.LogWarning("The selected font is null or empty"); } } else @@ -459,7 +441,8 @@ namespace Jellyfin.Api.Controllers encodingOptions.EnableFallbackFont = false; } - return File(Encoding.UTF8.GetBytes(string.Empty), MediaTypeNames.Text.Plain); + // returning HTTP 204 will break the SubtitlesOctopus + return Ok(); } } } From dd3b48f2039fe299a55db437190a9e0d5c78145c Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Thu, 20 Aug 2020 15:17:42 +0800 Subject: [PATCH 0013/1930] fix lint --- Jellyfin.Api/Controllers/SubtitleController.cs | 3 ++- MediaBrowser.Model/Subtitles/FontFile.cs | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 6c9d1beecd..912de0fd60 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -393,6 +393,7 @@ namespace Jellyfin.Api.Controllers _logger.LogWarning("Some fonts will not be sent due to size limitations"); yield break; } + yield return fontFile; } } @@ -425,7 +426,7 @@ namespace Jellyfin.Api.Controllers if (fontFile != null && fileSize != null && fileSize > 0) { - _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); + _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize); FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); diff --git a/MediaBrowser.Model/Subtitles/FontFile.cs b/MediaBrowser.Model/Subtitles/FontFile.cs index 13963a9cb5..115c492957 100644 --- a/MediaBrowser.Model/Subtitles/FontFile.cs +++ b/MediaBrowser.Model/Subtitles/FontFile.cs @@ -1,17 +1,17 @@ -#nullable disable -#pragma warning disable CS1591 - using System; namespace MediaBrowser.Model.Subtitles { + /// + /// Class FontFile. + /// public class FontFile { /// /// Gets or sets the name. /// /// The name. - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the size. From 05e78ee78c56364971956507f6239ded61f0af87 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Thu, 20 Aug 2020 22:53:36 +0800 Subject: [PATCH 0014/1930] Apply suggestions from code review Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/SubtitleController.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 912de0fd60..8550a86e0c 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -427,9 +427,7 @@ namespace Jellyfin.Api.Controllers if (fontFile != null && fileSize != null && fileSize > 0) { _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize); - - FileStream stream = new FileStream(fontFile.FullName, FileMode.Open, FileAccess.Read); - return File(stream, MimeTypes.GetMimeType(fontFile.FullName)); + return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName)); } else { From 8a15ad160b30769305b5cf03e16b3cec742156de Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 5 Sep 2020 18:58:16 -0400 Subject: [PATCH 0015/1930] Fix plugin events not being called and clean up InstallationManager.cs --- .../Updates/InstallationManager.cs | 66 ++++++------------- .../Updates/IInstallationManager.cs | 23 ------- 2 files changed, 19 insertions(+), 70 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index f121a34938..ac3caf83e6 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -10,12 +10,15 @@ using System.Runtime.Serialization; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Data.Events; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Events; +using MediaBrowser.Controller.Events.Updates; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; @@ -34,6 +37,7 @@ namespace Emby.Server.Implementations.Updates /// private readonly ILogger _logger; private readonly IApplicationPaths _appPaths; + private readonly IEventManager _eventManager; private readonly IHttpClientFactory _httpClientFactory; private readonly IJsonSerializer _jsonSerializer; private readonly IServerConfigurationManager _config; @@ -63,23 +67,20 @@ namespace Emby.Server.Implementations.Updates ILogger logger, IApplicationHost appHost, IApplicationPaths appPaths, + IEventManager eventManager, IHttpClientFactory httpClientFactory, IJsonSerializer jsonSerializer, IServerConfigurationManager config, IFileSystem fileSystem, IZipClient zipClient) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>(); _completedInstallationsInternal = new ConcurrentBag(); _logger = logger; _applicationHost = appHost; _appPaths = appPaths; + _eventManager = eventManager; _httpClientFactory = httpClientFactory; _jsonSerializer = jsonSerializer; _config = config; @@ -87,27 +88,6 @@ namespace Emby.Server.Implementations.Updates _zipClient = zipClient; } - /// - public event EventHandler PackageInstalling; - - /// - public event EventHandler PackageInstallationCompleted; - - /// - public event EventHandler PackageInstallationFailed; - - /// - public event EventHandler PackageInstallationCancelled; - - /// - public event EventHandler PluginUninstalled; - - /// - public event EventHandler PluginUpdated; - - /// - public event EventHandler PluginInstalled; - /// public IEnumerable CompletedInstallations => _completedInstallationsInternal; @@ -256,11 +236,11 @@ namespace Emby.Server.Implementations.Updates var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token; - PackageInstalling?.Invoke(this, package); + await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false); try { - await InstallPackageInternal(package, linkedToken).ConfigureAwait(false); + var isUpdate = await InstallPackageInternal(package, linkedToken).ConfigureAwait(false); lock (_currentInstallationsLock) { @@ -268,8 +248,11 @@ namespace Emby.Server.Implementations.Updates } _completedInstallationsInternal.Add(package); + await _eventManager.PublishAsync(isUpdate + ? (GenericEventArgs)new PluginUpdatedEventArgs(package) + : new PluginInstalledEventArgs(package)).ConfigureAwait(false); - PackageInstallationCompleted?.Invoke(this, package); + _applicationHost.NotifyPendingRestart(); } catch (OperationCanceledException) { @@ -280,7 +263,7 @@ namespace Emby.Server.Implementations.Updates _logger.LogInformation("Package installation cancelled: {0} {1}", package.Name, package.Version); - PackageInstallationCancelled?.Invoke(this, package); + await _eventManager.PublishAsync(new PluginInstallationCancelledEventArgs(package)).ConfigureAwait(false); throw; } @@ -293,11 +276,11 @@ namespace Emby.Server.Implementations.Updates _currentInstallations.Remove(tuple); } - PackageInstallationFailed?.Invoke(this, new InstallationFailedEventArgs + await _eventManager.PublishAsync(new InstallationFailedEventArgs { InstallationInfo = package, Exception = ex - }); + }).ConfigureAwait(false); throw; } @@ -314,7 +297,7 @@ namespace Emby.Server.Implementations.Updates /// The package. /// The cancellation token. /// . - private async Task InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) + private async Task InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) { // Set last update time if we were installed before IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Id == package.Guid) @@ -324,20 +307,9 @@ namespace Emby.Server.Implementations.Updates await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); // Do plugin-specific processing - if (plugin == null) - { - _logger.LogInformation("New plugin installed: {0} {1}", package.Name, package.Version); + _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version); - PluginInstalled?.Invoke(this, package); - } - else - { - _logger.LogInformation("Plugin updated: {0} {1}", package.Name, package.Version); - - PluginUpdated?.Invoke(this, package); - } - - _applicationHost.NotifyPendingRestart(); + return plugin != null; } private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken) @@ -438,7 +410,7 @@ namespace Emby.Server.Implementations.Updates _config.SaveConfiguration(); } - PluginUninstalled?.Invoke(this, plugin); + _eventManager.Publish(new PluginUninstalledEventArgs(plugin)); _applicationHost.NotifyPendingRestart(); } diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 4b4030bc27..1b38abb356 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -11,29 +11,6 @@ namespace MediaBrowser.Common.Updates { public interface IInstallationManager : IDisposable { - event EventHandler PackageInstalling; - - event EventHandler PackageInstallationCompleted; - - event EventHandler PackageInstallationFailed; - - event EventHandler PackageInstallationCancelled; - - /// - /// Occurs when a plugin is uninstalled. - /// - event EventHandler PluginUninstalled; - - /// - /// Occurs when a plugin is updated. - /// - event EventHandler PluginUpdated; - - /// - /// Occurs when a plugin is installed. - /// - event EventHandler PluginInstalled; - /// /// Gets the completed installations. /// From e3fb7f426c969c0316b53fe3348367c949f71c66 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 11 Sep 2020 16:08:49 -0600 Subject: [PATCH 0016/1930] Migrate subtitle upload to Jellyfin.Api --- .../Controllers/SubtitleController.cs | 28 ++ .../Models/SubtitleDtos/UploadSubtitleDto.cs | 34 ++ MediaBrowser.Api/Subtitles/SubtitleService.cs | 355 ------------------ 3 files changed, 62 insertions(+), 355 deletions(-) create mode 100644 Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs delete mode 100644 MediaBrowser.Api/Subtitles/SubtitleService.cs diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 78c9d43981..944da237bf 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using Jellyfin.Api.Models.SubtitleDtos; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -317,6 +318,33 @@ namespace Jellyfin.Api.Controllers return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8")); } + /// + /// Upload an external subtitle file. + /// + /// The item the subtitle belongs to. + /// The request body. + /// Subtitle uploaded. + /// A . + [HttpPost("Videos/{itemId}/Subtitles")] + public async Task UploadSubtitle( + [FromRoute, Required] Guid itemId, + [FromBody, Required] UploadSubtitleDto body) + { + var video = (Video)_libraryManager.GetItemById(itemId); + var data = Convert.FromBase64String(body.Data); + await using var memoryStream = new MemoryStream(data); + await _subtitleManager.UploadSubtitle( + video, + new SubtitleResponse + { + Format = body.Format, + Language = body.Language, + IsForced = body.IsForced, + Stream = memoryStream + }).ConfigureAwait(false); + return NoContent(); + } + /// /// Encodes a subtitle in the specified format. /// diff --git a/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs b/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs new file mode 100644 index 0000000000..30473255e8 --- /dev/null +++ b/Jellyfin.Api/Models/SubtitleDtos/UploadSubtitleDto.cs @@ -0,0 +1,34 @@ +using System.ComponentModel.DataAnnotations; + +namespace Jellyfin.Api.Models.SubtitleDtos +{ + /// + /// Upload subtitles dto. + /// + public class UploadSubtitleDto + { + /// + /// Gets or sets the subtitle language. + /// + [Required] + public string Language { get; set; } = string.Empty; + + /// + /// Gets or sets the subtitle format. + /// + [Required] + public string Format { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether the subtitle is forced. + /// + [Required] + public bool IsForced { get; set; } + + /// + /// Gets or sets the subtitle data. + /// + [Required] + public string Data { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/MediaBrowser.Api/Subtitles/SubtitleService.cs b/MediaBrowser.Api/Subtitles/SubtitleService.cs deleted file mode 100644 index ed2533f6d4..0000000000 --- a/MediaBrowser.Api/Subtitles/SubtitleService.cs +++ /dev/null @@ -1,355 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Controller.Subtitles; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Services; -using Microsoft.Extensions.Logging; -using MimeTypes = MediaBrowser.Model.Net.MimeTypes; - -namespace MediaBrowser.Api.Subtitles -{ - [Route("/Videos/{Id}/Subtitles/{Index}", "DELETE", Summary = "Deletes an external subtitle file")] - [Authenticated(Roles = "Admin")] - public class DeleteSubtitle - { - /// - /// Gets or sets the id. - /// - /// The id. - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")] - public Guid Id { get; set; } - - [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "DELETE")] - public int Index { get; set; } - } - - [Route("/Videos/{Id}/Subtitles", "POST", Summary = "Upload an external subtitle file")] - [Authenticated(Roles = "admin")] - public class PostSubtitle : IReturnVoid - { - /// - /// Gets or sets the id. - /// - /// The id. - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string Id { get; set; } - - [ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string Language { get; set; } - - [ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string Format { get; set; } - - [ApiMember(Name = "IsForced", Description = "IsForced", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string IsForced { get; set; } - - [ApiMember(Name = "Data", Description = "Data", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string Data { get; set; } - - } - - [Route("/Items/{Id}/RemoteSearch/Subtitles/{Language}", "GET")] - [Authenticated] - public class SearchRemoteSubtitles : IReturn - { - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public Guid Id { get; set; } - - [ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string Language { get; set; } - - public bool? IsPerfectMatch { get; set; } - } - - [Route("/Items/{Id}/RemoteSearch/Subtitles/{SubtitleId}", "POST")] - [Authenticated] - public class DownloadRemoteSubtitles : IReturnVoid - { - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public Guid Id { get; set; } - - [ApiMember(Name = "SubtitleId", Description = "SubtitleId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")] - public string SubtitleId { get; set; } - } - - [Route("/Providers/Subtitles/Subtitles/{Id}", "GET")] - [Authenticated] - public class GetRemoteSubtitles : IReturnVoid - { - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string Id { get; set; } - } - - [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")] - [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/{StartPositionTicks}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")] - public class GetSubtitle - { - /// - /// Gets or sets the id. - /// - /// The id. - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public Guid Id { get; set; } - - [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string MediaSourceId { get; set; } - - [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")] - public int Index { get; set; } - - [ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string Format { get; set; } - - [ApiMember(Name = "StartPositionTicks", Description = "StartPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] - public long StartPositionTicks { get; set; } - - [ApiMember(Name = "EndPositionTicks", Description = "EndPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] - public long? EndPositionTicks { get; set; } - - [ApiMember(Name = "CopyTimestamps", Description = "CopyTimestamps", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] - public bool CopyTimestamps { get; set; } - public bool AddVttTimeMap { get; set; } - } - - [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/subtitles.m3u8", "GET", Summary = "Gets an HLS subtitle playlist.")] - [Authenticated] - public class GetSubtitlePlaylist - { - /// - /// Gets or sets the id. - /// - /// The id. - [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string Id { get; set; } - - [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")] - public string MediaSourceId { get; set; } - - [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")] - public int Index { get; set; } - - [ApiMember(Name = "SegmentLength", Description = "The subtitle srgment length", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")] - public int SegmentLength { get; set; } - } - - public class SubtitleService : BaseApiService - { - private readonly ILibraryManager _libraryManager; - private readonly ISubtitleManager _subtitleManager; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IMediaSourceManager _mediaSourceManager; - private readonly IProviderManager _providerManager; - private readonly IFileSystem _fileSystem; - private readonly IAuthorizationContext _authContext; - - public SubtitleService( - ILogger logger, - IServerConfigurationManager serverConfigurationManager, - IHttpResultFactory httpResultFactory, - ILibraryManager libraryManager, - ISubtitleManager subtitleManager, - ISubtitleEncoder subtitleEncoder, - IMediaSourceManager mediaSourceManager, - IProviderManager providerManager, - IFileSystem fileSystem, - IAuthorizationContext authContext) - : base(logger, serverConfigurationManager, httpResultFactory) - { - _libraryManager = libraryManager; - _subtitleManager = subtitleManager; - _subtitleEncoder = subtitleEncoder; - _mediaSourceManager = mediaSourceManager; - _providerManager = providerManager; - _fileSystem = fileSystem; - _authContext = authContext; - } - - public async Task Get(GetSubtitlePlaylist request) - { - var item = (Video)_libraryManager.GetItemById(new Guid(request.Id)); - - var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false); - - var builder = new StringBuilder(); - - var runtime = mediaSource.RunTimeTicks ?? -1; - - if (runtime <= 0) - { - throw new ArgumentException("HLS Subtitles are not supported for this media."); - } - - var segmentLengthTicks = TimeSpan.FromSeconds(request.SegmentLength).Ticks; - if (segmentLengthTicks <= 0) - { - throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)"); - } - - builder.AppendLine("#EXTM3U"); - builder.AppendLine("#EXT-X-TARGETDURATION:" + request.SegmentLength.ToString(CultureInfo.InvariantCulture)); - builder.AppendLine("#EXT-X-VERSION:3"); - builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0"); - builder.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD"); - - long positionTicks = 0; - - var accessToken = _authContext.GetAuthorizationInfo(Request).Token; - - while (positionTicks < runtime) - { - var remaining = runtime - positionTicks; - var lengthTicks = Math.Min(remaining, segmentLengthTicks); - - builder.AppendLine("#EXTINF:" + TimeSpan.FromTicks(lengthTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture) + ","); - - var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks); - - var url = string.Format("stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}", - positionTicks.ToString(CultureInfo.InvariantCulture), - endPositionTicks.ToString(CultureInfo.InvariantCulture), - accessToken); - - builder.AppendLine(url); - - positionTicks += segmentLengthTicks; - } - - builder.AppendLine("#EXT-X-ENDLIST"); - - return ResultFactory.GetResult(Request, builder.ToString(), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary()); - } - - public async Task Get(GetSubtitle request) - { - if (string.Equals(request.Format, "js", StringComparison.OrdinalIgnoreCase)) - { - request.Format = "json"; - } - if (string.IsNullOrEmpty(request.Format)) - { - var item = (Video)_libraryManager.GetItemById(request.Id); - - var idString = request.Id.ToString("N", CultureInfo.InvariantCulture); - var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false, null) - .First(i => string.Equals(i.Id, request.MediaSourceId ?? idString)); - - var subtitleStream = mediaSource.MediaStreams - .First(i => i.Type == MediaStreamType.Subtitle && i.Index == request.Index); - - return await ResultFactory.GetStaticFileResult(Request, subtitleStream.Path).ConfigureAwait(false); - } - - if (string.Equals(request.Format, "vtt", StringComparison.OrdinalIgnoreCase) && request.AddVttTimeMap) - { - using var stream = await GetSubtitles(request).ConfigureAwait(false); - using var reader = new StreamReader(stream); - - var text = reader.ReadToEnd(); - - text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000"); - - return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format)); - } - - return ResultFactory.GetResult(Request, await GetSubtitles(request).ConfigureAwait(false), MimeTypes.GetMimeType("file." + request.Format)); - } - - private Task GetSubtitles(GetSubtitle request) - { - var item = _libraryManager.GetItemById(request.Id); - - return _subtitleEncoder.GetSubtitles(item, - request.MediaSourceId, - request.Index, - request.Format, - request.StartPositionTicks, - request.EndPositionTicks ?? 0, - request.CopyTimestamps, - CancellationToken.None); - } - - public async Task Get(SearchRemoteSubtitles request) - { - var video = (Video)_libraryManager.GetItemById(request.Id); - - return await _subtitleManager.SearchSubtitles(video, request.Language, request.IsPerfectMatch, CancellationToken.None).ConfigureAwait(false); - } - - public Task Delete(DeleteSubtitle request) - { - var item = _libraryManager.GetItemById(request.Id); - return _subtitleManager.DeleteSubtitles(item, request.Index); - } - - public void Post(PostSubtitle request) - { - var video = (Video)_libraryManager.GetItemById(request.Id); - - var bytes = Convert.FromBase64String(request.Data); - var memoryStream = new MemoryStream(bytes) - { - Position = 0 - }; - - Task.Run(async () => - { - try - { - await _subtitleManager.UploadSubtitle(video, new SubtitleResponse { - Format = request.Format, - Language = request.Language, - IsForced = Convert.ToBoolean(request.IsForced), - Stream = memoryStream - }).ConfigureAwait(false); - - _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error uploading subtitle"); - } - }); - } - - public async Task Get(GetRemoteSubtitles request) - { - var result = await _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).ConfigureAwait(false); - - return ResultFactory.GetResult(Request, result.Stream, MimeTypes.GetMimeType("file." + result.Format)); - } - - public void Post(DownloadRemoteSubtitles request) - { - var video = (Video)_libraryManager.GetItemById(request.Id); - - Task.Run(async () => - { - try - { - await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None) - .ConfigureAwait(false); - - _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error downloading subtitles"); - } - }); - } - } -} From 97e948bbf6405c65d711aca6cd9d9febae95e8ff Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 11 Sep 2020 16:11:19 -0600 Subject: [PATCH 0017/1930] Fix added warnings --- MediaBrowser.Controller/Subtitles/ISubtitleManager.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs index 8537a7ef47..feb26bc101 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs @@ -56,6 +56,9 @@ namespace MediaBrowser.Controller.Subtitles /// /// Upload new subtitle. /// + /// The video the subtitle belongs to. + /// The subtitle response. + /// A representing the asynchronous operation. Task UploadSubtitle(Video video, SubtitleResponse response); /// From dfbe4413ff89aced08dae1222a82468e6d322b43 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 11 Sep 2020 16:13:15 -0600 Subject: [PATCH 0018/1930] Fix added warnings --- MediaBrowser.Providers/Subtitles/SubtitleManager.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 30f390dcf5..f4a58775db 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -177,8 +177,7 @@ namespace MediaBrowser.Providers.Subtitles public async Task UploadSubtitle(Video video, SubtitleResponse response) { var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video); - - await TrySaveSubtitle(video, libraryOptions, response); + await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false); } private async Task TrySaveSubtitle( From 9ef79d190b2490a03c566bfaaf963fbba7d124a9 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sat, 12 Sep 2020 16:41:37 +0100 Subject: [PATCH 0019/1930] Large number of files --- Emby.Dlna/Main/DlnaEntryPoint.cs | 42 +- Emby.Dlna/PlayTo/PlayToManager.cs | 10 +- .../ApplicationHost.cs | 220 +-- .../Emby.Server.Implementations.csproj | 2 +- .../LiveTv/LiveTvMediaSourceProvider.cs | 2 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 1 + .../HdHomerun/HdHomerunUdpStream.cs | 3 +- .../LiveTv/TunerHosts/M3UTunerHost.cs | 1 + .../Networking/NetworkManager.cs | 556 -------- Emby.Server.Implementations/Udp/UdpServer.cs | 2 +- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 3 +- .../DefaultAuthorizationHandler.cs | 3 +- .../Auth/DownloadPolicy/DownloadHandler.cs | 3 +- ...TimeOrIgnoreParentalControlSetupHandler.cs | 3 +- .../FirstTimeSetupOrDefaultHandler.cs | 1 + .../FirstTimeSetupOrElevatedHandler.cs | 1 + .../IgnoreParentalControlHandler.cs | 3 +- .../LocalAccessOrRequiresElevationHandler.cs | 3 +- .../LocalAccessPolicy/LocalAccessHandler.cs | 3 +- .../RequiresElevationHandler.cs | 1 + Jellyfin.Api/Controllers/SystemController.cs | 11 +- Jellyfin.Api/Controllers/UserController.cs | 3 +- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 3 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 3 +- .../Jellyfin.Networking.csproj | 39 + .../Manager/INetworkManager.cs | 189 +++ Jellyfin.Networking/Manager/NetworkManager.cs | 1203 +++++++++++++++++ .../Jellyfin.Server.Implementations.csproj | 1 + .../Users/UserManager.cs | 4 +- Jellyfin.Server/CoreAppHost.cs | 4 +- .../IpBasedAccessValidationMiddleware.cs | 37 +- .../Middleware/LanFilteringMiddleware.cs | 24 +- Jellyfin.Server/Program.cs | 67 +- MediaBrowser.Common/Net/INetworkManager.cs | 97 -- .../IServerApplicationHost.cs | 30 +- .../Configuration/PathSubstitution.cs | 19 + .../Configuration/ServerConfiguration.cs | 668 ++++----- MediaBrowser.sln | 34 +- RSSDP/RSSDP.csproj | 1 + RSSDP/SsdpCommunicationsServer.cs | 5 +- RSSDP/SsdpDevicePublisher.cs | 11 +- .../LocalAccessHandlerTests.cs | 3 +- .../JellyfinApplicationFactory.cs | 3 - 43 files changed, 1977 insertions(+), 1345 deletions(-) delete mode 100644 Emby.Server.Implementations/Networking/NetworkManager.cs create mode 100644 Jellyfin.Networking/Jellyfin.Networking.csproj create mode 100644 Jellyfin.Networking/Manager/INetworkManager.cs create mode 100644 Jellyfin.Networking/Manager/NetworkManager.cs delete mode 100644 MediaBrowser.Common/Net/INetworkManager.cs create mode 100644 MediaBrowser.Model/Configuration/PathSubstitution.cs diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 40c2cc0e0a..98f50c09af 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -2,12 +2,14 @@ using System; using System.Globalization; +using System.Linq; using System.Net.Http; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -25,6 +27,7 @@ using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using Microsoft.Extensions.Logging; +using NetworkCollection; using Rssdp; using Rssdp.Infrastructure; using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; @@ -134,20 +137,20 @@ namespace Emby.Dlna.Main { await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false); - await ReloadComponents().ConfigureAwait(false); + ReloadComponents(); _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated; } - private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) + private void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) { if (string.Equals(e.Key, "dlna", StringComparison.OrdinalIgnoreCase)) { - await ReloadComponents().ConfigureAwait(false); + ReloadComponents(); } } - private async Task ReloadComponents() + private void ReloadComponents() { var options = _config.GetDlnaConfiguration(); @@ -155,7 +158,7 @@ namespace Emby.Dlna.Main if (options.EnableServer) { - await StartDevicePublisher(options).ConfigureAwait(false); + StartDevicePublisher(options); } else { @@ -225,7 +228,7 @@ namespace Emby.Dlna.Main } } - public async Task StartDevicePublisher(Configuration.DlnaOptions options) + public void StartDevicePublisher(Configuration.DlnaOptions options) { if (!options.BlastAliveMessages) { @@ -245,7 +248,7 @@ namespace Emby.Dlna.Main SupportPnpRootDevice = false }; - await RegisterServerEndpoints().ConfigureAwait(false); + RegisterServerEndpoints(); _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); } @@ -255,39 +258,46 @@ namespace Emby.Dlna.Main } } - private async Task RegisterServerEndpoints() + private void RegisterServerEndpoints() { - var addresses = await _appHost.GetLocalIpAddresses(CancellationToken.None).ConfigureAwait(false); + var bindAddresses = _networkManager.GetInternalBindAddresses() + .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)); var udn = CreateUuid(_appHost.SystemId); - foreach (var address in addresses) + if (!bindAddresses.Any()) { - if (address.AddressFamily == AddressFamily.InterNetworkV6) + // No interfaces returned, so use loopback. + bindAddresses = _networkManager.GetLoopbacks(); + } + + foreach (var addr in bindAddresses) + { + if (addr.AddressFamily == AddressFamily.InterNetworkV6) { // Not supporting IPv6 right now continue; } // Limit to LAN addresses only - if (!_networkManager.IsAddressInSubnets(address, true, true)) + if (!_networkManager.IsInLocalNetwork(addr)) { continue; } var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); + _logger.LogInformation("Registering publisher for {0} on {1}", fullService, addr); var descriptorUri = "/dlna/" + udn + "/description.xml"; - var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri); + var uri = new Uri(_appHost.GetSmartApiUrl(addr.Address) + descriptorUri); var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri, // Must point to the URL that serves your devices UPnP description document. - Address = address, - SubnetMask = _networkManager.GetLocalIpSubnetMask(address), + Address = addr.Address, + SubnetMask = ((IPNetAddress)addr).Mask, // MIGRATION: This fields is going. FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 21877f121f..10887bf60d 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -177,15 +177,7 @@ namespace Emby.Dlna.PlayTo _sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName); - string serverAddress; - if (info.LocalIpAddress == null || info.LocalIpAddress.Equals(IPAddress.Any) || info.LocalIpAddress.Equals(IPAddress.IPv6Any)) - { - serverAddress = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - } - else - { - serverAddress = _appHost.GetLocalApiUrl(info.LocalIpAddress); - } + string serverAddress = _appHost.GetSmartApiUrl(info.LocalIpAddress); controller = new PlayToController( sessionInfo, diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 642e2fdbe9..cc04cb03f5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -46,6 +46,7 @@ using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; +using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; @@ -97,6 +98,7 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Plugins.TheTvdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -117,7 +119,6 @@ namespace Emby.Server.Implementations private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" }; private readonly IFileSystem _fileSystemManager; - private readonly INetworkManager _networkManager; private readonly IXmlSerializer _xmlSerializer; private readonly IStartupOptions _startupOptions; @@ -188,6 +189,11 @@ namespace Emby.Server.Implementations /// The plugins. public IReadOnlyList Plugins => _plugins; + /// + /// Gets the NetworkManager object. + /// + private readonly INetworkManager _networkManager; + /// /// Gets the logger factory. /// @@ -211,7 +217,7 @@ namespace Emby.Server.Implementations private readonly List _disposableParts = new List(); /// - /// Gets the configuration manager. + /// Gets or sets the configuration manager. /// /// The configuration manager. protected IConfigurationManager ConfigurationManager { get; set; } @@ -244,28 +250,25 @@ namespace Emby.Server.Implementations /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. public ApplicationHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, IFileSystem fileSystem, - INetworkManager networkManager, IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); ServiceCollection = serviceCollection; - _networkManager = networkManager; - networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; - ApplicationPaths = applicationPaths; LoggerFactory = loggerFactory; _fileSystemManager = fileSystem; ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); + _networkManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); + Logger = LoggerFactory.CreateLogger(); _startupOptions = options; @@ -278,8 +281,6 @@ namespace Emby.Server.Implementations fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); - _networkManager.NetworkChanged += OnNetworkChanged; - CertificateInfo = new CertificateInfo { Path = ServerConfigurationManager.Configuration.CertificatePath, @@ -308,16 +309,6 @@ namespace Emby.Server.Implementations .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase); } - private string[] GetConfiguredLocalSubnets() - { - return ServerConfigurationManager.Configuration.LocalNetworkSubnets; - } - - private void OnNetworkChanged(object sender, EventArgs e) - { - _validAddressResults.Clear(); - } - /// public Version ApplicationVersion { get; } @@ -398,7 +389,7 @@ namespace Emby.Server.Implementations /// /// Resolves this instance. /// - /// The type + /// The type. /// ``0. public T Resolve() => ServiceProvider.GetService(); @@ -1091,13 +1082,10 @@ namespace Emby.Server.Implementations /// /// Gets the system status. /// - /// The cancellation token. + /// Where this request originated. /// SystemInfo. - public async Task GetSystemInfo(CancellationToken cancellationToken) + public SystemInfo GetSystemInfo(IPAddress source) { - var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - var transcodingTempPath = ConfigurationManager.GetTranscodePath(); - return new SystemInfo { HasPendingRestart = HasPendingRestart, @@ -1117,9 +1105,9 @@ namespace Emby.Server.Implementations CanSelfRestart = CanSelfRestart, CanLaunchWebBrowser = CanLaunchWebBrowser, HasUpdateAvailable = HasUpdateAvailable, - TranscodingTempPath = transcodingTempPath, + TranscodingTempPath = ConfigurationManager.GetTranscodePath(), ServerName = FriendlyName, - LocalAddress = localAddress, + LocalAddress = GetSmartApiUrl(source), SupportsLibraryMonitor = true, EncoderLocation = _mediaEncoder.EncoderLocation, SystemArchitecture = RuntimeInformation.OSArchitecture, @@ -1132,10 +1120,8 @@ namespace Emby.Server.Implementations .Select(i => new WakeOnLanInfo(i)) .ToList(); - public async Task GetPublicSystemInfo(CancellationToken cancellationToken) + public PublicSystemInfo GetPublicSystemInfo(IPAddress source) { - var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - return new PublicSystemInfo { Version = ApplicationVersionString, @@ -1143,8 +1129,8 @@ namespace Emby.Server.Implementations Id = SystemId, OperatingSystem = OperatingSystem.Id.ToString(), ServerName = FriendlyName, - LocalAddress = localAddress, - StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted + LocalAddress = GetSmartApiUrl(source), + StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted }; } @@ -1152,186 +1138,51 @@ namespace Emby.Server.Implementations public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps; /// - public async Task GetLocalApiUrl(CancellationToken cancellationToken) + public string GetSmartApiUrl(object source) { - try + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) { - // Return the first matched address, if found, or the first known local address - var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false); - if (addresses.Count == 0) - { - return null; - } - - return GetLocalApiUrl(addresses[0]); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error getting local Ip address information"); + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); } - return null; - } + string smart = _networkManager.GetBindInterface(source, out int? port); - /// - /// Removes the scope id from IPv6 addresses. - /// - /// The IPv6 address. - /// The IPv6 address without the scope id. - private ReadOnlySpan RemoveScopeId(ReadOnlySpan address) - { - var index = address.IndexOf('%'); - if (index == -1) + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { - return address; + return smart.Trim('/'); } - return address.Slice(0, index); - } - - /// - public string GetLocalApiUrl(IPAddress ipAddress) - { - if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) - { - var str = RemoveScopeId(ipAddress.ToString()); - Span span = new char[str.Length + 2]; - span[0] = '['; - str.CopyTo(span.Slice(1)); - span[^1] = ']'; - - return GetLocalApiUrl(span); - } - - return GetLocalApiUrl(ipAddress.ToString()); + return GetLocalApiUrl(smart.Trim('/'), source is HttpRequest request ? request.Scheme : null, port); } /// public string GetLoopbackHttpApiUrl() { + if (NetworkManager.IsIP6Enabled) + { + return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort); + } + return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort); } /// - public string GetLocalApiUrl(ReadOnlySpan host, string scheme = null, int? port = null) + public string GetLocalApiUrl(string host, string scheme = null, int? port = null) { // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does // not. For consistency, always trim the trailing slash. return new UriBuilder { Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp), - Host = host.ToString(), + Host = host, Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort), Path = ServerConfigurationManager.Configuration.BaseUrl }.ToString().TrimEnd('/'); } - public Task> GetLocalIpAddresses(CancellationToken cancellationToken) - { - return GetLocalIpAddressesInternal(true, 0, cancellationToken); - } - - private async Task> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken) - { - var addresses = ServerConfigurationManager - .Configuration - .LocalNetworkAddresses - .Select(x => NormalizeConfiguredLocalAddress(x)) - .Where(i => i != null) - .ToList(); - - if (addresses.Count == 0) - { - addresses.AddRange(_networkManager.GetLocalIpAddresses()); - } - - var resultList = new List(); - - foreach (var address in addresses) - { - if (!allowLoopback) - { - if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback)) - { - continue; - } - } - - if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false)) - { - resultList.Add(address); - - if (limit > 0 && resultList.Count >= limit) - { - return resultList; - } - } - } - - return resultList; - } - - public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan address) - { - var index = address.Trim('/').IndexOf('/'); - if (index != -1) - { - address = address.Slice(index + 1); - } - - if (IPAddress.TryParse(address.Trim('/'), out IPAddress result)) - { - return result; - } - - return null; - } - - private readonly ConcurrentDictionary _validAddressResults = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - private async Task IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken) - { - if (address.Equals(IPAddress.Loopback) - || address.Equals(IPAddress.IPv6Loopback)) - { - return true; - } - - var apiUrl = GetLocalApiUrl(address) + "/system/ping"; - - if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult)) - { - return cachedResult; - } - - try - { - using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); - using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); - var result = await System.Text.Json.JsonSerializer.DeserializeAsync(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); - var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); - - _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid); - Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid); - return valid; - } - catch (OperationCanceledException) - { - Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); - throw; - } - catch (Exception ex) - { - Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false); - - _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); - return false; - } - } - public string FriendlyName => string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) ? Environment.MachineName @@ -1486,6 +1337,7 @@ namespace Emby.Server.Implementations _disposed = true; } + } internal class CertificateInfo diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 0a348f0d00..db81167433 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -36,7 +36,7 @@ - + diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 8a0c0043a9..598cf0af7c 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -76,7 +76,7 @@ namespace Emby.Server.Implementations.LiveTv } var list = sources.ToList(); - var serverUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + var serverUrl = _appHost.GetSmartApiUrl(string.Empty); foreach (var source in list) { diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 28e30fac8b..1cf129ad2d 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -10,6 +10,7 @@ using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 6730751d50..02ee302d0d 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,6 +7,7 @@ using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; @@ -57,7 +58,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var mediaSource = OriginalMediaSource; var uri = new Uri(mediaSource.Path); - var localPort = _networkManager.GetRandomUnusedUdpPort(); + var localPort = 50000; // Will return to random after next PR. Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath)); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index 8107bc427b..f297ecd5df 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs deleted file mode 100644 index 089ec30e6b..0000000000 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ /dev/null @@ -1,556 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using Microsoft.Extensions.Logging; - -namespace Emby.Server.Implementations.Networking -{ - /// - /// Class to take care of network interface management. - /// - public class NetworkManager : INetworkManager - { - private readonly ILogger _logger; - - private IPAddress[] _localIpAddresses; - private readonly object _localIpAddressSyncLock = new object(); - - private readonly object _subnetLookupLock = new object(); - private readonly Dictionary> _subnetLookup = new Dictionary>(StringComparer.Ordinal); - - private List _macAddresses; - - /// - /// Initializes a new instance of the class. - /// - /// Logger to use for messages. - public NetworkManager(ILogger logger) - { - _logger = logger; - - NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; - NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; - } - - /// - public event EventHandler NetworkChanged; - - /// - public Func LocalSubnetsFn { get; set; } - - private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) - { - _logger.LogDebug("NetworkAvailabilityChanged"); - OnNetworkChanged(); - } - - private void OnNetworkAddressChanged(object sender, EventArgs e) - { - _logger.LogDebug("NetworkAddressChanged"); - OnNetworkChanged(); - } - - private void OnNetworkChanged() - { - lock (_localIpAddressSyncLock) - { - _localIpAddresses = null; - _macAddresses = null; - } - - NetworkChanged?.Invoke(this, EventArgs.Empty); - } - - /// - public IPAddress[] GetLocalIpAddresses() - { - lock (_localIpAddressSyncLock) - { - if (_localIpAddresses == null) - { - var addresses = GetLocalIpAddressesInternal().ToArray(); - - _localIpAddresses = addresses; - } - - return _localIpAddresses; - } - } - - private List GetLocalIpAddressesInternal() - { - var list = GetIPsDefault().ToList(); - - if (list.Count == 0) - { - list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList(); - } - - var listClone = new List(); - - var subnets = LocalSubnetsFn(); - - foreach (var i in list) - { - if (i.IsIPv6LinkLocal || i.ToString().StartsWith("169.254.", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (Array.IndexOf(subnets, $"[{i}]") == -1) - { - listClone.Add(i); - } - } - - return listClone - .OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1) - // .ThenBy(i => listClone.IndexOf(i)) - .GroupBy(i => i.ToString()) - .Select(x => x.First()) - .ToList(); - } - - /// - public bool IsInPrivateAddressSpace(string endpoint) - { - return IsInPrivateAddressSpace(endpoint, true); - } - - // Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address - private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets) - { - if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - // IPV6 - if (endpoint.Split('.').Length > 4) - { - // Handle ipv4 mapped to ipv6 - var originalEndpoint = endpoint; - endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase); - - if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - } - - // Private address space: - - if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - if (!IPAddress.TryParse(endpoint, out var ipAddress)) - { - return false; - } - - byte[] octet = ipAddress.GetAddressBytes(); - - if ((octet[0] == 10) || - (octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918 - (octet[0] == 192 && octet[1] == 168) || // RFC1918 - (octet[0] == 127) || // RFC1122 - (octet[0] == 169 && octet[1] == 254)) // RFC3927 - { - return true; - } - - if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint)) - { - return true; - } - - return false; - } - - /// - public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint) - { - if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase)) - { - var endpointFirstPart = endpoint.Split('.')[0]; - - var subnets = GetSubnets(endpointFirstPart); - - foreach (var subnet_Match in subnets) - { - // logger.LogDebug("subnet_Match:" + subnet_Match); - - if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - } - - return false; - } - - // Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart - private List GetSubnets(string endpointFirstPart) - { - lock (_subnetLookupLock) - { - if (_subnetLookup.TryGetValue(endpointFirstPart, out var subnets)) - { - return subnets; - } - - subnets = new List(); - - foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces()) - { - foreach (var unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses) - { - if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && endpointFirstPart == unicastIPAddressInformation.Address.ToString().Split('.')[0]) - { - int subnet_Test = 0; - foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.')) - { - if (part.Equals("0", StringComparison.Ordinal)) - { - break; - } - - subnet_Test++; - } - - var subnet_Match = string.Join(".", unicastIPAddressInformation.Address.ToString().Split('.').Take(subnet_Test).ToArray()); - - // TODO: Is this check necessary? - if (adapter.OperationalStatus == OperationalStatus.Up) - { - subnets.Add(subnet_Match); - } - } - } - } - - _subnetLookup[endpointFirstPart] = subnets; - - return subnets; - } - } - - /// - public bool IsInLocalNetwork(string endpoint) - { - return IsInLocalNetworkInternal(endpoint, true); - } - - /// - public bool IsAddressInSubnets(string addressString, string[] subnets) - { - return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets); - } - - /// - public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC) - { - byte[] octet = address.GetAddressBytes(); - - if ((octet[0] == 127) || // RFC1122 - (octet[0] == 169 && octet[1] == 254)) // RFC3927 - { - // don't use on loopback or 169 interfaces - return false; - } - - string addressString = address.ToString(); - string excludeAddress = "[" + addressString + "]"; - var subnets = LocalSubnetsFn(); - - // Include any address if LAN subnets aren't specified - if (subnets.Length == 0) - { - return true; - } - - // Exclude any addresses if they appear in the LAN list in [ ] - if (Array.IndexOf(subnets, excludeAddress) != -1) - { - return false; - } - - return IsAddressInSubnets(address, addressString, subnets); - } - - /// - /// Checks if the give address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format. - /// - /// IPAddress version of the address. - /// The address to check. - /// If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address. - /// falseif the address isn't in the subnets, true otherwise. - private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets) - { - foreach (var subnet in subnets) - { - var normalizedSubnet = subnet.Trim(); - // Is the subnet a host address and does it match the address being passes? - if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - // Parse CIDR subnets and see if address falls within it. - if (normalizedSubnet.Contains('/', StringComparison.Ordinal)) - { - try - { - var ipNetwork = IPNetwork.Parse(normalizedSubnet); - if (ipNetwork.Contains(address)) - { - return true; - } - } - catch - { - // Ignoring - invalid subnet passed encountered. - } - } - } - - return false; - } - - private bool IsInLocalNetworkInternal(string endpoint, bool resolveHost) - { - if (string.IsNullOrEmpty(endpoint)) - { - throw new ArgumentNullException(nameof(endpoint)); - } - - if (IPAddress.TryParse(endpoint, out var address)) - { - var addressString = address.ToString(); - - var localSubnetsFn = LocalSubnetsFn; - if (localSubnetsFn != null) - { - var localSubnets = localSubnetsFn(); - foreach (var subnet in localSubnets) - { - // Only validate if there's at least one valid entry. - if (!string.IsNullOrWhiteSpace(subnet)) - { - return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false); - } - } - } - - int lengthMatch = 100; - if (address.AddressFamily == AddressFamily.InterNetwork) - { - lengthMatch = 4; - if (IsInPrivateAddressSpace(addressString, true)) - { - return true; - } - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - lengthMatch = 9; - if (IsInPrivateAddressSpace(endpoint, true)) - { - return true; - } - } - - // Should be even be doing this with ipv6? - if (addressString.Length >= lengthMatch) - { - var prefix = addressString.Substring(0, lengthMatch); - - if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) - { - return true; - } - } - } - else if (resolveHost) - { - if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out var uri)) - { - try - { - var host = uri.DnsSafeHost; - _logger.LogDebug("Resolving host {0}", host); - - address = GetIpAddresses(host).GetAwaiter().GetResult().FirstOrDefault(); - - if (address != null) - { - _logger.LogDebug("{0} resolved to {1}", host, address); - - return IsInLocalNetworkInternal(address.ToString(), false); - } - } - catch (InvalidOperationException) - { - // Can happen with reverse proxy or IIS url rewriting? - } - catch (Exception ex) - { - _logger.LogError(ex, "Error resolving hostname"); - } - } - } - - return false; - } - - private static Task GetIpAddresses(string hostName) - { - return Dns.GetHostAddressesAsync(hostName); - } - - private IEnumerable GetIPsDefault() - { - IEnumerable interfaces; - - try - { - interfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(x => x.OperationalStatus == OperationalStatus.Up - || x.OperationalStatus == OperationalStatus.Unknown); - } - catch (NetworkInformationException ex) - { - _logger.LogError(ex, "Error in GetAllNetworkInterfaces"); - return Enumerable.Empty(); - } - - return interfaces.SelectMany(network => - { - var ipProperties = network.GetIPProperties(); - - // Exclude any addresses if they appear in the LAN list in [ ] - - return ipProperties.UnicastAddresses - .Select(i => i.Address) - .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6); - }).GroupBy(i => i.ToString()) - .Select(x => x.First()); - } - - private static async Task> GetLocalIpAddressesFallback() - { - var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false); - - // Reverse them because the last one is usually the correct one - // It's not fool-proof so ultimately the consumer will have to examine them and decide - return host.AddressList - .Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6) - .Reverse(); - } - - /// - /// Gets a random port number that is currently available. - /// - /// System.Int32. - public int GetRandomUnusedTcpPort() - { - var listener = new TcpListener(IPAddress.Any, 0); - listener.Start(); - var port = ((IPEndPoint)listener.LocalEndpoint).Port; - listener.Stop(); - return port; - } - - /// - public int GetRandomUnusedUdpPort() - { - var localEndPoint = new IPEndPoint(IPAddress.Any, 0); - using (var udpClient = new UdpClient(localEndPoint)) - { - return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - } - } - - /// - public List GetMacAddresses() - { - return _macAddresses ??= GetMacAddressesInternal().ToList(); - } - - private static IEnumerable GetMacAddressesInternal() - => NetworkInterface.GetAllNetworkInterfaces() - .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback) - .Select(x => x.GetPhysicalAddress()) - .Where(x => !x.Equals(PhysicalAddress.None)); - - /// - public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask) - { - IPAddress network1 = GetNetworkAddress(address1, subnetMask); - IPAddress network2 = GetNetworkAddress(address2, subnetMask); - return network1.Equals(network2); - } - - private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) - { - byte[] ipAdressBytes = address.GetAddressBytes(); - byte[] subnetMaskBytes = subnetMask.GetAddressBytes(); - - if (ipAdressBytes.Length != subnetMaskBytes.Length) - { - throw new ArgumentException("Lengths of IP address and subnet mask do not match."); - } - - byte[] broadcastAddress = new byte[ipAdressBytes.Length]; - for (int i = 0; i < broadcastAddress.Length; i++) - { - broadcastAddress[i] = (byte)(ipAdressBytes[i] & subnetMaskBytes[i]); - } - - return new IPAddress(broadcastAddress); - } - - /// - public IPAddress GetLocalIpSubnetMask(IPAddress address) - { - NetworkInterface[] interfaces; - - try - { - var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown }; - - interfaces = NetworkInterface.GetAllNetworkInterfaces() - .Where(i => validStatuses.Contains(i.OperationalStatus)) - .ToArray(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in GetAllNetworkInterfaces"); - return null; - } - - foreach (NetworkInterface ni in interfaces) - { - foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) - { - if (ip.Address.Equals(address) && ip.IPv4Mask != null) - { - return ip.IPv4Mask; - } - } - } - - return null; - } - } -} diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index b7a59cee2d..3dc34da5cf 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Udp { string localUrl = !string.IsNullOrEmpty(_config[AddressOverrideConfigKey]) ? _config[AddressOverrideConfigKey] - : await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + : _appHost.GetSmartApiUrl(string.Empty); // MIGRATION: Temp value. if (!string.IsNullOrEmpty(localUrl)) { diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index d732b6bc6a..08746b346b 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,6 +1,7 @@ -using System.Security.Claims; +using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index b5913daab9..69e6a8fb2d 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs index b61680ab1a..d1297119cd 100644 --- a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs +++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs index 31482a930f..53b5d47787 100644 --- a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs index 9815e252ee..abdf2858d0 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs index decbe0c035..ada8a0d4ec 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs index 5213bc4cb7..475e3cdac4 100644 --- a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs +++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index 14722aa57e..d022c9067f 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -1,5 +1,6 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Jellyfin.Api.Constants; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs index af73352bcc..418d63de68 100644 --- a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs index b235c4b63b..a1cddbca3e 100644 --- a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs @@ -1,5 +1,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 4cb1984a2f..6876b47b44 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; @@ -8,6 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -64,9 +65,9 @@ namespace Jellyfin.Api.Controllers [HttpGet("Info")] [Authorize(Policy = Policies.FirstTimeSetupOrIgnoreParentalControl)] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> GetSystemInfo() + public ActionResult GetSystemInfo() { - return await _appHost.GetSystemInfo(CancellationToken.None).ConfigureAwait(false); + return _appHost.GetSystemInfo(Request.HttpContext.Connection.RemoteIpAddress); } /// @@ -76,9 +77,9 @@ namespace Jellyfin.Api.Controllers /// A with public info about the system. [HttpGet("Info/Public")] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> GetPublicSystemInfo() + public ActionResult GetPublicSystemInfo() { - return await _appHost.GetPublicSystemInfo(CancellationToken.None).ConfigureAwait(false); + return _appHost.GetPublicSystemInfo(Request.HttpContext.Connection.RemoteIpAddress); } /// diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 630e9df6ac..152e650bc0 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; @@ -7,6 +7,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.UserDtos; using Jellyfin.Data.Enums; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index af0519ffa8..3be8734b94 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -8,6 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 1207fb5134..d63e3ab118 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Linq; using System.Text.Json; @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj new file mode 100644 index 0000000000..b6834cb0ee --- /dev/null +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -0,0 +1,39 @@ + + + Jellyfin.Networking + Library + netstandard2.1 + false + true + true + enable + + + + + + + + + + + + + + + ../jellyfin.ruleset + + + + + + + + + + + + + + + diff --git a/Jellyfin.Networking/Manager/INetworkManager.cs b/Jellyfin.Networking/Manager/INetworkManager.cs new file mode 100644 index 0000000000..ba571750b9 --- /dev/null +++ b/Jellyfin.Networking/Manager/INetworkManager.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.NetworkInformation; +using MediaBrowser.Model.Configuration; +using NetworkCollection; + +namespace Jellyfin.Networking.Manager +{ + /// + /// Interface for the NetworkManager class. + /// + public interface INetworkManager + { + /// + /// Event triggered on network changes. + /// + event EventHandler NetworkChanged; + + /// + /// Gets the Published server override list. + /// + Dictionary PublishedServerOverrides { get; } + + /// + /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// + public bool TrustAllIP6Interfaces { get; } + + /// + /// Gets returns the remote address filter. + /// + NetCollection RemoteAddressFilter { get; } + + /// + /// Calculates the list of interfaces to use for Kestrel. + /// + /// A NetCollection object containing all the interfaces to bind. + /// If all the interfaces are specified, and none are excluded, it returns zero items + /// to represent any address. + NetCollection GetAllBindInterfaces(); + + /// + /// Returns a collection containing the loopback interfaces. + /// + /// Netcollection. + public NetCollection GetLoopbacks(); + + /// + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// The priority of selection is as follows:- + /// + /// The value contained in the startup parameter --published-server-url. + /// + /// If the user specified custom subnet overrides, the correct subnet for the source address. + /// + /// If the user specified bind interfaces to use:- + /// The bind interface that contains the source subnet. + /// The first bind interface specified that suits best first the source's endpoint. eg. external or internal. + /// + /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:- + /// The first public interface that isn't a loopback and contains the source subnet. + /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways. + /// An internal interface if there are no public ip addresses. + /// + /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:- + /// The first private interface that contains the source subnet. + /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways. + /// + /// If no interfaces meet any of these criteria, then a loopback address is returned. + /// + /// Interface that have been specifically excluded from binding are not used in any of the calculations. + /// + /// Source of the request. + /// Optional port returned, if it's part of an override. + /// IP Address to use, or loopback address if all else fails. + string GetBindInterface(object? source, out int? port); + + /// + /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. + /// + /// IP address to check. + /// True if it is. + bool IsExcludedInterface(IPAddress address); + + /// + /// Get a list of all the MAC addresses associated with active interfaces. + /// + /// List of MAC addresses. + List GetMacAddresses(); + + /// + /// Checks to see if the IP Address provided matches an interface that has a gateway. + /// + /// IP to check. Can be an IPAddress or an IPObject. + /// Result of the check. + public bool IsGatewayInterface(object? addressObj); + + /// + /// Returns true if the address is a private address. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// + /// Address to check. + /// True or False. + bool IsPrivateAddressRange(IPObject address); + + /// + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// + /// IP to check. + /// True if endpoint is within the LAN range. + bool IsInLocalNetwork(string address); + + /// + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// + /// IP to check. + /// True if endpoint is within the LAN range. + bool IsInLocalNetwork(IPObject address); + + /// + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// + /// IP to check. + /// True if endpoint is within the LAN range. + bool IsInLocalNetwork(IPAddress address); + + /// + /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes. + /// eg. "eth1", or "TP-LINK Wireless USB Adapter". + /// + /// Token to parse. + /// Resultant object if successful. + /// Success of the operation. + bool TryParseInterface(string token, out IPNetAddress result); + + /// + /// Parses an array of strings into a NetCollection. + /// + /// Values to parse. + /// When true, only include values in []. When false, ignore bracketed values. + /// IPCollection object containing the value strings. + NetCollection CreateIPCollection(string[] values, bool bracketed = false); + + /// + /// Returns all the internal Bind interface addresses. + /// + /// An internal list of interfaces addresses. + NetCollection GetInternalBindAddresses(); + + /// + /// Checks to see if an IP address is still a valid interface address. + /// + /// IP address to check. + /// True if it is. + bool IsValidInterfaceAddress(IPAddress address); + + /// + /// Returns true if the IP address is in the excluded list. + /// + /// IP to check. + /// True if excluded. + bool IsExcluded(IPAddress ip); + + /// + /// Returns true if the IP address is in the excluded list. + /// + /// IP to check. + /// True if excluded. + bool IsExcluded(EndPoint ip); + + /// + /// Gets the filtered LAN ip addresses. + /// + /// Optional filter for the list. + /// Returns a filtered list of LAN addresses. + NetCollection GetFilteredLANSubnets(NetCollection? filter = null); + + /// + /// Reloads all settings and re-initialises the instance. + /// + /// to use. + public void UpdateSettings(ServerConfiguration config); + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs new file mode 100644 index 0000000000..36a0a94a09 --- /dev/null +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -0,0 +1,1203 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Configuration; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using NetworkCollection; + +namespace Jellyfin.Networking.Manager +{ + /// + /// Class to take care of network interface management. + /// + public class NetworkManager : INetworkManager, IDisposable + { + private static NetworkManager? _instance; + + /// + /// Contains the description of the interface along with its index. + /// + private readonly SortedList _interfaceNames; + + /// + /// Threading lock for network interfaces. + /// + private readonly object _intLock = new object(); + + /// + /// List of all interface addresses and masks. + /// + private readonly NetCollection _interfaceAddresses; + + /// + /// List of all interface MAC addresses. + /// + private readonly List _macAddresses; + + private readonly ILogger _logger; + + private readonly IConfigurationManager _configurationManager; + + /// + /// Holds the bind address overrides. + /// + private readonly Dictionary _overrideUrls; + + /// + /// Used to stop "event-racing conditions". + /// + private bool _eventfire; + + /// + /// Unfiltered user defined LAN subnets. (Configuration.LocalNetworkSubnets). + /// or internal interface network subnets if undefined by user. + /// + private NetCollection _lanSubnets; + + /// + /// User defined list of subnets to excluded from the LAN. + /// + private NetCollection _excludedSubnets; + + /// + /// List of interface addresses to bind the WS. + /// + private NetCollection _bindAddresses; + + /// + /// List of interface addresses to exclude from bind. + /// + private NetCollection _bindExclusions; + + /// + /// Caches list of all internal filtered interface addresses and masks. + /// + private NetCollection _internalInterfaces; + + /// + /// Flag set when no custom LAN has been defined in the config. + /// + private bool _usingPrivateAddresses; + + /// + /// True if this object is disposed. + /// + private bool _disposed; + + /// + /// Initializes a new instance of the class. + /// + /// IServerConfigurationManager instance. + /// Logger to use for messages. +#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in InitialiseLAN function. Compiler doesn't yet recognise this. + public NetworkManager(IConfigurationManager configurationManager, ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); + + _interfaceAddresses = new NetCollection(unique: false); + _macAddresses = new List(); + _interfaceNames = new SortedList(); + _overrideUrls = new Dictionary(); + + UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); + if (!IsIP6Enabled && !IsIP4Enabled) + { + throw new ApplicationException("IPv4 and IPv6 cannot both be disabled."); + } + + NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; + NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; + + _configurationManager.ConfigurationUpdated += ConfigurationUpdated; + + Instance = this; + } +#pragma warning restore CS8618 // Non-nullable field is uninitialized. + + /// + /// Event triggered on network changes. + /// + public event EventHandler? NetworkChanged; + + /// + /// Gets the singleton of this object. + /// + public static NetworkManager Instance + { + get => GetInstance(); + + internal set + { + _instance = value; + } + } + + /// + /// Gets the unique network location signature, which is updated on every network change. + /// + public static string NetworkLocationSignature { get; internal set; } = Guid.NewGuid().ToString(); + + /// + /// Gets a value indicating whether IP6 is enabled. + /// + public static bool IsIP6Enabled { get; internal set; } + + /// + /// Gets a value indicating whether IP4 is enabled. + /// + public static bool IsIP4Enabled { get; internal set; } = true; + + /// + /// Gets a value indicating whether is multi-socket binding available. + /// + public static bool EnableMultiSocketBinding { get; internal set; } = true; + + /// + /// Gets the number of times the network address has changed. + /// + public static int NetworkChangeCount { get; internal set; } = 1; + + /// + public NetCollection RemoteAddressFilter { get; private set; } + + /// + /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// + public bool TrustAllIP6Interfaces { get; internal set; } + + /// + /// Gets the Published server override list. + /// + public Dictionary PublishedServerOverrides => _overrideUrls; + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + public List GetMacAddresses() + { + // Populated in construction - so always has values. + lock (_intLock) + { + return _macAddresses.ToList(); + } + } + + /// + public bool IsGatewayInterface(object? addressObj) + { + var address = (addressObj is IPAddress addressIP) ? + addressIP : (addressObj is IPObject addressIPObj) ? + addressIPObj.Address : IPAddress.None; + + lock (_intLock) + { + return _internalInterfaces.Where(i => i.Address.Equals(address) && (i.Tag < 0)).Any(); + } + } + + /// + public NetCollection GetLoopbacks() + { + NetCollection nc = new NetCollection(); + if (IsIP4Enabled) + { + nc.Add(IPAddress.Loopback); + } + + if (IsIP6Enabled) + { + nc.Add(IPAddress.IPv6Loopback); + } + + return nc; + } + + /// + public bool IsExcluded(IPAddress ip) + { + return _excludedSubnets.Contains(ip); + } + + /// + public bool IsExcluded(EndPoint ip) + { + if (ip != null) + { + return _excludedSubnets.Contains(((IPEndPoint)ip).Address); + } + + return false; + } + + /// + public NetCollection CreateIPCollection(string[] values, bool bracketed = false) + { + NetCollection col = new NetCollection(); + if (values != null) + { + for (int a = 0; a < values.Length; a++) + { + string v = values[a].Trim(); + + try + { + if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) + { + if (bracketed) + { + AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); + } + } + else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) + { + if (bracketed) + { + AddToCollection(col, v.Substring(1)); + } + } + else if (!bracketed) + { + AddToCollection(col, v); + } + } + catch (ArgumentException e) + { + _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); + } + } + } + + return col; + } + + /// + public NetCollection GetAllBindInterfaces() + { + lock (_intLock) + { + int count = _bindAddresses.Count; + + if (count == 0) + { + if (_bindExclusions.Count > 0) + { + // Return all the interfaces except the ones specifically excluded. + return _interfaceAddresses.Exclude(_bindExclusions); + } + + // No bind address and no exclusions, so listen on all interfaces. + NetCollection result = new NetCollection(); + + if (IsIP4Enabled) + { + result.Add(IPAddress.Any); + } + + if (IsIP6Enabled) + { + result.Add(IPAddress.IPv6Any); + } + + return result; + } + + // Remove any excluded bind interfaces. + return _bindAddresses.Exclude(_bindExclusions); + } + } + + /// + public string GetBindInterface(object? source, out int? port) + { + bool chromeCast = false; + port = null; + // Parse the source object in an attempt to discover where the request originated. + IPObject sourceAddr; + if (source is HttpRequest sourceReq) + { + port = sourceReq.Host.Port; + if (IPHost.TryParse(sourceReq.Host.Host, out IPHost host)) + { + sourceAddr = host; + } + else + { + // Assume it's external, as we cannot resolve the host. + sourceAddr = IPHost.None; + } + } + else if (source is string sourceStr && !string.IsNullOrEmpty(sourceStr)) + { + if (string.Equals(sourceStr, "chromecast", StringComparison.OrdinalIgnoreCase)) + { + chromeCast = true; + // Just assign a variable so has source = true; + sourceAddr = IPNetAddress.IP4Loopback; + } + + if (IPHost.TryParse(sourceStr, out IPHost host)) + { + sourceAddr = host; + } + else + { + // Assume it's external, as we cannot resolve the host. + sourceAddr = IPHost.None; + } + } + else if (source is IPAddress sourceIP) + { + sourceAddr = new IPNetAddress(sourceIP); + } + else + { + // If we have no idea, then assume it came from an external address. + sourceAddr = IPHost.None; + } + + // Do we have a source? + bool haveSource = !sourceAddr.Address.Equals(IPAddress.None); + + if (haveSource) + { + if (!IsIP6Enabled && sourceAddr.AddressFamily == AddressFamily.InterNetworkV6) + { + _logger.LogWarning("IPv6 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); + } + + if (!IsIP4Enabled && sourceAddr.AddressFamily == AddressFamily.InterNetwork) + { + _logger.LogWarning("IPv4 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); + } + } + + bool isExternal = haveSource && !IsInLocalNetwork(sourceAddr); + + string bindPreference = string.Empty; + if (haveSource) + { + // Check for user override. + foreach (var addr in _overrideUrls) + { + // Remaining. Match anything. + if (addr.Key.Equals(IPAddress.Broadcast)) + { + bindPreference = addr.Value; + break; + } + else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && (isExternal || chromeCast)) + { + // External. + bindPreference = addr.Value; + break; + } + else if (addr.Key.Contains(sourceAddr)) + { + // Match ip address. + bindPreference = addr.Value; + break; + } + } + } + + _logger.LogDebug("GetBindInterface: Souce: {0}, External: {1}:", haveSource, isExternal); + + if (!string.IsNullOrEmpty(bindPreference)) + { + // Has it got a port defined? + var parts = bindPreference.Split(':'); + if (parts.Length > 1) + { + if (int.TryParse(parts[1], out int p)) + { + bindPreference = parts[0]; + port = p; + } + } + + _logger.LogInformation("{0}: Using BindAddress {1}:{2}", sourceAddr, bindPreference, port); + return bindPreference; + } + + string ipresult; + + // No preference given, so move on to bind addresses. + lock (_intLock) + { + var nc = _bindAddresses.Exclude(_bindExclusions).Where(p => !p.IsLoopback()); + + int count = nc.Count(); + if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses.Equals(IPAddress.IPv6Any))) + { + // Ignore IPAny addresses. + count = 0; + } + + if (count != 0) + { + // Check to see if any of the bind interfaces are in the same subnet. + + IEnumerable bindResult; + IPAddress? defaultGateway = null; + + if (isExternal) + { + // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. + bindResult = nc.Where(p => !IsInLocalNetwork(p)).OrderBy(p => p.Tag); + defaultGateway = bindResult.FirstOrDefault()?.Address; + bindResult = bindResult.Where(p => p.Contains(sourceAddr)).OrderBy(p => p.Tag); + } + else + { + // Look for the best internal address. + bindResult = nc.Where(p => IsInLocalNetwork(p) && p.Contains(sourceAddr)).OrderBy(p => p.Tag); + } + + if (bindResult.Any()) + { + ipresult = FormatIP6String(bindResult.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", sourceAddr, ipresult); + return ipresult; + } + + if (isExternal && defaultGateway != null) + { + ipresult = FormatIP6String(defaultGateway); + _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", sourceAddr, ipresult); + return ipresult; + } + + ipresult = FormatIP6String(nc.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", sourceAddr, ipresult); + + if (isExternal) + { + // TODO: remove this after testing. + _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", sourceAddr); + } + + return ipresult; + } + + if (isExternal) + { + // Get the first WAN interface address that isn't a loopback. + var extResult = _interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => !IsInLocalNetwork(p)) + .OrderBy(p => p.Tag); + + if (extResult.Any()) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in extResult) + { + if (!IsInLocalNetwork(intf) && intf.Contains(sourceAddr)) + { + ipresult = FormatIP6String(intf.Address); + _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", sourceAddr, ipresult); + return ipresult; + } + } + + ipresult = FormatIP6String(extResult.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", sourceAddr, ipresult); + return ipresult; + } + + // Have to return something, so return an internal address + + // TODO: remove this after testing. + _logger.LogWarning("{0}: External request received, however, no WAN interface found.", sourceAddr); + } + + // Get the first LAN interface address that isn't a loopback. + var result = _interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => IsInLocalNetwork(p)) + .OrderBy(p => p.Tag); + + if (result.Any()) + { + if (haveSource) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in result) + { + if (intf.Contains(sourceAddr)) + { + ipresult = FormatIP6String(intf.Address); + _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", sourceAddr, ipresult); + return ipresult; + } + } + } + + ipresult = FormatIP6String(result.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", sourceAddr, ipresult); + return ipresult; + } + + // There isn't any others, so we'll use the loopback. + ipresult = IsIP6Enabled ? "::" : "127.0.0.1"; + _logger.LogWarning("{0}: GetBindInterface: Loopback return.", sourceAddr, ipresult); + return ipresult; + } + } + + /// + public NetCollection GetInternalBindAddresses() + { + lock (_intLock) + { + int count = _bindAddresses.Count; + + if (count == 0) + { + if (_bindExclusions.Count > 0) + { + // Return all the internal interfaces except the ones excluded. + return new NetCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); + } + + // No bind address, so return all internal interfaces. + return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + } + + return new NetCollection(_bindAddresses.Where(p => !p.IsLoopback())); + } + } + + /// + public bool IsInLocalNetwork(IPObject address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.Equals(IPAddress.None)) + { + return false; + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + + lock (_intLock) + { + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); + } + } + + /// + public bool IsInLocalNetwork(string address) + { + if (IPHost.TryParse(address, out IPHost ep)) + { + lock (_intLock) + { + return _lanSubnets.Contains(ep) && !_excludedSubnets.Contains(ep); + } + } + + return false; + } + + /// + public bool IsInLocalNetwork(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + + lock (_intLock) + { + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); + } + } + + /// + public bool IsPrivateAddressRange(IPObject address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + else + { + return address.IsPrivateAddressRange(); + } + } + + /// + public bool IsExcludedInterface(IPAddress address) + { + lock (_intLock) + { + if (_bindExclusions.Count > 0) + { + return _bindExclusions.Contains(address); + } + + return false; + } + } + + /// + public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) + { + lock (_intLock) + { + if (filter == null) + { + return NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)); + } + + return _lanSubnets.Exclude(filter); + } + } + + /// + public bool IsValidInterfaceAddress(IPAddress address) + { + lock (_intLock) + { + return _interfaceAddresses.Contains(address); + } + } + + /// + public bool TryParseInterface(string token, out IPNetAddress result) + { + if (string.IsNullOrEmpty(token)) + { + result = IPNetAddress.None; + return false; + } + + if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) + { + _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); + + // Replace interface tags with the interface IP's. + foreach (IPNetAddress iface in _interfaceAddresses) + { + if (Math.Abs(iface.Tag) == index && + ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || + (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + { + result = iface; + return true; + } + } + } + + return IPNetAddress.TryParse(token, out result); + } + + /// + /// Reloads all settings and re-initialises the instance. + /// + /// to use. + public void UpdateSettings(ServerConfiguration config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + IsIP4Enabled = Socket.OSSupportsIPv6 && config.EnableIPV4; + IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; + TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; + EnableMultiSocketBinding = config.EnableMultiSocketBinding; + + InitialiseInterfaces(); + InitialiseLAN(config); + InitialiseBind(config); + InitialiseRemote(config); + InitialiseOverrides(config); + } + + /// + /// Protected implementation of Dispose pattern. + /// + /// True to dispose the managed state. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _configurationManager.ConfigurationUpdated -= ConfigurationUpdated; + NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; + NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; + } + + _disposed = true; + } + } + + private static NetworkManager GetInstance() + { + if (_instance == null) + { + throw new ApplicationException("NetworkManager is not initialised."); + } + + return _instance; + } + + private void ConfigurationUpdated(object? sender, EventArgs args) + { + UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); + } + + /// + /// Converts an IPAddress into a string. + /// Ipv6 addresses are returned in [ ], with their scope removed. + /// + /// Address to convert. + /// URI save conversion of the address. + private string FormatIP6String(IPAddress address) + { + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase); + + if (i != -1) + { + str = str.Substring(0, i); + } + + return $"[{str}]"; + } + + return str; + } + + /// + /// Parses strings into the collection, replacing any interface references. + /// + /// Collection. + /// String to parse. + private void AddToCollection(NetCollection col, string token) + { + // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. + // Null check required here for automated testing. + if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) + { + _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); + + // Replace interface tags with the interface IP's. + foreach (IPNetAddress iface in _interfaceAddresses) + { + if (Math.Abs(iface.Tag) == index && + ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || + (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + { + col.Add(iface); + } + } + } + else if (NetCollection.TryParse(token, out IPObject obj)) + { + if (!IsIP6Enabled) + { + // Remove IP6 addresses from multi-homed IPHosts. + obj.Remove(AddressFamily.InterNetworkV6); + if (!obj.IsIP6()) + { + col.Add(obj); + } + } + else if (!IsIP4Enabled) + { + // Remove IP4 addresses from multi-homed IPHosts. + obj.Remove(AddressFamily.InterNetwork); + if (obj.IsIP6()) + { + col.Add(obj); + } + } + else + { + col.Add(obj); + } + } + else + { + _logger.LogDebug("Invalid or unknown network {0}.", token); + } + } + + /// + /// Handler for network change events. + /// + /// Sender. + /// Network availablity information. + private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) + { + _logger.LogDebug("Network availability changed."); + OnNetworkChanged(); + } + + /// + /// Handler for network change events. + /// + /// Sender. + /// Event arguments. + private void OnNetworkAddressChanged(object? sender, EventArgs e) + { + _logger.LogDebug("Network address change detected."); + OnNetworkChanged(); + } + + /// + /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// + /// The network change async. + private async Task OnNetworkChangeAsync() + { + try + { + await Task.Delay(2000).ConfigureAwait(false); + InitialiseInterfaces(); + // Recalculate LAN caches. + InitialiseLAN((ServerConfiguration)_configurationManager.CommonConfiguration); + + NetworkChanged?.Invoke(this, EventArgs.Empty); + } + finally + { + _eventfire = false; + } + } + + /// + /// Triggers our event, and re-loads interface information. + /// + private void OnNetworkChanged() + { + // As per UPnP Device Architecture v1.0 Annex A - IPv6 Support. + NetworkLocationSignature = Guid.NewGuid().ToString(); + NetworkChangeCount++; + if (NetworkChangeCount > 99) + { + NetworkChangeCount = 1; + } + + if (!_eventfire) + { + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + _ = OnNetworkChangeAsync(); + } + } + + /// + /// Parses the user defined overrides into the dictionary object. + /// Overrides are the equivalent of localised publishedServerUrl, enabling + /// different addresses to be advertised over different subnets. + /// format is subnet=ipaddress|host|uri + /// when subnet = 0.0.0.0, any external address matches. + /// + private void InitialiseOverrides(ServerConfiguration config) + { + string[] overrides = config.PublishedServerUriBySubnet; + if (overrides == null) + { + lock (_intLock) + { + _overrideUrls.Clear(); + } + + return; + } + + lock (_intLock) + { + _overrideUrls.Clear(); + + foreach (var entry in overrides) + { + var parts = entry.Split('='); + if (parts.Length != 2) + { + _logger.LogError("Unable to parse bind override. {0}", entry); + } + else + { + var replacement = parts[1].Trim(); + if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase)) + { + _overrideUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; + } + else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + { + _overrideUrls[new IPNetAddress(IPAddress.Any)] = replacement; + } + else if (TryParseInterface(parts[0], out IPNetAddress address)) + { + _overrideUrls[address] = replacement; + } + else + { + _logger.LogError("Unable to parse bind ip address. {0}", parts[1]); + } + } + } + } + } + + private void InitialiseBind(ServerConfiguration config) + { + string[] ba = config.LocalNetworkAddresses; + + // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 + + if (ba.Length == 1 && ba[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) + { + ba = ba[0].Split(','); + } + + // TODO: end fix. + + // Read and parse bind addresses and exclusions, removing ones that don't exist. + _bindAddresses = CreateIPCollection(ba).Union(_interfaceAddresses); + _bindExclusions = CreateIPCollection(ba, true).Union(_interfaceAddresses); + _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); + _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); + } + + private void InitialiseRemote(ServerConfiguration config) + { + RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); + } + + /// + /// Initialises internal LAN cache settings. + /// + private void InitialiseLAN(ServerConfiguration config) + { + lock (_intLock) + { + _logger.LogDebug("Refreshing LAN information."); + + // Get config options. + string[] subnets = config.LocalNetworkSubnets; + + // Create lists from user settings. + + _lanSubnets = CreateIPCollection(subnets); + _excludedSubnets = NetCollection.AsNetworks(CreateIPCollection(subnets, true)); + + // If no LAN addresses are specified - all private subnets are deemed to be the LAN + _usingPrivateAddresses = _lanSubnets.Count == 0; + + // NOTE: The order of the commands in this statement matters. + if (_usingPrivateAddresses) + { + _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); + // Internal interfaces must be private and not excluded. + _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i))); + + // Subnets are the same as the calculated internal interface. + _lanSubnets = new NetCollection(); + + // We must listen on loopback for LiveTV to function regardless of the settings. + if (IsIP6Enabled) + { + _lanSubnets.Add(IPNetAddress.IP6Loopback); + _lanSubnets.Add(IPNetAddress.Parse("fc00::/7")); // ULA + _lanSubnets.Add(IPNetAddress.Parse("fe80::/10")); // Site local + } + + if (IsIP4Enabled) + { + _lanSubnets.Add(IPNetAddress.IP4Loopback); + _lanSubnets.Add(IPNetAddress.Parse("10.0.0.0/8")); + _lanSubnets.Add(IPNetAddress.Parse("172.16.0.0/12")); + _lanSubnets.Add(IPNetAddress.Parse("192.168.0.0/16")); + } + } + else + { + // We must listen on loopback for LiveTV to function regardless of the settings. + if (IsIP6Enabled) + { + _lanSubnets.Add(IPNetAddress.IP6Loopback); + } + + if (IsIP4Enabled) + { + _lanSubnets.Add(IPNetAddress.IP4Loopback); + } + + // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. + _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i))); + } + + _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets); + _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets); + _logger.LogInformation("Using LAN addresses: {0}", NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets))); + } + } + + /// + /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. + /// Generate a list of all active mac addresses that aren't loopback addreses. + /// + private void InitialiseInterfaces() + { + lock (_intLock) + { + _logger.LogDebug("Refreshing interfaces."); + + _interfaceNames.Clear(); + _interfaceAddresses.Clear(); + + try + { + IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces() + .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); + + foreach (NetworkInterface adapter in nics) + { + try + { + IPInterfaceProperties ipProperties = adapter.GetIPProperties(); + PhysicalAddress mac = adapter.GetPhysicalAddress(); + + // populate mac list + if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None) + { + _macAddresses.Add(mac); + } + + // populate interface address list + foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) + { + if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + { + IPNetAddress nw = new IPNetAddress(info.Address, info.IPv4Mask) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv4Properties().Index + }; + + int tag = nw.Tag; + /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */ + if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.Add(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + } + else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + { + IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv6Properties().Index + }; + + int tag = nw.Tag; + /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */ + if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.Add(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + } + } + } +#pragma warning disable CA1031 // Do not catch general exception types + catch + { + // Ignore error, and attempt to continue. + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); + _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses); + + // If for some reason we don't have an interface info, resolve our DNS name. + if (_interfaceAddresses.Count == 0) + { + _logger.LogWarning("No interfaces information available. Using loopback."); + + IPHost host = new IPHost(Dns.GetHostName()); + foreach (var a in host.GetAddresses()) + { + _interfaceAddresses.Add(a); + } + + if (_interfaceAddresses.Count == 0) + { + _logger.LogError("No interfaces information available. Resolving DNS name."); + // Last ditch attempt - use loopback address. + _interfaceAddresses.Add(IPNetAddress.IP4Loopback); + if (IsIP6Enabled) + { + _interfaceAddresses.Add(IPNetAddress.IP6Loopback); + } + } + } + } + catch (NetworkInformationException ex) + { + _logger.LogError(ex, "Error in InitialiseInterfaces."); + } + } + } + } +} diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 30ed3e6af3..335a1a9156 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -36,6 +36,7 @@ + diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 8f04baa089..8c19665cc1 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable #pragma warning disable CA1307 using System; @@ -12,10 +12,10 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Data.Events; using Jellyfin.Data.Events.Users; +using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Cryptography; using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Events; diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 8d569a779a..566ba0ad85 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -5,6 +5,7 @@ using System.Reflection; using Emby.Drawing; using Emby.Server.Implementations; using Jellyfin.Drawing.Skia; +using Jellyfin.Networking.Manager; using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; @@ -34,21 +35,18 @@ namespace Jellyfin.Server /// The to be used by the . /// The to be used by the . /// The to be used by the . - /// The to be used by the . /// The to be used by the . public CoreAppHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, IFileSystem fileSystem, - INetworkManager networkManager, IServiceCollection collection) : base( applicationPaths, loggerFactory, options, fileSystem, - networkManager, collection) { } diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 4bda8f2737..110290027b 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,9 +1,11 @@ using System.Linq; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; +using NetworkCollection; namespace Jellyfin.Server.Middleware { @@ -38,36 +40,35 @@ namespace Jellyfin.Server.Middleware return; } - var remoteIp = httpContext.GetNormalizedRemoteIp(); + var remoteIp = httpContext.Connection.RemoteIpAddress; if (serverConfigurationManager.Configuration.EnableRemoteAccess) { - var addressFilter = serverConfigurationManager.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray(); + // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. + // If left blank, all remote addresses will be allowed. + NetCollection remoteAddressFilter = networkManager.RemoteAddressFilter; - if (addressFilter.Length > 0 && !networkManager.IsInLocalNetwork(remoteIp)) + if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp)) { - if (serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist) + // remoteAddressFilter is a whitelist or blacklist. + bool isListed = remoteAddressFilter.Contains(remoteIp); + if (!serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist) { - if (networkManager.IsAddressInSubnets(remoteIp, addressFilter)) - { - return; - } + // Black list, so flip over. + isListed = !isListed; } - else + + if (!isListed) { - if (!networkManager.IsAddressInSubnets(remoteIp, addressFilter)) - { - return; - } + // If your name isn't on the list, you arn't coming in. + return; } } } - else + else if (!networkManager.IsInLocalNetwork(remoteIp)) { - if (!networkManager.IsInLocalNetwork(remoteIp)) - { - return; - } + // Remote not enabled. So everyone should be LAN. + return; } await _next(httpContext).ConfigureAwait(false); diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 9d795145aa..2ff6f8a765 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; @@ -32,32 +33,13 @@ namespace Jellyfin.Server.Middleware /// The async task. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) { - var currentHost = httpContext.Request.Host.ToString(); - var hosts = serverConfigurationManager - .Configuration - .LocalNetworkAddresses - .Select(NormalizeConfiguredLocalAddress) - .ToList(); + var host = httpContext.Connection.RemoteIpAddress; - if (hosts.Count == 0) + if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.Configuration.EnableRemoteAccess) { - await _next(httpContext).ConfigureAwait(false); return; } - currentHost ??= string.Empty; - - if (networkManager.IsInPrivateAddressSpace(currentHost)) - { - hosts.Add("localhost"); - hosts.Add("127.0.0.1"); - - if (hosts.All(i => currentHost.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1)) - { - return; - } - } - await _next(httpContext).ConfigureAwait(false); } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index c933d679f4..8549e39dbc 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -12,8 +12,8 @@ using System.Threading.Tasks; using CommandLine; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; -using Emby.Server.Implementations.Networking; using Jellyfin.Api.Controllers; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; @@ -24,6 +24,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using NetworkCollection; using Serilog; using Serilog.Extensions.Logging; using SQLitePCL; @@ -161,7 +162,6 @@ namespace Jellyfin.Server _loggerFactory, options, new ManagedFileSystem(_loggerFactory.CreateLogger(), appPaths), - new NetworkManager(_loggerFactory.CreateLogger()), serviceCollection); try @@ -272,57 +272,16 @@ namespace Jellyfin.Server return builder .UseKestrel((builderContext, options) => { - var addresses = appHost.ServerConfigurationManager - .Configuration - .LocalNetworkAddresses - .Select(x => appHost.NormalizeConfiguredLocalAddress(x)) - .Where(i => i != null) - .ToHashSet(); - if (addresses.Count > 0 && !addresses.Contains(IPAddress.Any)) - { - if (!addresses.Contains(IPAddress.Loopback)) - { - // we must listen on loopback for LiveTV to function regardless of the settings - addresses.Add(IPAddress.Loopback); - } + NetCollection addresses = NetworkManager.Instance.GetAllBindInterfaces(); - foreach (var address in addresses) - { - _logger.LogInformation("Kestrel listening on {IpAddress}", address); - options.Listen(address, appHost.HttpPort); - if (appHost.ListenWithHttps) - { - options.Listen(address, appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(appHost.Certificate); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); - } - else if (builderContext.HostingEnvironment.IsDevelopment()) - { - try - { - options.Listen(address, appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); - } - catch (InvalidOperationException ex) - { - _logger.LogError(ex, "Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted."); - } - } - } - } - else + bool flagged = false; + foreach (IPObject netAdd in addresses) { - _logger.LogInformation("Kestrel listening on all interfaces"); - options.ListenAnyIP(appHost.HttpPort); - + _logger.LogInformation("Kestrel listening on {0}", netAdd); + options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { - options.ListenAnyIP(appHost.HttpsPort, listenOptions => + options.Listen(netAdd.Address, appHost.HttpsPort, listenOptions => { listenOptions.UseHttps(appHost.Certificate); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; @@ -332,15 +291,19 @@ namespace Jellyfin.Server { try { - options.ListenAnyIP(appHost.HttpsPort, listenOptions => + options.Listen(netAdd.Address, appHost.HttpsPort, listenOptions => { listenOptions.UseHttps(); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); } - catch (InvalidOperationException ex) + catch (InvalidOperationException) { - _logger.LogError(ex, "Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted."); + if (!flagged) + { + _logger.LogWarning("Failed to listen to HTTPS using the ASP.NET Core HTTPS development certificate. Please ensure it has been installed and set as trusted."); + flagged = true; + } } } } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs deleted file mode 100644 index a0330afeff..0000000000 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ /dev/null @@ -1,97 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.NetworkInformation; - -namespace MediaBrowser.Common.Net -{ - public interface INetworkManager - { - event EventHandler NetworkChanged; - - /// - /// Gets or sets a function to return the list of user defined LAN addresses. - /// - Func LocalSubnetsFn { get; set; } - - /// - /// Gets a random port TCP number that is currently available. - /// - /// System.Int32. - int GetRandomUnusedTcpPort(); - - /// - /// Gets a random port UDP number that is currently available. - /// - /// System.Int32. - int GetRandomUnusedUdpPort(); - - /// - /// Returns the MAC Address from first Network Card in Computer. - /// - /// The MAC Address. - List GetMacAddresses(); - - /// - /// Determines whether [is in private address space] [the specified endpoint]. - /// - /// The endpoint. - /// true if [is in private address space] [the specified endpoint]; otherwise, false. - bool IsInPrivateAddressSpace(string endpoint); - - /// - /// Determines whether [is in private address space 10.x.x.x] [the specified endpoint] and exists in the subnets returned by GetSubnets(). - /// - /// The endpoint. - /// true if [is in private address space 10.x.x.x] [the specified endpoint]; otherwise, false. - bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint); - - /// - /// Determines whether [is in local network] [the specified endpoint]. - /// - /// The endpoint. - /// true if [is in local network] [the specified endpoint]; otherwise, false. - bool IsInLocalNetwork(string endpoint); - - /// - /// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses. - /// - /// The list of ipaddresses. - IPAddress[] GetLocalIpAddresses(); - - /// - /// Checks if the given address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format. - /// - /// The address to check. - /// If true, check against addresses in the LAN settings surrounded by brackets ([]). - /// trueif the address is in at least one of the given subnets, false otherwise. - bool IsAddressInSubnets(string addressString, string[] subnets); - - /// - /// Returns true if address is in the LAN list in the config file. - /// - /// The address to check. - /// If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address. - /// If true, returns false if address is in the 127.x.x.x or 169.128.x.x range. - /// falseif the address isn't in the LAN list, true if the address has been defined as a LAN address. - bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC); - - /// - /// Checks if address is in the LAN list in the config file. - /// - /// Source address to check. - /// Destination address to check against. - /// Destination subnet to check against. - /// true/falsedepending on whether address1 is in the same subnet as IPAddress2 with subnetMask. - bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask); - - /// - /// Returns the subnet mask of an interface with the given address. - /// - /// The address to check. - /// Returns the subnet mask of an interface with the given address, or null if an interface match cannot be found. - IPAddress GetLocalIpSubnetMask(IPAddress address); - } -} diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index cfad17fb72..f147e6a86c 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -56,41 +56,27 @@ namespace MediaBrowser.Controller /// /// Gets the system info. /// + /// The originator of the request. /// SystemInfo. - Task GetSystemInfo(CancellationToken cancellationToken); + SystemInfo GetSystemInfo(IPAddress source); - Task GetPublicSystemInfo(CancellationToken cancellationToken); - - /// - /// Gets all the local IP addresses of this API instance. Each address is validated by sending a 'ping' request - /// to the API that should exist at the address. - /// - /// A cancellation token that can be used to cancel the task. - /// A list containing all the local IP addresses of the server. - Task> GetLocalIpAddresses(CancellationToken cancellationToken); + PublicSystemInfo GetPublicSystemInfo(IPAddress address); /// /// Gets a local (LAN) URL that can be used to access the API. The hostname used is the first valid configured - /// IP address that can be found via . HTTPS will be preferred when available. + /// HTTPS will be preferred when available. /// - /// A cancellation token that can be used to cancel the task. + /// The source of the request. /// The server URL. - Task GetLocalApiUrl(CancellationToken cancellationToken); + string GetSmartApiUrl(object source); /// - /// Gets a localhost URL that can be used to access the API using the loop-back IP address (127.0.0.1) + /// Gets a localhost URL that can be used to access the API using the loop-back IP address. /// over HTTP (not HTTPS). /// /// The API URL. string GetLoopbackHttpApiUrl(); - /// - /// Gets a local (LAN) URL that can be used to access the API. HTTPS will be preferred when available. - /// - /// The IP address to use as the hostname in the URL. - /// The API URL. - string GetLocalApiUrl(IPAddress address); - /// /// Gets a local (LAN) URL that can be used to access the API. /// Note: if passing non-null scheme or port it is up to the caller to ensure they form the correct pair. @@ -105,7 +91,7 @@ namespace MediaBrowser.Controller /// preferring the HTTPS port, if available. /// /// The API URL. - string GetLocalApiUrl(ReadOnlySpan hostname, string scheme = null, int? port = null); + string GetLocalApiUrl(string hostname, string scheme = null, int? port = null); /// /// Open a URL in an external browser window. diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs new file mode 100644 index 0000000000..40eb36c2ea --- /dev/null +++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs @@ -0,0 +1,19 @@ +#nullable enable +#pragma warning disable CS1591 +#pragma warning disable CA1819 + +using System; +using System.Collections.Generic; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Updates; + +namespace MediaBrowser.Model.Configuration +{ + + public class PathSubstitution + { + public string From { get; set; } = string.Empty; + + public string To { get; set; } = string.Empty; + } +} diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 48d1a7346a..073a629829 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -1,5 +1,6 @@ #nullable disable #pragma warning disable CS1591 +#pragma warning disable CA1819 using System; using System.Collections.Generic; @@ -15,322 +16,13 @@ namespace MediaBrowser.Model.Configuration { public const int DefaultHttpPort = 8096; public const int DefaultHttpsPort = 8920; - private string _baseUrl; - - /// - /// Gets or sets a value indicating whether to enable automatic port forwarding. - /// - public bool EnableUPnP { get; set; } - - /// - /// Gets or sets a value indicating whether to enable prometheus metrics exporting. - /// - public bool EnableMetrics { get; set; } - - /// - /// Gets or sets the public mapped port. - /// - /// The public mapped port. - public int PublicPort { get; set; } - - /// - /// Gets or sets the public HTTPS port. - /// - /// The public HTTPS port. - public int PublicHttpsPort { get; set; } - - /// - /// Gets or sets the HTTP server port number. - /// - /// The HTTP server port number. - public int HttpServerPortNumber { get; set; } - - /// - /// Gets or sets the HTTPS server port number. - /// - /// The HTTPS server port number. - public int HttpsPortNumber { get; set; } - - /// - /// Gets or sets a value indicating whether to use HTTPS. - /// - /// - /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be - /// provided for and . - /// - public bool EnableHttps { get; set; } - - public bool EnableNormalizedItemByNameIds { get; set; } - - /// - /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. - /// - public string CertificatePath { get; set; } - - /// - /// Gets or sets the password required to access the X.509 certificate data in the file specified by . - /// - public string CertificatePassword { get; set; } - - /// - /// Gets or sets a value indicating whether this instance is port authorized. - /// - /// true if this instance is port authorized; otherwise, false. - public bool IsPortAuthorized { get; set; } - - /// - /// Gets or sets if quick connect is available for use on this server. - /// - public bool QuickConnectAvailable { get; set; } - - public bool AutoRunWebApp { get; set; } - - public bool EnableRemoteAccess { get; set; } - - /// - /// Gets or sets a value indicating whether [enable case sensitive item ids]. - /// - /// true if [enable case sensitive item ids]; otherwise, false. - public bool EnableCaseSensitiveItemIds { get; set; } - - public bool DisableLiveTvChannelUserDataName { get; set; } - - /// - /// Gets or sets the metadata path. - /// - /// The metadata path. - public string MetadataPath { get; set; } - - public string MetadataNetworkPath { get; set; } - - /// - /// Gets or sets the preferred metadata language. - /// - /// The preferred metadata language. - public string PreferredMetadataLanguage { get; set; } - - /// - /// Gets or sets the metadata country code. - /// - /// The metadata country code. - public string MetadataCountryCode { get; set; } - - /// - /// Characters to be replaced with a ' ' in strings to create a sort name. - /// - /// The sort replace characters. - public string[] SortReplaceCharacters { get; set; } - - /// - /// Characters to be removed from strings to create a sort name. - /// - /// The sort remove characters. - public string[] SortRemoveCharacters { get; set; } - - /// - /// Words to be removed from strings to create a sort name. - /// - /// The sort remove words. - public string[] SortRemoveWords { get; set; } - - /// - /// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated. - /// - /// The min resume PCT. - public int MinResumePct { get; set; } - - /// - /// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched. - /// - /// The max resume PCT. - public int MaxResumePct { get; set; } - - /// - /// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates.. - /// - /// The min resume duration seconds. - public int MinResumeDurationSeconds { get; set; } - - /// - /// The delay in seconds that we will wait after a file system change to try and discover what has been added/removed - /// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several - /// different directories and files. - /// - /// The file watcher delay. - public int LibraryMonitorDelay { get; set; } - - /// - /// Gets or sets a value indicating whether [enable dashboard response caching]. - /// Allows potential contributors without visual studio to modify production dashboard code and test changes. - /// - /// true if [enable dashboard response caching]; otherwise, false. - public bool EnableDashboardResponseCaching { get; set; } - - /// - /// Gets or sets the image saving convention. - /// - /// The image saving convention. - public ImageSavingConvention ImageSavingConvention { get; set; } - - public MetadataOptions[] MetadataOptions { get; set; } - - public bool SkipDeserializationForBasicTypes { get; set; } - - public string ServerName { get; set; } - - public string BaseUrl - { - get => _baseUrl; - set - { - // Normalize the start of the string - if (string.IsNullOrWhiteSpace(value)) - { - // If baseUrl is empty, set an empty prefix string - _baseUrl = string.Empty; - return; - } - - if (value[0] != '/') - { - // If baseUrl was not configured with a leading slash, append one for consistency - value = "/" + value; - } - - // Normalize the end of the string - if (value[value.Length - 1] == '/') - { - // If baseUrl was configured with a trailing slash, remove it for consistency - value = value.Remove(value.Length - 1); - } - - _baseUrl = value; - } - } - - public string UICulture { get; set; } - - public bool SaveMetadataHidden { get; set; } - - public NameValuePair[] ContentTypes { get; set; } - - public int RemoteClientBitrateLimit { get; set; } - - public bool EnableFolderView { get; set; } - - public bool EnableGroupingIntoCollections { get; set; } - - public bool DisplaySpecialsWithinSeasons { get; set; } - - public string[] LocalNetworkSubnets { get; set; } - - public string[] LocalNetworkAddresses { get; set; } - - public string[] CodecsUsed { get; set; } - - public List PluginRepositories { get; set; } - - public bool IgnoreVirtualInterfaces { get; set; } - - public bool EnableExternalContentInSuggestions { get; set; } - - /// - /// Gets or sets a value indicating whether the server should force connections over HTTPS. - /// - public bool RequireHttps { get; set; } - - public bool EnableNewOmdbSupport { get; set; } - - public string[] RemoteIPFilter { get; set; } - - public bool IsRemoteIPFilterBlacklist { get; set; } - - public int ImageExtractionTimeoutMs { get; set; } - - public PathSubstitution[] PathSubstitutions { get; set; } - - public bool EnableSimpleArtistDetection { get; set; } - - public string[] UninstalledPlugins { get; set; } - - /// - /// Gets or sets a value indicating whether slow server responses should be logged as a warning. - /// - public bool EnableSlowResponseWarning { get; set; } - - /// - /// Gets or sets the threshold for the slow response time warning in ms. - /// - public long SlowResponseThresholdMs { get; set; } - - /// - /// Gets or sets the cors hosts. - /// - public string[] CorsHosts { get; set; } - - /// - /// Gets or sets the known proxies. - /// - public string[] KnownProxies { get; set; } + private string _baseUrl = string.Empty; /// /// Initializes a new instance of the class. /// public ServerConfiguration() { - UninstalledPlugins = Array.Empty(); - RemoteIPFilter = Array.Empty(); - LocalNetworkSubnets = Array.Empty(); - LocalNetworkAddresses = Array.Empty(); - CodecsUsed = Array.Empty(); - PathSubstitutions = Array.Empty(); - IgnoreVirtualInterfaces = false; - EnableSimpleArtistDetection = false; - SkipDeserializationForBasicTypes = true; - - PluginRepositories = new List(); - - DisplaySpecialsWithinSeasons = true; - EnableExternalContentInSuggestions = true; - - ImageSavingConvention = ImageSavingConvention.Compatible; - PublicPort = DefaultHttpPort; - PublicHttpsPort = DefaultHttpsPort; - HttpServerPortNumber = DefaultHttpPort; - HttpsPortNumber = DefaultHttpsPort; - EnableMetrics = false; - EnableHttps = false; - EnableDashboardResponseCaching = true; - EnableCaseSensitiveItemIds = true; - EnableNormalizedItemByNameIds = true; - DisableLiveTvChannelUserDataName = true; - EnableNewOmdbSupport = true; - - AutoRunWebApp = true; - EnableRemoteAccess = true; - QuickConnectAvailable = false; - - EnableUPnP = false; - MinResumePct = 5; - MaxResumePct = 90; - - // 5 minutes - MinResumeDurationSeconds = 300; - - LibraryMonitorDelay = 60; - - ContentTypes = Array.Empty(); - - PreferredMetadataLanguage = "en"; - MetadataCountryCode = "US"; - - SortReplaceCharacters = new[] { ".", "+", "%" }; - SortRemoveCharacters = new[] { ",", "&", "-", "{", "}", "'" }; - SortRemoveWords = new[] { "the", "a", "an" }; - - BaseUrl = string.Empty; - UICulture = "en-US"; - MetadataOptions = new[] { new MetadataOptions() @@ -379,18 +71,354 @@ namespace MediaBrowser.Model.Configuration DisabledImageFetchers = new[] { "The Open Movie Database", "TheMovieDb" } } }; - - EnableSlowResponseWarning = true; - SlowResponseThresholdMs = 500; - CorsHosts = new[] { "*" }; - KnownProxies = Array.Empty(); } - } - public class PathSubstitution - { - public string From { get; set; } + /// + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// + public bool EnableUPnP { get; set; } = false; + + /// + /// Gets or sets a value indicating whether to enable prometheus metrics exporting. + /// + public bool EnableMetrics { get; set; } = false; + + /// + /// Gets or sets the public mapped port. + /// + /// The public mapped port. + public int PublicPort { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. + /// + public bool UPnPCreateHttpPortMap { get; set; } = false; + + /// + /// Gets or sets client udp port range. + /// + public string UDPPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// + public bool EnableIPV6 { get; set; } = false; + + /// + /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// + public bool EnableIPV4 { get; set; } = true; + + /// + /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// + public bool EnableSSDPTracing { get; set; } = false; + + /// + /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// + public string SSDPTracingFilter { get; set; } = string.Empty; + + /// + /// Gets or sets the number of times SSDP UDP messages are sent. + /// + public int UDPSendCount { get; set; } = 2; + + /// + /// Gets or sets the delay between each groups of SSDP messages (in ms). + /// + public int UDPSendDelay { get; set; } = 100; + + /// + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. + /// + public int GatewayMonitorPeriod { get; set; } = 60; + + /// + /// Gets a value indicating whether is multi-socket binding available. + /// + public bool EnableMultiSocketBinding { get; } = true; + + /// + /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. + /// Depending on the address range implemented ULA ranges might not be used. + /// + public bool TrustAllIP6Interfaces { get; set; } = false; + + /// + /// Gets or sets the ports that HDHomerun uses. + /// + public string HDHomerunPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether gets or sets Autodiscovery tracing. + /// + public bool AutoDiscoveryTracing { get; set; } = false; + + /// + /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// + public bool AutoDiscovery { get; set; } = true; + + /// + /// Gets or sets the public HTTPS port. + /// + /// The public HTTPS port. + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets the HTTP server port number. + /// + /// The HTTP server port number. + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets the HTTPS server port number. + /// + /// The HTTPS server port number. + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets a value indicating whether to use HTTPS. + /// + /// + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for and . + /// + public bool EnableHttps { get; set; } = false; + + public bool EnableNormalizedItemByNameIds { get; set; } = true; + + /// + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// + public string CertificatePath { get; set; } = string.Empty; + + /// + /// Gets or sets the password required to access the X.509 certificate data in the file specified by . + /// + public string CertificatePassword { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether this instance is port authorized. + /// + /// true if this instance is port authorized; otherwise, false. + public bool IsPortAuthorized { get; set; } + + /// + /// Gets or sets a value indicating whether quick connect is available for use on this server. + /// + public bool QuickConnectAvailable { get; set; } = false; + + public bool AutoRunWebApp { get; set; } = true; + + /// + /// Gets or sets a value indicating whether access outside of the LAN is permitted. + /// + public bool EnableRemoteAccess { get; set; } = true; + + /// + /// Gets or sets a value indicating whether [enable case sensitive item ids]. + /// + /// true if [enable case sensitive item ids]; otherwise, false. + public bool EnableCaseSensitiveItemIds { get; set; } = true; + + public bool DisableLiveTvChannelUserDataName { get; set; } = true; + + /// + /// Gets or sets the metadata path. + /// + /// The metadata path. + public string MetadataPath { get; set; } = string.Empty; + + public string MetadataNetworkPath { get; set; } = string.Empty; + + /// + /// Gets or sets the preferred metadata language. + /// + /// The preferred metadata language. + public string PreferredMetadataLanguage { get; set; } = string.Empty; + + /// + /// Gets or sets the metadata country code. + /// + /// The metadata country code. + public string MetadataCountryCode { get; set; } = "US"; + + /// + /// Gets or sets characters to be replaced with a ' ' in strings to create a sort name. + /// + /// The sort replace characters. + public string[] SortReplaceCharacters { get; set; } = new[] { ".", "+", "%" }; + + /// + /// Gets or sets characters to be removed from strings to create a sort name. + /// + /// The sort remove characters. + public string[] SortRemoveCharacters { get; set; } = new[] { ",", "&", "-", "{", "}", "'" }; + + /// + /// Gets or sets words to be removed from strings to create a sort name. + /// + /// The sort remove words. + public string[] SortRemoveWords { get; set; } = new[] { "the", "a", "an" }; + + /// + /// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated. + /// + /// The min resume PCT. + public int MinResumePct { get; set; } = 5; + + /// + /// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched. + /// + /// The max resume PCT. + public int MaxResumePct { get; set; } = 90; + + /// + /// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates.. + /// + /// The min resume duration seconds. + public int MinResumeDurationSeconds { get; set; } = 300; + + /// + /// Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed + /// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several + /// different directories and files. + /// + /// The file watcher delay. + public int LibraryMonitorDelay { get; set; } = 60; + + /// + /// Gets or sets a value indicating whether [enable dashboard response caching]. + /// Allows potential contributors without visual studio to modify production dashboard code and test changes. + /// + /// true if [enable dashboard response caching]; otherwise, false. + public bool EnableDashboardResponseCaching { get; set; } = true; + + /// + /// Gets or sets the image saving convention. + /// + /// The image saving convention. + public ImageSavingConvention ImageSavingConvention { get; set; } + + public MetadataOptions[] MetadataOptions { get; set; } + + public bool SkipDeserializationForBasicTypes { get; set; } = true; + + public string ServerName { get; set; } = string.Empty; + + public string BaseUrl + { + get => _baseUrl; + set + { + // Normalize the start of the string + if (string.IsNullOrWhiteSpace(value)) + { + // If baseUrl is empty, set an empty prefix string + _baseUrl = string.Empty; + return; + } + + if (value[0] != '/') + { + // If baseUrl was not configured with a leading slash, append one for consistency + value = "/" + value; + } + + // Normalize the end of the string + if (value[value.Length - 1] == '/') + { + // If baseUrl was configured with a trailing slash, remove it for consistency + value = value.Remove(value.Length - 1); + } + + _baseUrl = value; + } + } + + public string UICulture { get; set; } = "en-US"; + + public bool SaveMetadataHidden { get; set; } = false; + + public NameValuePair[] ContentTypes { get; set; } = Array.Empty(); + + public int RemoteClientBitrateLimit { get; set; } = 0; + + public bool EnableFolderView { get; set; } = false; + + public bool EnableGroupingIntoCollections { get; set; } = false; + + public bool DisplaySpecialsWithinSeasons { get; set; } = true; + + /// + /// Gets or sets the subnets that are deemed to make up the LAN. + /// + public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); + + /// + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// + public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); + + public string[] CodecsUsed { get; set; } = Array.Empty(); + + public List PluginRepositories { get; set; } = new List(); + + public bool EnableExternalContentInSuggestions { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// + public bool RequireHttps { get; set; } = false; + + public bool EnableNewOmdbSupport { get; set; } = true; + + /// + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with . + /// + public string[] RemoteIPFilter { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist. + /// + public bool IsRemoteIPFilterBlacklist { get; set; } = false; + + public int ImageExtractionTimeoutMs { get; set; } = 0; + + public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty(); + + public bool EnableSimpleArtistDetection { get; set; } = false; + + public string[] UninstalledPlugins { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether slow server responses should be logged as a warning. + /// + public bool EnableSlowResponseWarning { get; set; } = true; + + /// + /// Gets or sets the threshold for the slow response time warning in ms. + /// + public long SlowResponseThresholdMs { get; set; } = 500; + + /// + /// Gets or sets the cors hosts. + /// + public string[] CorsHosts { get; set; } = new[] { "*" }; + + /// + /// Gets or sets the known proxies. + /// + public string[] KnownProxies { get; set; } = Array.Empty(); - public string To { get; set; } } } diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 25402aee13..d460c0ab0c 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26730.3 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" EndProject @@ -66,12 +66,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Data", "Jellyfin.D EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementations", "Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj", "{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -132,10 +138,6 @@ Global {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -176,10 +178,22 @@ Global {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Debug|Any CPU.Build.0 = Debug|Any CPU {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.ActiveCfg = Release|Any CPU {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.Build.0 = Release|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} EndGlobalSection @@ -201,12 +215,4 @@ Global $0.DotNetNamingPolicy = $2 $2.DirectoryNamespaceAssociation = PrefixedHierarchical EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - EndGlobalSection EndGlobal diff --git a/RSSDP/RSSDP.csproj b/RSSDP/RSSDP.csproj index 664663bd76..3266a05cbf 100644 --- a/RSSDP/RSSDP.csproj +++ b/RSSDP/RSSDP.csproj @@ -6,6 +6,7 @@ + diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index a4be32e7d2..e28a2f48d4 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -7,6 +7,7 @@ using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; @@ -352,7 +353,7 @@ namespace Rssdp.Infrastructure if (_enableMultiSocketBinding) { - foreach (var address in _networkManager.GetLocalIpAddresses()) + foreach (var address in _networkManager.GetAllBindInterfaces()) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { @@ -362,7 +363,7 @@ namespace Rssdp.Infrastructure try { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address, _LocalPort)); + sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort)); } catch (Exception ex) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 1a8577d8da..43fccdad42 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -5,7 +5,9 @@ using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Net; +using NetworkCollection; namespace Rssdp.Infrastructure { @@ -300,17 +302,14 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { - if (!_sendOnlyMatchedHost || - _networkManager.IsInSameSubnet(device.ToRootDevice().Address, remoteEndPoint.Address, device.ToRootDevice().SubnetMask)) + var ip1 = new IPNetAddress(device.ToRootDevice().Address, device.ToRootDevice().SubnetMask); + var ip2 = new IPNetAddress(remoteEndPoint.Address, device.ToRootDevice().SubnetMask); + if (!_sendOnlyMatchedHost || ip1.NetworkAddress.Equals(ip2.NetworkAddress)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } } } - else - { - // WriteTrace(String.Format("Sending 0 search responses.")); - } }); } diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs index 09ffa84689..2c7f0c4f9b 100644 --- a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs @@ -1,9 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; using AutoFixture; using AutoFixture.AutoMoq; using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Constants; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs index 77f1640fa3..939023a95b 100644 --- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs @@ -3,8 +3,6 @@ using System.Collections.Concurrent; using System.IO; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; -using Emby.Server.Implementations.Networking; -using Jellyfin.Drawing.Skia; using Jellyfin.Server; using MediaBrowser.Common; using Microsoft.AspNetCore.Hosting; @@ -81,7 +79,6 @@ namespace Jellyfin.Api.Tests loggerFactory, commandLineOpts, new ManagedFileSystem(loggerFactory.CreateLogger(), appPaths), - new NetworkManager(loggerFactory.CreateLogger()), serviceCollection); _disposableComponents.Add(appHost); appHost.Init(); From 288d89493e76b8881c719fe549859b2c0b5f7e29 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sat, 12 Sep 2020 17:21:03 +0100 Subject: [PATCH 0020/1930] Fixed testing units. --- .../Middleware/IpBasedAccessValidationMiddleware.cs | 3 ++- Jellyfin.Server/Middleware/LanFilteringMiddleware.cs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 110290027b..ff82fe6cc6 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -34,8 +34,9 @@ namespace Jellyfin.Server.Middleware /// The async task. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) { - if (httpContext.IsLocal()) + if (httpContext.Connection.RemoteIpAddress == null) { + // Running locally. await _next(httpContext).ConfigureAwait(false); return; } diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 2ff6f8a765..87c82bf583 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -1,10 +1,13 @@ using System; using System.Linq; +using System.Net; using System.Threading.Tasks; using Jellyfin.Networking.Manager; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; +using NetworkCollection; namespace Jellyfin.Server.Middleware { @@ -33,7 +36,7 @@ namespace Jellyfin.Server.Middleware /// The async task. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) { - var host = httpContext.Connection.RemoteIpAddress; + var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.Configuration.EnableRemoteAccess) { From 68de105dc21f4d1114a3b1db81f177caae747ef6 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sun, 13 Sep 2020 13:49:11 +0100 Subject: [PATCH 0021/1930] Comments part 1 --- Emby.Dlna/Common/Argument.cs | 20 +- Emby.Dlna/Common/DeviceIcon.cs | 32 +- Emby.Dlna/Common/DeviceService.cs | 33 +- Emby.Dlna/Common/ServiceAction.cs | 21 +- Emby.Dlna/Common/StateVariable.cs | 31 +- .../Dlna/DeviceIdentification.cs | 23 +- MediaBrowser.Model/Dlna/DeviceProfile.cs | 364 +++++++++++++----- MediaBrowser.Model/Dlna/XmlAttribute.cs | 9 + 8 files changed, 377 insertions(+), 156 deletions(-) diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs index f375e6049c..430a3b47d5 100644 --- a/Emby.Dlna/Common/Argument.cs +++ b/Emby.Dlna/Common/Argument.cs @@ -1,13 +1,23 @@ -#pragma warning disable CS1591 - namespace Emby.Dlna.Common { + /// + /// DLNA Query parameter type, used when quering DLNA devices via SOAP. + /// public class Argument { - public string Name { get; set; } + /// + /// Gets or sets name of the DLNA argument. + /// + public string Name { get; set; } = string.Empty; - public string Direction { get; set; } + /// + /// Gets or sets the direction of the parameter. + /// + public string Direction { get; set; } = string.Empty; - public string RelatedStateVariable { get; set; } + /// + /// Gets or sets the related DLNA state variable for this argument. + /// + public string RelatedStateVariable { get; set; } = string.Empty; } } diff --git a/Emby.Dlna/Common/DeviceIcon.cs b/Emby.Dlna/Common/DeviceIcon.cs index c3f7fa8aaa..f9fd1dcec6 100644 --- a/Emby.Dlna/Common/DeviceIcon.cs +++ b/Emby.Dlna/Common/DeviceIcon.cs @@ -1,29 +1,41 @@ -#pragma warning disable CS1591 - using System.Globalization; namespace Emby.Dlna.Common { + /// + /// Defines the . + /// public class DeviceIcon { - public string Url { get; set; } + /// + /// Gets or sets the Url. + /// + public string Url { get; set; } = string.Empty; - public string MimeType { get; set; } + /// + /// Gets or sets the MimeType. + /// + public string MimeType { get; set; } = string.Empty; + /// + /// Gets or sets the Width. + /// public int Width { get; set; } + /// + /// Gets or sets the Height. + /// public int Height { get; set; } - public string Depth { get; set; } + /// + /// Gets or sets the Depth. + /// + public string Depth { get; set; } = string.Empty; /// public override string ToString() { - return string.Format( - CultureInfo.InvariantCulture, - "{0}x{1}", - Height, - Width); + return string.Format(CultureInfo.InvariantCulture, "{0}x{1}", Height, Width); } } } diff --git a/Emby.Dlna/Common/DeviceService.cs b/Emby.Dlna/Common/DeviceService.cs index 44c0a0412a..c1369558ec 100644 --- a/Emby.Dlna/Common/DeviceService.cs +++ b/Emby.Dlna/Common/DeviceService.cs @@ -1,21 +1,36 @@ -#pragma warning disable CS1591 - namespace Emby.Dlna.Common { + /// + /// Defines the . + /// public class DeviceService { - public string ServiceType { get; set; } + /// + /// Gets or sets the Service Type. + /// + public string ServiceType { get; set; } = string.Empty; - public string ServiceId { get; set; } + /// + /// Gets or sets the Service Id. + /// + public string ServiceId { get; set; } = string.Empty; - public string ScpdUrl { get; set; } + /// + /// Gets or sets the Scpd Url. + /// + public string ScpdUrl { get; set; } = string.Empty; - public string ControlUrl { get; set; } + /// + /// Gets or sets the Control Url. + /// + public string ControlUrl { get; set; } = string.Empty; - public string EventSubUrl { get; set; } + /// + /// Gets or sets the EventSubUrl. + /// + public string EventSubUrl { get; set; } = string.Empty; /// - public override string ToString() - => ServiceId; + public override string ToString() => ServiceId; } } diff --git a/Emby.Dlna/Common/ServiceAction.cs b/Emby.Dlna/Common/ServiceAction.cs index d458d7f3f6..02b81a0aa7 100644 --- a/Emby.Dlna/Common/ServiceAction.cs +++ b/Emby.Dlna/Common/ServiceAction.cs @@ -1,24 +1,31 @@ -#pragma warning disable CS1591 - using System.Collections.Generic; namespace Emby.Dlna.Common { + /// + /// Defines the . + /// public class ServiceAction { + /// + /// Initializes a new instance of the class. + /// public ServiceAction() { ArgumentList = new List(); } - public string Name { get; set; } + /// + /// Gets or sets the name of the action. + /// + public string Name { get; set; } = string.Empty; + /// + /// Gets the ArgumentList. + /// public List ArgumentList { get; } /// - public override string ToString() - { - return Name; - } + public override string ToString() => Name; } } diff --git a/Emby.Dlna/Common/StateVariable.cs b/Emby.Dlna/Common/StateVariable.cs index 6daf7ab6b2..fd733e0853 100644 --- a/Emby.Dlna/Common/StateVariable.cs +++ b/Emby.Dlna/Common/StateVariable.cs @@ -1,27 +1,34 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; namespace Emby.Dlna.Common { + /// + /// Defines the . + /// public class StateVariable { - public StateVariable() - { - AllowedValues = Array.Empty(); - } + /// + /// Gets or sets the name of the state variable. + /// + public string Name { get; set; } = string.Empty; - public string Name { get; set; } - - public string DataType { get; set; } + /// + /// Gets or sets the data type of the state variable. + /// + public string DataType { get; set; } = string.Empty; + /// + /// Gets or sets a value indicating whether it sends events. + /// public bool SendsEvents { get; set; } - public IReadOnlyList AllowedValues { get; set; } + /// + /// Gets or sets the allowed values range. + /// + public IReadOnlyList AllowedValues { get; set; } = Array.Empty(); /// - public override string ToString() - => Name; + public override string ToString() => Name; } } diff --git a/MediaBrowser.Model/Dlna/DeviceIdentification.cs b/MediaBrowser.Model/Dlna/DeviceIdentification.cs index 43407383a8..c511801f4f 100644 --- a/MediaBrowser.Model/Dlna/DeviceIdentification.cs +++ b/MediaBrowser.Model/Dlna/DeviceIdentification.cs @@ -11,59 +11,54 @@ namespace MediaBrowser.Model.Dlna /// Gets or sets the name of the friendly. /// /// The name of the friendly. - public string FriendlyName { get; set; } + public string FriendlyName { get; set; } = string.Empty; /// /// Gets or sets the model number. /// /// The model number. - public string ModelNumber { get; set; } + public string ModelNumber { get; set; } = string.Empty; /// /// Gets or sets the serial number. /// /// The serial number. - public string SerialNumber { get; set; } + public string SerialNumber { get; set; } = string.Empty; /// /// Gets or sets the name of the model. /// /// The name of the model. - public string ModelName { get; set; } + public string ModelName { get; set; } = string.Empty; /// /// Gets or sets the model description. /// /// The model description. - public string ModelDescription { get; set; } + public string ModelDescription { get; set; } = string.Empty; /// /// Gets or sets the model URL. /// /// The model URL. - public string ModelUrl { get; set; } + public string ModelUrl { get; set; } = string.Empty; /// /// Gets or sets the manufacturer. /// /// The manufacturer. - public string Manufacturer { get; set; } + public string Manufacturer { get; set; } = string.Empty; /// /// Gets or sets the manufacturer URL. /// /// The manufacturer URL. - public string ManufacturerUrl { get; set; } + public string ManufacturerUrl { get; set; } = string.Empty; /// /// Gets or sets the headers. /// /// The headers. - public HttpHeaderInfo[] Headers { get; set; } - - public DeviceIdentification() - { - Headers = Array.Empty(); - } + public HttpHeaderInfo[] Headers { get; set; } = Array.Empty(); } } diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 7e921b1fdf..8b2a94fd45 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -1,6 +1,5 @@ #nullable disable -#pragma warning disable CS1591 - +#pragma warning disable CA1819 // Properties should not return arrays using System; using System.Linq; using System.Xml.Serialization; @@ -8,107 +7,15 @@ using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Model.Dlna { + /// + /// Defines the . + /// [XmlRoot("Profile")] public class DeviceProfile { /// - /// Gets or sets the name. + /// Initializes a new instance of the class. /// - /// The name. - public string Name { get; set; } - - [XmlIgnore] - public string Id { get; set; } - - /// - /// Gets or sets the identification. - /// - /// The identification. - public DeviceIdentification Identification { get; set; } - - public string FriendlyName { get; set; } - - public string Manufacturer { get; set; } - - public string ManufacturerUrl { get; set; } - - public string ModelName { get; set; } - - public string ModelDescription { get; set; } - - public string ModelNumber { get; set; } - - public string ModelUrl { get; set; } - - public string SerialNumber { get; set; } - - public bool EnableAlbumArtInDidl { get; set; } - - public bool EnableSingleAlbumArtLimit { get; set; } - - public bool EnableSingleSubtitleLimit { get; set; } - - public string SupportedMediaTypes { get; set; } - - public string UserId { get; set; } - - public string AlbumArtPn { get; set; } - - public int MaxAlbumArtWidth { get; set; } - - public int MaxAlbumArtHeight { get; set; } - - public int? MaxIconWidth { get; set; } - - public int? MaxIconHeight { get; set; } - - public long? MaxStreamingBitrate { get; set; } - - public long? MaxStaticBitrate { get; set; } - - public int? MusicStreamingTranscodingBitrate { get; set; } - - public int? MaxStaticMusicBitrate { get; set; } - - /// - /// Controls the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace. - /// - public string SonyAggregationFlags { get; set; } - - public string ProtocolInfo { get; set; } - - public int TimelineOffsetSeconds { get; set; } - - public bool RequiresPlainVideoItems { get; set; } - - public bool RequiresPlainFolders { get; set; } - - public bool EnableMSMediaReceiverRegistrar { get; set; } - - public bool IgnoreTranscodeByteRangeRequests { get; set; } - - public XmlAttribute[] XmlRootAttributes { get; set; } - - /// - /// Gets or sets the direct play profiles. - /// - /// The direct play profiles. - public DirectPlayProfile[] DirectPlayProfiles { get; set; } - - /// - /// Gets or sets the transcoding profiles. - /// - /// The transcoding profiles. - public TranscodingProfile[] TranscodingProfiles { get; set; } - - public ContainerProfile[] ContainerProfiles { get; set; } - - public CodecProfile[] CodecProfiles { get; set; } - - public ResponseProfile[] ResponseProfiles { get; set; } - - public SubtitleProfile[] SubtitleProfiles { get; set; } - public DeviceProfile() { DirectPlayProfiles = Array.Empty(); @@ -126,11 +33,217 @@ namespace MediaBrowser.Model.Dlna MusicStreamingTranscodingBitrate = 128000; } + /// + /// Gets or sets the Name. + /// + public string Name { get; set; } + + /// + /// Gets or sets the Id. + /// + [XmlIgnore] + public string Id { get; set; } + + /// + /// Gets or sets the Identification. + /// + public DeviceIdentification Identification { get; set; } + + /// + /// Gets or sets the FriendlyName. + /// + public string FriendlyName { get; set; } + + /// + /// Gets or sets the Manufacturer. + /// + public string Manufacturer { get; set; } + + /// + /// Gets or sets the ManufacturerUrl. + /// + public string ManufacturerUrl { get; set; } + + /// + /// Gets or sets the ModelName. + /// + public string ModelName { get; set; } + + /// + /// Gets or sets the ModelDescription. + /// + public string ModelDescription { get; set; } + + /// + /// Gets or sets the ModelNumber. + /// + public string ModelNumber { get; set; } + + /// + /// Gets or sets the ModelUrl. + /// + public string ModelUrl { get; set; } + + /// + /// Gets or sets the SerialNumber. + /// + public string SerialNumber { get; set; } + + /// + /// Gets or sets a value indicating whether EnableAlbumArtInDidl. + /// + public bool EnableAlbumArtInDidl { get; set; } + + /// + /// Gets or sets a value indicating whether EnableSingleAlbumArtLimit. + /// + public bool EnableSingleAlbumArtLimit { get; set; } + + /// + /// Gets or sets a value indicating whether EnableSingleSubtitleLimit. + /// + public bool EnableSingleSubtitleLimit { get; set; } + + /// + /// Gets or sets the SupportedMediaTypes. + /// + public string SupportedMediaTypes { get; set; } + + /// + /// Gets or sets the UserId. + /// + public string UserId { get; set; } + + /// + /// Gets or sets the AlbumArtPn. + /// + public string AlbumArtPn { get; set; } + + /// + /// Gets or sets the MaxAlbumArtWidth. + /// + public int MaxAlbumArtWidth { get; set; } + + /// + /// Gets or sets the MaxAlbumArtHeight. + /// + public int MaxAlbumArtHeight { get; set; } + + /// + /// Gets or sets the MaxIconWidth. + /// + public int? MaxIconWidth { get; set; } + + /// + /// Gets or sets the MaxIconHeight. + /// + public int? MaxIconHeight { get; set; } + + /// + /// Gets or sets the MaxStreamingBitrate. + /// + public long? MaxStreamingBitrate { get; set; } + + /// + /// Gets or sets the MaxStaticBitrate. + /// + public long? MaxStaticBitrate { get; set; } + + /// + /// Gets or sets the MusicStreamingTranscodingBitrate. + /// + public int? MusicStreamingTranscodingBitrate { get; set; } + + /// + /// Gets or sets the MaxStaticMusicBitrate. + /// + public int? MaxStaticMusicBitrate { get; set; } + + /// + /// Gets or sets the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace. + /// + public string SonyAggregationFlags { get; set; } + + /// + /// Gets or sets the ProtocolInfo. + /// + public string ProtocolInfo { get; set; } + + /// + /// Gets or sets the TimelineOffsetSeconds. + /// + public int TimelineOffsetSeconds { get; set; } + + /// + /// Gets or sets a value indicating whether RequiresPlainVideoItems. + /// + public bool RequiresPlainVideoItems { get; set; } + + /// + /// Gets or sets a value indicating whether RequiresPlainFolders. + /// + public bool RequiresPlainFolders { get; set; } + + /// + /// Gets or sets a value indicating whether EnableMSMediaReceiverRegistrar. + /// + public bool EnableMSMediaReceiverRegistrar { get; set; } + + /// + /// Gets or sets a value indicating whether IgnoreTranscodeByteRangeRequests. + /// + public bool IgnoreTranscodeByteRangeRequests { get; set; } + + /// + /// Gets or sets the XmlRootAttributes. + /// + public XmlAttribute[] XmlRootAttributes { get; set; } + + /// + /// Gets or sets the direct play profiles. + /// + public DirectPlayProfile[] DirectPlayProfiles { get; set; } + + /// + /// Gets or sets the transcoding profiles. + /// + public TranscodingProfile[] TranscodingProfiles { get; set; } + + /// + /// Gets or sets the ContainerProfiles. + /// + public ContainerProfile[] ContainerProfiles { get; set; } + + /// + /// Gets or sets the CodecProfiles. + /// + public CodecProfile[] CodecProfiles { get; set; } + + /// + /// Gets or sets the ResponseProfiles. + /// + public ResponseProfile[] ResponseProfiles { get; set; } + + /// + /// Gets or sets the SubtitleProfiles. + /// + public SubtitleProfile[] SubtitleProfiles { get; set; } + + /// + /// The GetSupportedMediaTypes. + /// + /// The . public string[] GetSupportedMediaTypes() { return ContainerProfile.SplitValue(SupportedMediaTypes); } + /// + /// Gets the audio transcoding profile. + /// + /// The container. + /// The audio Codec. + /// A . public TranscodingProfile GetAudioTranscodingProfile(string container, string audioCodec) { container = (container ?? string.Empty).TrimStart('.'); @@ -158,6 +271,13 @@ namespace MediaBrowser.Model.Dlna return null; } + /// + /// Gets the video transcoding profile. + /// + /// The container. + /// The audio Codec. + /// The video Codec. + /// The . public TranscodingProfile GetVideoTranscodingProfile(string container, string audioCodec, string videoCodec) { container = (container ?? string.Empty).TrimStart('.'); @@ -190,6 +310,16 @@ namespace MediaBrowser.Model.Dlna return null; } + /// + /// Gets the audio media profile. + /// + /// The container. + /// The audio codec. + /// The audio channels. + /// The audio bitrate. + /// The audio sample rate. + /// The audio bit depth. + /// The . public ResponseProfile GetAudioMediaProfile(string container, string audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth) { foreach (var i in ResponseProfiles) @@ -231,6 +361,11 @@ namespace MediaBrowser.Model.Dlna return null; } + /// + /// Gets the model profile condition. + /// + /// The c. + /// The . private ProfileCondition GetModelProfileCondition(ProfileCondition c) { return new ProfileCondition @@ -242,6 +377,13 @@ namespace MediaBrowser.Model.Dlna }; } + /// + /// Gets the image media profile. + /// + /// The container. + /// The width. + /// The height. + /// The . public ResponseProfile GetImageMediaProfile(string container, int? width, int? height) { foreach (var i in ResponseProfiles) @@ -277,7 +419,31 @@ namespace MediaBrowser.Model.Dlna return null; } - public ResponseProfile GetVideoMediaProfile(string container, + /// + /// Gets the video media profile. + /// + /// The container. + /// The audio codec. + /// The video codec. + /// The width. + /// The height. + /// The bit depth. + /// The video bitrate. + /// The video profile. + /// The video level. + /// The video framerate. + /// The packet length. + /// The timestamp. + /// True if anamorphic. + /// True if interlaced. + /// The ref frames. + /// The number of video streams. + /// The number of audio streams. + /// The video Codec tag. + /// True if Avc. + /// The . + public ResponseProfile GetVideoMediaProfile( + string container, string audioCodec, string videoCodec, int? width, diff --git a/MediaBrowser.Model/Dlna/XmlAttribute.cs b/MediaBrowser.Model/Dlna/XmlAttribute.cs index 3a8939a797..03bb2e4b11 100644 --- a/MediaBrowser.Model/Dlna/XmlAttribute.cs +++ b/MediaBrowser.Model/Dlna/XmlAttribute.cs @@ -5,11 +5,20 @@ using System.Xml.Serialization; namespace MediaBrowser.Model.Dlna { + /// + /// Defines the . + /// public class XmlAttribute { + /// + /// Gets or sets the name of the attribute. + /// [XmlAttribute("name")] public string Name { get; set; } + /// + /// Gets or sets the value of the attribute. + /// [XmlAttribute("value")] public string Value { get; set; } } From 3ad320175df5d01d9ae4e32e3b2f23decef317d2 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sun, 13 Sep 2020 14:18:15 +0100 Subject: [PATCH 0022/1930] ConnectionManager - static implementation --- Emby.Dlna/Configuration/DlnaOptions.cs | 69 ++++++++- .../ConnectionManagerService.cs | 12 +- .../ConnectionManagerXmlBuilder.cs | 145 ++++++++++-------- Emby.Dlna/ConnectionManager/ControlHandler.cs | 13 ++ .../ServiceActionListBuilder.cs | 37 ++++- 5 files changed, 199 insertions(+), 77 deletions(-) diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index 6dd9a445a8..481ff059b5 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -2,8 +2,14 @@ namespace Emby.Dlna.Configuration { + /// + /// The DlnaOptions class contains the user definable parameters for the dlna subsystems. + /// public class DlnaOptions { + /// + /// Initializes a new instance of the class. + /// public DlnaOptions() { EnablePlayTo = true; @@ -11,23 +17,76 @@ namespace Emby.Dlna.Configuration BlastAliveMessages = true; SendOnlyMatchedHost = true; ClientDiscoveryIntervalSeconds = 60; - BlastAliveMessageIntervalSeconds = 1800; + AliveMessageIntervalSeconds = 1800; } + /// + /// Gets or sets a value indicating whether gets or sets a value to indicate the status of the dlna playTo subsystem. + /// public bool EnablePlayTo { get; set; } + /// + /// Gets or sets a value indicating whether gets or sets a value to indicate the status of the dlna server subsystem. + /// public bool EnableServer { get; set; } + /// + /// Gets or sets a value indicating whether detailed dlna server logs are sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// public bool EnableDebugLog { get; set; } - public bool BlastAliveMessages { get; set; } - - public bool SendOnlyMatchedHost { get; set; } + /// + /// Gets or sets a value indicating whether whether detailed playTo debug logs are sent to the console/log. + /// If the setting "Emby.Dlna.PlayTo": "Debug" msut be set in logging.default.json for this property to work. + /// + public bool EnablePlayToTracing { get; set; } + /// + /// Gets or sets the ssdp client discovery interval time (in seconds). + /// This is the time after which the server will send a ssdp search request. + /// public int ClientDiscoveryIntervalSeconds { get; set; } - public int BlastAliveMessageIntervalSeconds { get; set; } + /// + /// Gets or sets the frequency at which ssdp alive notifications are transmitted. + /// + public int AliveMessageIntervalSeconds { get; set; } + /// + /// Gets or sets the frequency at which ssdp alive notifications are transmitted. MIGRATING - TO BE REMOVED ONCE WEB HAS BEEN ALTERED. + /// + public int BlastAliveMessageIntervalSeconds + { + get + { + return AliveMessageIntervalSeconds; + } + + set + { + AliveMessageIntervalSeconds = value; + } + } + + /// + /// Gets or sets the default user account that the dlna server uses. + /// public string DefaultUserId { get; set; } + + /// + /// Gets or sets a value indicating whether playTo device profiles should be created. + /// + public bool AutoCreatePlayToProfiles { get; set; } + + /// + /// Gets or sets a value indicating whether OBSOLETE. + /// + public bool BlastAliveMessages { get; set; } = true; + + /// + /// gets or sets a value indicating whether OBSOLETE. + /// + public bool SendOnlyMatchedHost { get; set; } = true; } } diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs index f5a7eca720..916044a0cc 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManagerService.cs @@ -9,11 +9,21 @@ using Microsoft.Extensions.Logging; namespace Emby.Dlna.ConnectionManager { + /// + /// Defines the . + /// public class ConnectionManagerService : BaseService, IConnectionManager { private readonly IDlnaManager _dlna; private readonly IServerConfigurationManager _config; + /// + /// Initializes a new instance of the class. + /// + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance.. + /// The for use with the instance.. public ConnectionManagerService( IDlnaManager dlna, IServerConfigurationManager config, @@ -28,7 +38,7 @@ namespace Emby.Dlna.ConnectionManager /// public string GetServiceXml() { - return new ConnectionManagerXmlBuilder().GetXml(); + return ConnectionManagerXmlBuilder.GetXml(); } /// diff --git a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs index c8db5a3674..c484dac542 100644 --- a/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ConnectionManagerXmlBuilder.cs @@ -6,45 +6,57 @@ using Emby.Dlna.Service; namespace Emby.Dlna.ConnectionManager { - public class ConnectionManagerXmlBuilder + /// + /// Defines the . + /// + public static class ConnectionManagerXmlBuilder { - public string GetXml() + /// + /// Gets the ConnectionManager:1 service template. + /// See http://upnp.org/specs/av/UPnP-av-ConnectionManager-v1-Service.pdf. + /// + /// An XML description of this service. + public static string GetXml() { - return new ServiceXmlBuilder().GetXml(new ServiceActionListBuilder().GetActions(), GetStateVariables()); + return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables()); } + /// + /// Get the list of state variables for this invocation. + /// + /// The . private static IEnumerable GetStateVariables() { - var list = new List(); - - list.Add(new StateVariable + var list = new List { - Name = "SourceProtocolInfo", - DataType = "string", - SendsEvents = true - }); + new StateVariable + { + Name = "SourceProtocolInfo", + DataType = "string", + SendsEvents = true + }, - list.Add(new StateVariable - { - Name = "SinkProtocolInfo", - DataType = "string", - SendsEvents = true - }); + new StateVariable + { + Name = "SinkProtocolInfo", + DataType = "string", + SendsEvents = true + }, - list.Add(new StateVariable - { - Name = "CurrentConnectionIDs", - DataType = "string", - SendsEvents = true - }); + new StateVariable + { + Name = "CurrentConnectionIDs", + DataType = "string", + SendsEvents = true + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_ConnectionStatus", - DataType = "string", - SendsEvents = false, + new StateVariable + { + Name = "A_ARG_TYPE_ConnectionStatus", + DataType = "string", + SendsEvents = false, - AllowedValues = new[] + AllowedValues = new[] { "OK", "ContentFormatMismatch", @@ -52,55 +64,56 @@ namespace Emby.Dlna.ConnectionManager "UnreliableChannel", "Unknown" } - }); + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_ConnectionManager", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_ConnectionManager", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_Direction", - DataType = "string", - SendsEvents = false, + new StateVariable + { + Name = "A_ARG_TYPE_Direction", + DataType = "string", + SendsEvents = false, - AllowedValues = new[] + AllowedValues = new[] { "Output", "Input" } - }); + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_ProtocolInfo", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_ProtocolInfo", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_ConnectionID", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_ConnectionID", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_AVTransportID", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_AVTransportID", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_RcsID", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_RcsID", + DataType = "ui4", + SendsEvents = false + } + }; return list; } diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index d4cc653942..2f8d197a7a 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -11,10 +11,19 @@ using Microsoft.Extensions.Logging; namespace Emby.Dlna.ConnectionManager { + /// + /// Defines the . + /// public class ControlHandler : BaseControlHandler { private readonly DeviceProfile _profile; + /// + /// Initializes a new instance of the class. + /// + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile) : base(config, logger) { @@ -33,6 +42,10 @@ namespace Emby.Dlna.ConnectionManager throw new ResourceNotFoundException("Unexpected control request name: " + methodName); } + /// + /// Builds the response to the GetProtocolInfo request. + /// + /// The . private void HandleGetProtocolInfo(XmlWriter xmlWriter) { xmlWriter.WriteElementString("Source", _profile.ProtocolInfo); diff --git a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs index b853e7eab6..542c7bfb4b 100644 --- a/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ConnectionManager/ServiceActionListBuilder.cs @@ -5,9 +5,16 @@ using Emby.Dlna.Common; namespace Emby.Dlna.ConnectionManager { - public class ServiceActionListBuilder + /// + /// Defines the . + /// + public static class ServiceActionListBuilder { - public IEnumerable GetActions() + /// + /// Returns an enumerable of the ConnectionManagar:1 DLNA actions. + /// + /// An . + public static IEnumerable GetActions() { var list = new List { @@ -21,6 +28,10 @@ namespace Emby.Dlna.ConnectionManager return list; } + /// + /// Returns the action details for "PrepareForConnection". + /// + /// The . private static ServiceAction PrepareForConnection() { var action = new ServiceAction @@ -80,6 +91,10 @@ namespace Emby.Dlna.ConnectionManager return action; } + /// + /// Returns the action details for "GetCurrentConnectionInfo". + /// + /// The . private static ServiceAction GetCurrentConnectionInfo() { var action = new ServiceAction @@ -146,7 +161,11 @@ namespace Emby.Dlna.ConnectionManager return action; } - private ServiceAction GetProtocolInfo() + /// + /// Returns the action details for "GetProtocolInfo". + /// + /// The . + private static ServiceAction GetProtocolInfo() { var action = new ServiceAction { @@ -170,7 +189,11 @@ namespace Emby.Dlna.ConnectionManager return action; } - private ServiceAction GetCurrentConnectionIDs() + /// + /// Returns the action details for "GetCurrentConnectionIDs". + /// + /// The . + private static ServiceAction GetCurrentConnectionIDs() { var action = new ServiceAction { @@ -187,7 +210,11 @@ namespace Emby.Dlna.ConnectionManager return action; } - private ServiceAction ConnectionComplete() + /// + /// Returns the action details for "ConnectionComplete". + /// + /// The . + private static ServiceAction ConnectionComplete() { var action = new ServiceAction { From c1b3f2c136201cc5d260270a427333ca79b004f2 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sun, 13 Sep 2020 14:31:12 +0100 Subject: [PATCH 0023/1930] ContentDirectory --- .../ContentDirectoryService.cs | 39 +- .../ContentDirectoryXmlBuilder.cs | 229 ++++---- Emby.Dlna/ContentDirectory/ControlHandler.cs | 541 +++++++++++++++--- Emby.Dlna/ContentDirectory/ServerItem.cs | 13 + .../ServiceActionListBuilder.cs | 51 +- Emby.Dlna/ContentDirectory/StubType.cs | 3 + 6 files changed, 668 insertions(+), 208 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs index 5760f260cf..2f3107450c 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs @@ -19,6 +19,9 @@ using Microsoft.Extensions.Logging; namespace Emby.Dlna.ContentDirectory { + /// + /// Defines the . + /// public class ContentDirectoryService : BaseService, IContentDirectory { private readonly ILibraryManager _libraryManager; @@ -33,6 +36,22 @@ namespace Emby.Dlna.ContentDirectory private readonly IMediaEncoder _mediaEncoder; private readonly ITVSeriesManager _tvSeriesManager; + /// + /// Initializes a new instance of the class. + /// + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. + /// The to use in the instance. public ContentDirectoryService( IDlnaManager dlna, IUserDataManager userDataManager, @@ -62,7 +81,10 @@ namespace Emby.Dlna.ContentDirectory _tvSeriesManager = tvSeriesManager; } - private int SystemUpdateId + /// + /// Gets the system id. (A unique id which changes on when our definition changes.) + /// + private static int SystemUpdateId { get { @@ -75,14 +97,18 @@ namespace Emby.Dlna.ContentDirectory /// public string GetServiceXml() { - return new ContentDirectoryXmlBuilder().GetXml(); + return ContentDirectoryXmlBuilder.GetXml(); } /// public Task ProcessControlRequestAsync(ControlRequest request) { - var profile = _dlna.GetProfile(request.Headers) ?? - _dlna.GetDefaultProfile(); + if (request == null) + { + throw new ArgumentNullException(nameof(request)); + } + + var profile = _dlna.GetProfile(request.Headers) ?? _dlna.GetDefaultProfile(); var serverAddress = request.RequestedUrl.Substring(0, request.RequestedUrl.IndexOf("/dlna", StringComparison.OrdinalIgnoreCase)); @@ -107,6 +133,11 @@ namespace Emby.Dlna.ContentDirectory .ProcessControlRequestAsync(request); } + /// + /// Get the user stored in the device profile. + /// + /// The . + /// The . private User GetUser(DeviceProfile profile) { if (!string.IsNullOrEmpty(profile.UserId)) diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs index 743dcc5161..3edaabb70e 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryXmlBuilder.cs @@ -6,143 +6,154 @@ using Emby.Dlna.Service; namespace Emby.Dlna.ContentDirectory { - public class ContentDirectoryXmlBuilder + /// + /// Defines the . + /// + public static class ContentDirectoryXmlBuilder { - public string GetXml() + /// + /// Gets the ContentDirectory:1 service template. + /// See http://upnp.org/specs/av/UPnP-av-ContentDirectory-v1-Service.pdf. + /// + /// An XML description of this service. + public static string GetXml() { - return new ServiceXmlBuilder().GetXml( - new ServiceActionListBuilder().GetActions(), - GetStateVariables()); + return new ServiceXmlBuilder().GetXml(ServiceActionListBuilder.GetActions(), GetStateVariables()); } + /// + /// Get the list of state variables for this invocation. + /// + /// The . private static IEnumerable GetStateVariables() { - var list = new List(); - - list.Add(new StateVariable + var list = new List { - Name = "A_ARG_TYPE_Filter", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_Filter", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_SortCriteria", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_SortCriteria", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_Index", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_Index", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_Count", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_Count", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_UpdateID", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_UpdateID", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "SearchCapabilities", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "SearchCapabilities", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "SortCapabilities", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "SortCapabilities", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "SystemUpdateID", - DataType = "ui4", - SendsEvents = true - }); + new StateVariable + { + Name = "SystemUpdateID", + DataType = "ui4", + SendsEvents = true + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_SearchCriteria", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_SearchCriteria", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_Result", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_Result", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_ObjectID", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_ObjectID", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_BrowseFlag", - DataType = "string", - SendsEvents = false, + new StateVariable + { + Name = "A_ARG_TYPE_BrowseFlag", + DataType = "string", + SendsEvents = false, - AllowedValues = new[] + AllowedValues = new[] { "BrowseMetadata", "BrowseDirectChildren" } - }); + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_BrowseLetter", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_BrowseLetter", + DataType = "string", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_CategoryType", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_CategoryType", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_RID", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_RID", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_PosSec", - DataType = "ui4", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_PosSec", + DataType = "ui4", + SendsEvents = false + }, - list.Add(new StateVariable - { - Name = "A_ARG_TYPE_Featurelist", - DataType = "string", - SendsEvents = false - }); + new StateVariable + { + Name = "A_ARG_TYPE_Featurelist", + DataType = "string", + SendsEvents = false + } + }; return list; } diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4b108b89ea..31f8ca7720 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1,6 +1,5 @@ -#pragma warning disable CS1591 - using System; +using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -8,6 +7,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Xml; +using Emby.Dlna.Configuration; using Emby.Dlna.Didl; using Emby.Dlna.Service; using Jellyfin.Data.Entities; @@ -38,6 +38,9 @@ using Series = MediaBrowser.Controller.Entities.TV.Series; namespace Emby.Dlna.ContentDirectory { + /// + /// Defines the . + /// public class ControlHandler : BaseControlHandler { private const string NsDc = "http://purl.org/dc/elements/1.1/"; @@ -58,6 +61,24 @@ namespace Emby.Dlna.ContentDirectory private readonly DeviceProfile _profile; + /// + /// Initializes a new instance of the class. + /// + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The server address to use in this instance> for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The system id for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. + /// The for use with the instance. public ControlHandler( ILogger logger, ILibraryManager libraryManager, @@ -102,6 +123,16 @@ namespace Emby.Dlna.ContentDirectory /// protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) { + if (xmlWriter == null) + { + throw new ArgumentNullException(nameof(xmlWriter)); + } + + if (methodParams == null) + { + throw new ArgumentNullException(nameof(methodParams)); + } + const string DeviceId = "test"; if (string.Equals(methodName, "GetSearchCapabilities", StringComparison.OrdinalIgnoreCase)) @@ -167,6 +198,10 @@ namespace Emby.Dlna.ContentDirectory throw new ResourceNotFoundException("Unexpected control request name: " + methodName); } + /// + /// Adds a "XSetBookmark" element to the xml document. + /// + /// The . private void HandleXSetBookmark(IDictionary sparams) { var id = sparams["ObjectID"]; @@ -189,41 +224,69 @@ namespace Emby.Dlna.ContentDirectory CancellationToken.None); } - private void HandleGetSearchCapabilities(XmlWriter xmlWriter) + /// + /// Adds the "SearchCaps" element to the xml document. + /// + /// The . + private static void HandleGetSearchCapabilities(XmlWriter xmlWriter) { xmlWriter.WriteElementString( "SearchCaps", "res@resolution,res@size,res@duration,dc:title,dc:creator,upnp:actor,upnp:artist,upnp:genre,upnp:album,dc:date,upnp:class,@id,@refID,@protocolInfo,upnp:author,dc:description,pv:avKeywords"); } - private void HandleGetSortCapabilities(XmlWriter xmlWriter) + /// + /// Adds the "SortCaps" element to the xml document. + /// + /// The . + private static void HandleGetSortCapabilities(XmlWriter xmlWriter) { xmlWriter.WriteElementString( "SortCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating"); } - private void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter) + /// + /// Adds the "SortExtensionCaps" element to the xml document. + /// + /// The . + private static void HandleGetSortExtensionCapabilities(XmlWriter xmlWriter) { xmlWriter.WriteElementString( "SortExtensionCaps", "res@duration,res@size,res@bitrate,dc:date,dc:title,dc:size,upnp:album,upnp:artist,upnp:albumArtist,upnp:episodeNumber,upnp:genre,upnp:originalTrackNumber,upnp:rating"); } + /// + /// Adds the "Id" element to the xml document. + /// + /// The . private void HandleGetSystemUpdateID(XmlWriter xmlWriter) { xmlWriter.WriteElementString("Id", _systemUpdateId.ToString(CultureInfo.InvariantCulture)); } - private void HandleGetFeatureList(XmlWriter xmlWriter) + /// + /// Adds the "FeatureList" element to the xml document. + /// + /// The . + private static void HandleGetFeatureList(XmlWriter xmlWriter) { xmlWriter.WriteElementString("FeatureList", WriteFeatureListXml()); } - private void HandleXGetFeatureList(XmlWriter xmlWriter) + /// + /// Adds the "FeatureList" element to the xml document. + /// + /// The . + private static void HandleXGetFeatureList(XmlWriter xmlWriter) => HandleGetFeatureList(xmlWriter); - private string WriteFeatureListXml() + /// + /// Builds a static feature list. + /// + /// The xml feature list. + private static string WriteFeatureListXml() { // TODO: clean this up var builder = new StringBuilder(); @@ -242,9 +305,16 @@ namespace Emby.Dlna.ContentDirectory return builder.ToString(); } - public string GetValueOrDefault(IDictionary sparams, string key, string defaultValue) + /// + /// Returns the value in the key of the dictionary, or defaultValue if it doesn't exist. + /// + /// The . + /// The key. + /// The defaultValue. + /// The . + public static string GetValueOrDefault(IDictionary sparams, string key, string defaultValue) { - if (sparams.TryGetValue(key, out string val)) + if (sparams != null && sparams.TryGetValue(key, out string val)) { return val; } @@ -252,6 +322,12 @@ namespace Emby.Dlna.ContentDirectory return defaultValue; } + /// + /// Builds the "Browse" xml response. + /// + /// The . + /// The . + /// The device Id to use. private void HandleBrowse(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { var id = sparams["ObjectID"]; @@ -313,7 +389,6 @@ namespace Emby.Dlna.ContentDirectory } else { - var dlnaOptions = _config.GetDlnaConfiguration(); _didlBuilder.WriteItemElement(writer, item, _user, null, null, deviceId, filter); } @@ -326,7 +401,6 @@ namespace Emby.Dlna.ContentDirectory provided = childrenResult.Items.Count; - var dlnaOptions = _config.GetDlnaConfiguration(); foreach (var i in childrenResult.Items) { var childItem = i.Item; @@ -357,12 +431,24 @@ namespace Emby.Dlna.ContentDirectory xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture)); } + /// + /// Builds the response to the "X_BrowseByLetter request. + /// + /// The . + /// The . + /// The device id. private void HandleXBrowseByLetter(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { // TODO: Implement this method HandleSearch(xmlWriter, sparams, deviceId); } + /// + /// Builds a response to the "Search" request. + /// + /// The xmlWriter. + /// The sparams. + /// The deviceId. private void HandleSearch(XmlWriter xmlWriter, IDictionary sparams, string deviceId) { var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", string.Empty)); @@ -442,7 +528,17 @@ namespace Emby.Dlna.ContentDirectory xmlWriter.WriteElementString("UpdateID", _systemUpdateId.ToString(CultureInfo.InvariantCulture)); } - private QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit) + /// + /// Returns the child items meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . + private static QueryResult GetChildrenSorted(BaseItem item, User user, SearchCriteria search, SortCriteria sort, int? startIndex, int? limit) { var folder = (Folder)item; @@ -494,11 +590,25 @@ namespace Emby.Dlna.ContentDirectory }); } - private DtoOptions GetDtoOptions() + /// + /// Returns a new DtoOptions object. + /// + /// The . + private static DtoOptions GetDtoOptions() { return new DtoOptions(true); } + /// + /// Returns the User items meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetUserItems(BaseItem item, StubType? stubType, User user, SortCriteria sort, int? startIndex, int? limit) { if (item is MusicGenre) @@ -568,6 +678,14 @@ namespace Emby.Dlna.ContentDirectory return ToResult(queryResult); } + /// + /// Returns the Live Tv Channels meeting the criteria. + /// + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetLiveTvChannels(User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -584,6 +702,16 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music folders meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetMusicFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -643,57 +771,58 @@ namespace Emby.Dlna.ContentDirectory return GetMusicGenres(item, user, query); } - var list = new List(); - - list.Add(new ServerItem(item) + var list = new List { - StubType = StubType.Latest - }); + new ServerItem(item) + { + StubType = StubType.Latest + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Playlists - }); + new ServerItem(item) + { + StubType = StubType.Playlists + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Albums - }); + new ServerItem(item) + { + StubType = StubType.Albums + }, - list.Add(new ServerItem(item) - { - StubType = StubType.AlbumArtists - }); + new ServerItem(item) + { + StubType = StubType.AlbumArtists + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Artists - }); + new ServerItem(item) + { + StubType = StubType.Artists + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Songs - }); + new ServerItem(item) + { + StubType = StubType.Songs + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Genres - }); + new ServerItem(item) + { + StubType = StubType.Genres + }, - list.Add(new ServerItem(item) - { - StubType = StubType.FavoriteArtists - }); + new ServerItem(item) + { + StubType = StubType.FavoriteArtists + }, - list.Add(new ServerItem(item) - { - StubType = StubType.FavoriteAlbums - }); + new ServerItem(item) + { + StubType = StubType.FavoriteAlbums + }, - list.Add(new ServerItem(item) - { - StubType = StubType.FavoriteSongs - }); + new ServerItem(item) + { + StubType = StubType.FavoriteSongs + } + }; return new QueryResult { @@ -702,6 +831,16 @@ namespace Emby.Dlna.ContentDirectory }; } + /// + /// Returns the movie folders meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetMovieFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -776,6 +915,13 @@ namespace Emby.Dlna.ContentDirectory }; } + /// + /// Returns the folders meeting the criteria. + /// + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetFolders(User user, int? startIndex, int? limit) { var folders = _libraryManager.GetUserRootFolder().GetChildren(user, true) @@ -796,6 +942,16 @@ namespace Emby.Dlna.ContentDirectory limit); } + /// + /// Returns the TV folders meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetTvFolders(BaseItem item, User user, StubType? stubType, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -840,42 +996,43 @@ namespace Emby.Dlna.ContentDirectory return GetGenres(item, user, query); } - var list = new List(); - - list.Add(new ServerItem(item) + var list = new List { - StubType = StubType.ContinueWatching - }); + new ServerItem(item) + { + StubType = StubType.ContinueWatching + }, - list.Add(new ServerItem(item) - { - StubType = StubType.NextUp - }); + new ServerItem(item) + { + StubType = StubType.NextUp + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Latest - }); + new ServerItem(item) + { + StubType = StubType.Latest + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Series - }); + new ServerItem(item) + { + StubType = StubType.Series + }, - list.Add(new ServerItem(item) - { - StubType = StubType.FavoriteSeries - }); + new ServerItem(item) + { + StubType = StubType.FavoriteSeries + }, - list.Add(new ServerItem(item) - { - StubType = StubType.FavoriteEpisodes - }); + new ServerItem(item) + { + StubType = StubType.FavoriteEpisodes + }, - list.Add(new ServerItem(item) - { - StubType = StubType.Genres - }); + new ServerItem(item) + { + StubType = StubType.Genres + } + }; return new QueryResult { @@ -884,6 +1041,13 @@ namespace Emby.Dlna.ContentDirectory }; } + /// + /// Returns the Movies that are part watched that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMovieContinueWatching(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -904,6 +1068,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the series meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetSeries(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -917,6 +1088,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the Movie folders meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMovieMovies(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -930,6 +1108,12 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the Movie collections meeting the criteria. + /// + /// The see cref="User"/>. + /// The see cref="InternalItemsQuery"/>. + /// The . private QueryResult GetMovieCollections(User user, InternalItemsQuery query) { query.Recursive = true; @@ -943,6 +1127,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the Music albums meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicAlbums(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -956,6 +1147,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the Music songs meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicSongs(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -969,6 +1167,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the songs tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetFavoriteSongs(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -982,6 +1187,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the series tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetFavoriteSeries(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -995,6 +1207,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the episodes tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetFavoriteEpisodes(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -1008,6 +1227,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the movies tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMovieFavorites(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -1021,6 +1247,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// /// Returns the albums tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetFavoriteAlbums(BaseItem parent, User user, InternalItemsQuery query) { query.Recursive = true; @@ -1034,6 +1267,14 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the genres meeting the criteria. + /// The GetGenres. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetGenres(BaseItem parent, User user, InternalItemsQuery query) { var genresResult = _libraryManager.GetGenres(new InternalItemsQuery(user) @@ -1052,6 +1293,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music genres meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicGenres(BaseItem parent, User user, InternalItemsQuery query) { var genresResult = _libraryManager.GetMusicGenres(new InternalItemsQuery(user) @@ -1070,6 +1318,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music albums by artist that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicAlbumArtists(BaseItem parent, User user, InternalItemsQuery query) { var artists = _libraryManager.GetAlbumArtists(new InternalItemsQuery(user) @@ -1088,6 +1343,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music artists meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicArtists(BaseItem parent, User user, InternalItemsQuery query) { var artists = _libraryManager.GetArtists(new InternalItemsQuery(user) @@ -1106,6 +1368,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the artists tagged as favourite that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetFavoriteArtists(BaseItem parent, User user, InternalItemsQuery query) { var artists = _libraryManager.GetArtists(new InternalItemsQuery(user) @@ -1125,6 +1394,12 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music playlists meeting the criteria. + /// + /// The user. + /// The query. + /// The . private QueryResult GetMusicPlaylists(User user, InternalItemsQuery query) { query.Parent = null; @@ -1137,6 +1412,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the latest music meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMusicLatest(BaseItem parent, User user, InternalItemsQuery query) { query.OrderBy = Array.Empty<(string, SortOrder)>(); @@ -1155,6 +1437,12 @@ namespace Emby.Dlna.ContentDirectory return ToResult(items); } + /// + /// Returns the next up item meeting the criteria. + /// + /// The . + /// The . + /// The . private QueryResult GetNextUp(BaseItem parent, InternalItemsQuery query) { query.OrderBy = Array.Empty<(string, SortOrder)>(); @@ -1172,6 +1460,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the latest tv meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetTvLatest(BaseItem parent, User user, InternalItemsQuery query) { query.OrderBy = Array.Empty<(string, SortOrder)>(); @@ -1190,6 +1485,13 @@ namespace Emby.Dlna.ContentDirectory return ToResult(items); } + /// + /// Returns the latest movies meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . private QueryResult GetMovieLatest(BaseItem parent, User user, InternalItemsQuery query) { query.OrderBy = Array.Empty<(string, SortOrder)>(); @@ -1208,6 +1510,16 @@ namespace Emby.Dlna.ContentDirectory return ToResult(items); } + /// + /// Returns music artist items that meet the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetMusicArtistItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -1228,6 +1540,16 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the genre items meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -1252,6 +1574,16 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } + /// + /// Returns the music genre items meeting the criteria. + /// + /// The . + /// The . + /// The . + /// The . + /// The start index. + /// The maximum number to return. + /// The . private QueryResult GetMusicGenreItems(BaseItem item, Guid parentId, User user, SortCriteria sort, int? startIndex, int? limit) { var query = new InternalItemsQuery(user) @@ -1272,7 +1604,12 @@ namespace Emby.Dlna.ContentDirectory return ToResult(result); } - private QueryResult ToResult(BaseItem[] result) + /// + /// Converts a array into a . + /// + /// An array of . + /// A . + private static QueryResult ToResult(BaseItem[] result) { var serverItems = result .Select(i => new ServerItem(i)) @@ -1285,7 +1622,12 @@ namespace Emby.Dlna.ContentDirectory }; } - private QueryResult ToResult(QueryResult result) + /// + /// Converts a to a . + /// + /// A . + /// The . + private static QueryResult ToResult(QueryResult result) { var serverItems = result .Items @@ -1299,7 +1641,13 @@ namespace Emby.Dlna.ContentDirectory }; } - private void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted) + /// + /// Sets the sorting method on a query. + /// + /// The . + /// The . + /// True if pre-sorted. + private static void SetSorting(InternalItemsQuery query, SortCriteria sort, bool isPreSorted) { if (isPreSorted) { @@ -1311,13 +1659,25 @@ namespace Emby.Dlna.ContentDirectory } } - private QueryResult ApplyPaging(QueryResult result, int? startIndex, int? limit) + /// + /// Apply paging to a query. + /// + /// The . + /// The start index. + /// The maximum number to return. + /// A . + private static QueryResult ApplyPaging(QueryResult result, int? startIndex, int? limit) { result.Items = result.Items.Skip(startIndex ?? 0).Take(limit ?? int.MaxValue).ToArray(); return result; } + /// + /// Retreives the ServerItem id. + /// + /// The id. + /// The . private ServerItem GetItemFromObjectId(string id) { return DidlBuilder.IsIdRoot(id) @@ -1326,6 +1686,11 @@ namespace Emby.Dlna.ContentDirectory : ParseItemId(id); } + /// + /// Parses the item id into a . + /// + /// The . + /// The corresponding . private ServerItem ParseItemId(string id) { StubType? stubType = null; diff --git a/Emby.Dlna/ContentDirectory/ServerItem.cs b/Emby.Dlna/ContentDirectory/ServerItem.cs index e406054149..34244000c1 100644 --- a/Emby.Dlna/ContentDirectory/ServerItem.cs +++ b/Emby.Dlna/ContentDirectory/ServerItem.cs @@ -4,8 +4,15 @@ using MediaBrowser.Controller.Entities; namespace Emby.Dlna.ContentDirectory { + /// + /// Defines the . + /// internal class ServerItem { + /// + /// Initializes a new instance of the class. + /// + /// The . public ServerItem(BaseItem item) { Item = item; @@ -16,8 +23,14 @@ namespace Emby.Dlna.ContentDirectory } } + /// + /// Gets or sets the underlying base item. + /// public BaseItem Item { get; set; } + /// + /// Gets or sets the DLNA item type. + /// public StubType? StubType { get; set; } } } diff --git a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs index 921b14e394..7e3db46519 100644 --- a/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs +++ b/Emby.Dlna/ContentDirectory/ServiceActionListBuilder.cs @@ -1,13 +1,18 @@ -#pragma warning disable CS1591 - using System.Collections.Generic; using Emby.Dlna.Common; namespace Emby.Dlna.ContentDirectory { - public class ServiceActionListBuilder + /// + /// Defines the . + /// + public static class ServiceActionListBuilder { - public IEnumerable GetActions() + /// + /// Returns a list of services that this instance provides. + /// + /// An . + public static IEnumerable GetActions() { return new[] { @@ -22,6 +27,10 @@ namespace Emby.Dlna.ContentDirectory }; } + /// + /// Returns the action details for "GetSystemUpdateID". + /// + /// The . private static ServiceAction GetGetSystemUpdateIDAction() { var action = new ServiceAction @@ -39,6 +48,10 @@ namespace Emby.Dlna.ContentDirectory return action; } + /// + /// Returns the action details for "GetSearchCapabilities". + /// + /// The . private static ServiceAction GetSearchCapabilitiesAction() { var action = new ServiceAction @@ -56,6 +69,10 @@ namespace Emby.Dlna.ContentDirectory return action; } + /// + /// Returns the action details for "GetSortCapabilities". + /// + /// The . private static ServiceAction GetSortCapabilitiesAction() { var action = new ServiceAction @@ -73,6 +90,10 @@ namespace Emby.Dlna.ContentDirectory return action; } + /// + /// Returns the action details for "X_GetFeatureList". + /// + /// The . private static ServiceAction GetX_GetFeatureListAction() { var action = new ServiceAction @@ -90,6 +111,10 @@ namespace Emby.Dlna.ContentDirectory return action; } + /// + /// Returns the action details for "Search". + /// + /// The . private static ServiceAction GetSearchAction() { var action = new ServiceAction @@ -170,7 +195,11 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetBrowseAction() + /// + /// Returns the action details for "Browse". + /// + /// The . + private static ServiceAction GetBrowseAction() { var action = new ServiceAction { @@ -250,7 +279,11 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetBrowseByLetterAction() + /// + /// Returns the action details for "X_BrowseByLetter". + /// + /// The . + private static ServiceAction GetBrowseByLetterAction() { var action = new ServiceAction { @@ -337,7 +370,11 @@ namespace Emby.Dlna.ContentDirectory return action; } - private ServiceAction GetXSetBookmarkAction() + /// + /// Returns the action details for "X_SetBookmark". + /// + /// The . + private static ServiceAction GetXSetBookmarkAction() { var action = new ServiceAction { diff --git a/Emby.Dlna/ContentDirectory/StubType.cs b/Emby.Dlna/ContentDirectory/StubType.cs index eee405d3e7..982ae5d68e 100644 --- a/Emby.Dlna/ContentDirectory/StubType.cs +++ b/Emby.Dlna/ContentDirectory/StubType.cs @@ -3,6 +3,9 @@ namespace Emby.Dlna.ContentDirectory { + /// + /// Defines the DLNA item types. + /// public enum StubType { Folder = 0, From b44455ad0d6e78b5baed535c06a7f7d49116d1ee Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Mon, 14 Sep 2020 15:46:38 +0100 Subject: [PATCH 0024/1930] Update based on PR1 changes. --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- .../ApplicationHost.cs | 62 ++- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- .../HdHomerun/HdHomerunUdpStream.cs | 2 +- .../LiveTv/TunerHosts/M3UTunerHost.cs | 2 +- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 2 +- .../DefaultAuthorizationHandler.cs | 2 +- .../Auth/DownloadPolicy/DownloadHandler.cs | 2 +- ...TimeOrIgnoreParentalControlSetupHandler.cs | 2 +- .../FirstTimeSetupOrDefaultHandler.cs | 2 +- .../FirstTimeSetupOrElevatedHandler.cs | 2 +- .../IgnoreParentalControlHandler.cs | 2 +- .../LocalAccessOrRequiresElevationHandler.cs | 2 +- .../LocalAccessPolicy/LocalAccessHandler.cs | 2 +- .../RequiresElevationHandler.cs | 2 +- Jellyfin.Api/Controllers/SystemController.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 2 +- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 463 ++++++++++-------- .../Users/UserManager.cs | 3 +- Jellyfin.Server/CoreAppHost.cs | 2 +- .../IpBasedAccessValidationMiddleware.cs | 2 +- .../Middleware/LanFilteringMiddleware.cs | 2 +- Jellyfin.Server/Program.cs | 4 +- .../MediaBrowser.Common.csproj | 3 +- .../Net}/INetworkManager.cs | 42 +- .../IServerApplicationHost.cs | 26 +- RSSDP/SsdpCommunicationsServer.cs | 2 +- RSSDP/SsdpDevicePublisher.cs | 2 +- .../LocalAccessHandlerTests.cs | 2 +- 31 files changed, 388 insertions(+), 263 deletions(-) rename {Jellyfin.Networking/Manager => MediaBrowser.Common/Net}/INetworkManager.cs (79%) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 98f50c09af..a5da2fc5c8 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -9,7 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index cc04cb03f5..67a352fc93 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -160,6 +160,11 @@ namespace Emby.Server.Implementations } } + /// + /// Gets the singleton instance. + /// + public INetworkManager NetManager { get; internal set; } + /// /// Occurs when [has pending restart changed]. /// @@ -189,11 +194,6 @@ namespace Emby.Server.Implementations /// The plugins. public IReadOnlyList Plugins => _plugins; - /// - /// Gets the NetworkManager object. - /// - private readonly INetworkManager _networkManager; - /// /// Gets the logger factory. /// @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); - _networkManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); + NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); Logger = LoggerFactory.CreateLogger(); @@ -524,7 +524,7 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(_fileSystemManager); ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(_networkManager); + ServiceCollection.AddSingleton(NetManager); ServiceCollection.AddSingleton(); @@ -1116,7 +1116,7 @@ namespace Emby.Server.Implementations } public IEnumerable GetWakeOnLanInfo() - => _networkManager.GetMacAddresses() + => NetManager.GetMacAddresses() .Select(i => new WakeOnLanInfo(i)) .ToList(); @@ -1138,7 +1138,7 @@ namespace Emby.Server.Implementations public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps; /// - public string GetSmartApiUrl(object source) + public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) { // Published server ends with a / if (_startupOptions.PublishedServerUrl != null) @@ -1147,7 +1147,47 @@ namespace Emby.Server.Implementations return _startupOptions.PublishedServerUrl.ToString().Trim('/'); } - string smart = _networkManager.GetBindInterface(source, out int? port); + string smart = NetManager.GetBindInterface(ipAddress, out port); + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return smart.Trim('/'); + } + + return GetLocalApiUrl(smart.Trim('/'), null, port); + } + + /// + public string GetSmartApiUrl(HttpRequest request, int? port = null) + { + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) + { + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + } + + string smart = NetManager.GetBindInterface(request, out port); + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return smart.Trim('/'); + } + + return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port); + } + + /// + public string GetSmartApiUrl(string hostname, int? port = null) + { + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) + { + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + } + + string smart = NetManager.GetBindInterface(hostname, out port); // If the smartAPI doesn't start with http then treat it as a host or ip. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) @@ -1155,7 +1195,7 @@ namespace Emby.Server.Implementations return smart.Trim('/'); } - return GetLocalApiUrl(smart.Trim('/'), source is HttpRequest request ? request.Scheme : null, port); + return GetLocalApiUrl(smart.Trim('/'), null, port); } /// diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 1cf129ad2d..27937d2f84 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -10,7 +10,7 @@ using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 02ee302d0d..efb6d162ac 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,7 +7,7 @@ using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index f297ecd5df..531a785a07 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -8,7 +8,7 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index 08746b346b..bd76b93bf4 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,7 +1,7 @@ using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index 69e6a8fb2d..dfa366796f 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs index d1297119cd..3183d13186 100644 --- a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs +++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs index 53b5d47787..1cee962e9f 100644 --- a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs index abdf2858d0..214198e001 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs index ada8a0d4ec..9867ea4ca6 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs index 475e3cdac4..affd955515 100644 --- a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs +++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index d022c9067f..fab464b503 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs index 418d63de68..801ee2f4c6 100644 --- a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs @@ -1,5 +1,5 @@ using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs index a1cddbca3e..7adf72c3d3 100644 --- a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 6876b47b44..b87e275d0f 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -8,7 +8,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 152e650bc0..c60497e304 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -7,7 +7,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.UserDtos; using Jellyfin.Data.Enums; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 3be8734b94..f81fb88fb1 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -8,7 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index d63e3ab118..9e4def774a 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -6,7 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 36a0a94a09..760938c40f 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -7,6 +7,7 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; using MediaBrowser.Model.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -19,8 +20,6 @@ namespace Jellyfin.Networking.Manager /// public class NetworkManager : INetworkManager, IDisposable { - private static NetworkManager? _instance; - /// /// Contains the description of the interface along with its index. /// @@ -48,7 +47,7 @@ namespace Jellyfin.Networking.Manager /// /// Holds the bind address overrides. /// - private readonly Dictionary _overrideUrls; + private readonly Dictionary _publishedServerUrls; /// /// Used to stop "event-racing conditions". @@ -105,7 +104,7 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses = new NetCollection(unique: false); _macAddresses = new List(); _interfaceNames = new SortedList(); - _overrideUrls = new Dictionary(); + _publishedServerUrls = new Dictionary(); UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); if (!IsIP6Enabled && !IsIP4Enabled) @@ -117,8 +116,6 @@ namespace Jellyfin.Networking.Manager NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; _configurationManager.ConfigurationUpdated += ConfigurationUpdated; - - Instance = this; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. @@ -127,19 +124,6 @@ namespace Jellyfin.Networking.Manager /// public event EventHandler? NetworkChanged; - /// - /// Gets the singleton of this object. - /// - public static NetworkManager Instance - { - get => GetInstance(); - - internal set - { - _instance = value; - } - } - /// /// Gets the unique network location signature, which is updated on every network change. /// @@ -176,7 +160,7 @@ namespace Jellyfin.Networking.Manager /// /// Gets the Published server override list. /// - public Dictionary PublishedServerOverrides => _overrideUrls; + public Dictionary PublishedServerUrls => _publishedServerUrls; /// public void Dispose() @@ -198,9 +182,12 @@ namespace Jellyfin.Networking.Manager /// public bool IsGatewayInterface(object? addressObj) { - var address = (addressObj is IPAddress addressIP) ? - addressIP : (addressObj is IPObject addressIPObj) ? - addressIPObj.Address : IPAddress.None; + var address = addressObj switch + { + IPAddress addressIp => addressIp, + IPObject addressIpObj => addressIpObj.Address, + _ => IPAddress.None + }; lock (_intLock) { @@ -320,243 +307,127 @@ namespace Jellyfin.Networking.Manager } /// - public string GetBindInterface(object? source, out int? port) + public string GetBindInterface(string source, out int? port) { - bool chromeCast = false; - port = null; - // Parse the source object in an attempt to discover where the request originated. - IPObject sourceAddr; - if (source is HttpRequest sourceReq) + if (!string.IsNullOrEmpty(source)) { - port = sourceReq.Host.Port; - if (IPHost.TryParse(sourceReq.Host.Host, out IPHost host)) + if (string.Equals(source, "chromecast", StringComparison.OrdinalIgnoreCase)) { - sourceAddr = host; - } - else - { - // Assume it's external, as we cannot resolve the host. - sourceAddr = IPHost.None; - } - } - else if (source is string sourceStr && !string.IsNullOrEmpty(sourceStr)) - { - if (string.Equals(sourceStr, "chromecast", StringComparison.OrdinalIgnoreCase)) - { - chromeCast = true; // Just assign a variable so has source = true; - sourceAddr = IPNetAddress.IP4Loopback; + return GetBindInterface(IPNetAddress.IP4Loopback, out port); } - if (IPHost.TryParse(sourceStr, out IPHost host)) + if (IPHost.TryParse(source, out IPHost host)) { - sourceAddr = host; - } - else - { - // Assume it's external, as we cannot resolve the host. - sourceAddr = IPHost.None; + return GetBindInterface(host, out port); } } - else if (source is IPAddress sourceIP) + + return GetBindInterface(IPHost.None, out port); + } + + /// + public string GetBindInterface(IPAddress source, out int? port) + { + return GetBindInterface(new IPNetAddress(source), out port); + } + + /// + public string GetBindInterface(HttpRequest source, out int? port) + { + string result; + + if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host)) { - sourceAddr = new IPNetAddress(sourceIP); + result = GetBindInterface(host, out port); + port ??= source.Host.Port; } else { - // If we have no idea, then assume it came from an external address. - sourceAddr = IPHost.None; + result = GetBindInterface(IPNetAddress.None, out port); + port ??= source?.Host.Port; } + return result; + } + + /// + public string GetBindInterface(IPObject source, out int? port) + { + port = null; + bool isChromeCast = source == IPNetAddress.IP4Loopback; // Do we have a source? - bool haveSource = !sourceAddr.Address.Equals(IPAddress.None); + bool haveSource = !source.Address.Equals(IPAddress.None); + bool isExternal = false; if (haveSource) { - if (!IsIP6Enabled && sourceAddr.AddressFamily == AddressFamily.InterNetworkV6) + if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) { _logger.LogWarning("IPv6 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); } - if (!IsIP4Enabled && sourceAddr.AddressFamily == AddressFamily.InterNetwork) + if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) { _logger.LogWarning("IPv4 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); } - } - bool isExternal = haveSource && !IsInLocalNetwork(sourceAddr); + isExternal = !IsInLocalNetwork(source); - string bindPreference = string.Empty; - if (haveSource) - { - // Check for user override. - foreach (var addr in _overrideUrls) + if (MatchesPublishedServerUrl(source, isExternal, isChromeCast, out string result, out port)) { - // Remaining. Match anything. - if (addr.Key.Equals(IPAddress.Broadcast)) - { - bindPreference = addr.Value; - break; - } - else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && (isExternal || chromeCast)) - { - // External. - bindPreference = addr.Value; - break; - } - else if (addr.Key.Contains(sourceAddr)) - { - // Match ip address. - bindPreference = addr.Value; - break; - } + _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, result, port); + return result; } } _logger.LogDebug("GetBindInterface: Souce: {0}, External: {1}:", haveSource, isExternal); - if (!string.IsNullOrEmpty(bindPreference)) - { - // Has it got a port defined? - var parts = bindPreference.Split(':'); - if (parts.Length > 1) - { - if (int.TryParse(parts[1], out int p)) - { - bindPreference = parts[0]; - port = p; - } - } - - _logger.LogInformation("{0}: Using BindAddress {1}:{2}", sourceAddr, bindPreference, port); - return bindPreference; - } - - string ipresult; - // No preference given, so move on to bind addresses. lock (_intLock) { - var nc = _bindAddresses.Exclude(_bindExclusions).Where(p => !p.IsLoopback()); - - int count = nc.Count(); - if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses.Equals(IPAddress.IPv6Any))) + if (MatchesBindInterface(source, isExternal, out string result)) { - // Ignore IPAny addresses. - count = 0; + return result; } - if (count != 0) + if (isExternal && MatchesExternalInterface(source, out result)) { - // Check to see if any of the bind interfaces are in the same subnet. - - IEnumerable bindResult; - IPAddress? defaultGateway = null; - - if (isExternal) - { - // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - bindResult = nc.Where(p => !IsInLocalNetwork(p)).OrderBy(p => p.Tag); - defaultGateway = bindResult.FirstOrDefault()?.Address; - bindResult = bindResult.Where(p => p.Contains(sourceAddr)).OrderBy(p => p.Tag); - } - else - { - // Look for the best internal address. - bindResult = nc.Where(p => IsInLocalNetwork(p) && p.Contains(sourceAddr)).OrderBy(p => p.Tag); - } - - if (bindResult.Any()) - { - ipresult = FormatIP6String(bindResult.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", sourceAddr, ipresult); - return ipresult; - } - - if (isExternal && defaultGateway != null) - { - ipresult = FormatIP6String(defaultGateway); - _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", sourceAddr, ipresult); - return ipresult; - } - - ipresult = FormatIP6String(nc.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", sourceAddr, ipresult); - - if (isExternal) - { - // TODO: remove this after testing. - _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", sourceAddr); - } - - return ipresult; - } - - if (isExternal) - { - // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaceAddresses - .Exclude(_bindExclusions) - .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag); - - if (extResult.Any()) - { - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in extResult) - { - if (!IsInLocalNetwork(intf) && intf.Contains(sourceAddr)) - { - ipresult = FormatIP6String(intf.Address); - _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", sourceAddr, ipresult); - return ipresult; - } - } - - ipresult = FormatIP6String(extResult.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", sourceAddr, ipresult); - return ipresult; - } - - // Have to return something, so return an internal address - - // TODO: remove this after testing. - _logger.LogWarning("{0}: External request received, however, no WAN interface found.", sourceAddr); + return result; } // Get the first LAN interface address that isn't a loopback. - var result = _interfaceAddresses + var interfaces = new NetCollection(_interfaceAddresses .Exclude(_bindExclusions) .Where(p => IsInLocalNetwork(p)) - .OrderBy(p => p.Tag); + .OrderBy(p => p.Tag)); - if (result.Any()) + if (interfaces.Count > 0) { if (haveSource) { // Does the request originate in one of the interface subnets? // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in result) + foreach (var intf in interfaces) { - if (intf.Contains(sourceAddr)) + if (intf.Contains(source)) { - ipresult = FormatIP6String(intf.Address); - _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", sourceAddr, ipresult); - return ipresult; + result = FormatIP6String(intf.Address); + _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result); + return result; } } } - ipresult = FormatIP6String(result.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", sourceAddr, ipresult); - return ipresult; + result = FormatIP6String(interfaces.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result); + return result; } // There isn't any others, so we'll use the loopback. - ipresult = IsIP6Enabled ? "::" : "127.0.0.1"; - _logger.LogWarning("{0}: GetBindInterface: Loopback return.", sourceAddr, ipresult); - return ipresult; + result = IsIP6Enabled ? "::" : "127.0.0.1"; + _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result); + return result; } } @@ -771,16 +642,6 @@ namespace Jellyfin.Networking.Manager } } - private static NetworkManager GetInstance() - { - if (_instance == null) - { - throw new ApplicationException("NetworkManager is not initialised."); - } - - return _instance; - } - private void ConfigurationUpdated(object? sender, EventArgs args) { UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); @@ -944,7 +805,7 @@ namespace Jellyfin.Networking.Manager { lock (_intLock) { - _overrideUrls.Clear(); + _publishedServerUrls.Clear(); } return; @@ -952,7 +813,7 @@ namespace Jellyfin.Networking.Manager lock (_intLock) { - _overrideUrls.Clear(); + _publishedServerUrls.Clear(); foreach (var entry in overrides) { @@ -966,15 +827,15 @@ namespace Jellyfin.Networking.Manager var replacement = parts[1].Trim(); if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase)) { - _overrideUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; + _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; } else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) { - _overrideUrls[new IPNetAddress(IPAddress.Any)] = replacement; + _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; } else if (TryParseInterface(parts[0], out IPNetAddress address)) { - _overrideUrls[address] = replacement; + _publishedServerUrls[address] = replacement; } else { @@ -1199,5 +1060,179 @@ namespace Jellyfin.Networking.Manager } } } + + /// + /// Attempts to match the source against a user defined bind interface. + /// + /// IP source address to use. + /// True if the source is in the external subnet. + /// True if the request is for a chromecast device. + /// The published server url that matches the source address. + /// The resultant port, if one exists. + /// True if a match is found. + private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, bool isChromeCast, out string bindPreference, out int? port) + { + bindPreference = string.Empty; + port = null; + + // Check for user override. + foreach (var addr in _publishedServerUrls) + { + // Remaining. Match anything. + if (addr.Key.Equals(IPAddress.Broadcast)) + { + bindPreference = addr.Value; + break; + } + else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && (isExternal || isChromeCast)) + { + // External. + bindPreference = addr.Value; + break; + } + else if (addr.Key.Contains(source)) + { + // Match ip address. + bindPreference = addr.Value; + break; + } + } + + if (!string.IsNullOrEmpty(bindPreference)) + { + // Has it got a port defined? + var parts = bindPreference.Split(':'); + if (parts.Length > 1) + { + if (int.TryParse(parts[1], out int p)) + { + bindPreference = parts[0]; + port = p; + } + } + + return true; + } + + return false; + } + + /// + /// Attempts to match the source against a user defined bind interface. + /// + /// IP source address to use. + /// True if the source is in the external subnet. + /// The result, if a match is found. + /// True if a match is found. + private bool MatchesBindInterface(IPObject source, bool isExternal, out string result) + { + result = string.Empty; + var nc = new NetCollection(_bindAddresses.Exclude(_bindExclusions).Where(p => !p.IsLoopback())); + + int count = nc.Count; + if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) + { + // Ignore IPAny addresses. + count = 0; + } + + if (count != 0) + { + // Check to see if any of the bind interfaces are in the same subnet. + + NetCollection bindResult; + IPAddress? defaultGateway = null; + IPAddress? bindAddress; + + if (isExternal) + { + // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. + bindResult = new NetCollection(nc + .Where(p => !IsInLocalNetwork(p)) + .OrderBy(p => p.Tag)); + defaultGateway = bindResult.FirstOrDefault()?.Address; + bindAddress = bindResult + .Where(p => p.Contains(source)) + .OrderBy(p => p.Tag) + .FirstOrDefault()?.Address; + } + else + { + // Look for the best internal address. + bindAddress = nc + .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) + .OrderBy(p => p.Tag) + .FirstOrDefault()?.Address; + } + + if (bindAddress != null) + { + result = FormatIP6String(bindAddress); + _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", source, result); + return true; + } + + if (isExternal && defaultGateway != null) + { + result = FormatIP6String(defaultGateway); + _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", source, result); + return true; + } + + result = FormatIP6String(nc.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", source, result); + + if (isExternal) + { + // TODO: remove this after testing. + _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source); + } + + return true; + } + + return false; + } + + /// + /// Attempts to match the source against am external interface. + /// + /// IP source address to use. + /// The result, if a match is found. + /// True if a match is found. + private bool MatchesExternalInterface(IPObject source, out string result) + { + result = string.Empty; + // Get the first WAN interface address that isn't a loopback. + var extResult = new NetCollection(_interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => !IsInLocalNetwork(p)) + .OrderBy(p => p.Tag)); + + if (extResult.Count > 0) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in extResult) + { + if (!IsInLocalNetwork(intf) && intf.Contains(source)) + { + result = FormatIP6String(intf.Address); + _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", source, result); + return true; + } + } + + result = FormatIP6String(extResult.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", source, result); + return true; + } + + // Have to return something, so return an internal address + + // TODO: remove this after testing. + _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source); + return false; + } } } diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 8c19665cc1..f73c917a0b 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -12,10 +12,11 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Data.Events; using Jellyfin.Data.Events.Users; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common; using MediaBrowser.Common.Cryptography; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Events; diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 566ba0ad85..e2d7305af4 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -5,7 +5,7 @@ using System.Reflection; using Emby.Drawing; using Emby.Server.Implementations; using Jellyfin.Drawing.Skia; -using Jellyfin.Networking.Manager; + using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index ff82fe6cc6..e927a147aa 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,6 +1,6 @@ using System.Linq; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 87c82bf583..fa34a167b3 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -2,7 +2,7 @@ using System; using System.Linq; using System.Net; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 8549e39dbc..939f61656f 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -13,7 +13,7 @@ using CommandLine; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; using Jellyfin.Api.Controllers; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; @@ -272,7 +272,7 @@ namespace Jellyfin.Server return builder .UseKestrel((builderContext, options) => { - NetCollection addresses = NetworkManager.Instance.GetAllBindInterfaces(); + NetCollection addresses = appHost.NetManager.GetAllBindInterfaces(); bool flagged = false; foreach (IPObject netAdd in addresses) diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 70dcc2397c..0fda47788b 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -20,8 +20,9 @@ - + + diff --git a/Jellyfin.Networking/Manager/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs similarity index 79% rename from Jellyfin.Networking/Manager/INetworkManager.cs rename to MediaBrowser.Common/Net/INetworkManager.cs index ba571750b9..32c017aee6 100644 --- a/Jellyfin.Networking/Manager/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,11 +1,13 @@ +#nullable enable using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using MediaBrowser.Model.Configuration; +using Microsoft.AspNetCore.Http; using NetworkCollection; -namespace Jellyfin.Networking.Manager +namespace MediaBrowser.Common.Net { /// /// Interface for the NetworkManager class. @@ -18,9 +20,9 @@ namespace Jellyfin.Networking.Manager event EventHandler NetworkChanged; /// - /// Gets the Published server override list. + /// Gets the published server urls list. /// - Dictionary PublishedServerOverrides { get; } + Dictionary PublishedServerUrls { get; } /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -28,7 +30,7 @@ namespace Jellyfin.Networking.Manager public bool TrustAllIP6Interfaces { get; } /// - /// Gets returns the remote address filter. + /// Gets the remote address filter. /// NetCollection RemoteAddressFilter { get; } @@ -75,7 +77,37 @@ namespace Jellyfin.Networking.Manager /// Source of the request. /// Optional port returned, if it's part of an override. /// IP Address to use, or loopback address if all else fails. - string GetBindInterface(object? source, out int? port); + string GetBindInterface(IPObject source, out int? port); + + /// + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See above). + /// + /// Source of the request. + /// Optional port returned, if it's part of an override. + /// IP Address to use, or loopback address if all else fails. + string GetBindInterface(HttpRequest source, out int? port); + + /// + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See above). + /// + /// IP address of the request. + /// Optional port returned, if it's part of an override. + /// IP Address to use, or loopback address if all else fails. + string GetBindInterface(IPAddress source, out int? port); + + /// + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See above). + /// + /// Source of the request. + /// Optional port returned, if it's part of an override. + /// IP Address to use, or loopback address if all else fails. + string GetBindInterface(string source, out int? port); /// /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index f147e6a86c..7bc1006fc0 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -63,12 +63,28 @@ namespace MediaBrowser.Controller PublicSystemInfo GetPublicSystemInfo(IPAddress address); /// - /// Gets a local (LAN) URL that can be used to access the API. The hostname used is the first valid configured - /// HTTPS will be preferred when available. + /// Gets a URL specific for the request. /// - /// The source of the request. - /// The server URL. - string GetSmartApiUrl(object source); + /// The instance. + /// Optional port number. + /// An accessible URL. + string GetSmartApiUrl(HttpRequest request, int? port = null); + + /// + /// Gets a URL specific for the request. + /// + /// The remote of the connection. + /// Optional port number. + /// An accessible URL. + string GetSmartApiUrl(IPAddress remoteAddr, int? port = null); + + /// + /// Gets a URL specific for the request. + /// + /// The hostname used in the connection. + /// Optional port number. + /// An accessible URL. + string GetSmartApiUrl(string hostname, int? port = null); /// /// Gets a localhost URL that can be used to access the API using the loop-back IP address. diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index e28a2f48d4..932f6bbb40 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -7,7 +7,7 @@ using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 43fccdad42..84456f7dcd 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Net; using NetworkCollection; diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs index 2c7f0c4f9b..05dd8f325e 100644 --- a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs @@ -4,7 +4,7 @@ using AutoFixture; using AutoFixture.AutoMoq; using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Constants; -using Jellyfin.Networking.Manager; + using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; From 38b8110a3ec33267bb2b9e0b75ed0e2a704f41ca Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Mon, 14 Sep 2020 15:55:25 +0100 Subject: [PATCH 0025/1930] Removing blank lines. --- Emby.Dlna/Main/DlnaEntryPoint.cs | 1 - .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 1 - .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 1 - Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs | 1 - Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 1 - .../DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs | 1 - Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs | 1 - .../FirstTimeOrIgnoreParentalControlSetupHandler.cs | 1 - .../FirstTimeSetupOrDefaultHandler.cs | 1 - .../FirstTimeSetupOrElevatedHandler.cs | 1 - .../IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs | 1 - .../LocalAccessOrRequiresElevationHandler.cs | 1 - Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs | 1 - .../Auth/RequiresElevationPolicy/RequiresElevationHandler.cs | 1 - Jellyfin.Api/Controllers/UserController.cs | 1 - Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 1 - Jellyfin.Api/Helpers/MediaInfoHelper.cs | 1 - Jellyfin.Server.Implementations/Users/UserManager.cs | 2 -- Jellyfin.Server/CoreAppHost.cs | 1 - Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs | 1 - Jellyfin.Server/Middleware/LanFilteringMiddleware.cs | 1 - Jellyfin.Server/Program.cs | 1 - RSSDP/SsdpCommunicationsServer.cs | 1 - RSSDP/SsdpDevicePublisher.cs | 1 - .../Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs | 1 - 25 files changed, 26 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index a5da2fc5c8..35ec15623c 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -9,7 +9,6 @@ using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 27937d2f84..28e30fac8b 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -10,7 +10,6 @@ using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index efb6d162ac..a8d2a27f78 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -7,7 +7,6 @@ using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index 531a785a07..8107bc427b 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index bd76b93bf4..e245b57681 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,7 +1,6 @@ using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index dfa366796f..e988ca6cd1 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs index 3183d13186..cea5ac4734 100644 --- a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs +++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs index 1cee962e9f..96cf4db4b5 100644 --- a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs index 214198e001..9815e252ee 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrDefaultPolicy/FirstTimeSetupOrDefaultHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs index 9867ea4ca6..decbe0c035 100644 --- a/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeSetupOrElevatedPolicy/FirstTimeSetupOrElevatedHandler.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs index affd955515..3eb3ac6cdc 100644 --- a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs +++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index fab464b503..7bede142e0 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs index 801ee2f4c6..2999c6c8a8 100644 --- a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs @@ -1,5 +1,4 @@ using System.Threading.Tasks; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs index 7adf72c3d3..b235c4b63b 100644 --- a/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/RequiresElevationPolicy/RequiresElevationHandler.cs @@ -1,6 +1,5 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; - using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index c60497e304..11cf41b838 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -7,7 +7,6 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.UserDtos; using Jellyfin.Data.Enums; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index f81fb88fb1..1d330a3357 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -8,7 +8,6 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 9e4def774a..b4b6e2d35c 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index f73c917a0b..ffd0066ee3 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CA1307 using System; @@ -12,7 +11,6 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Data.Events; using Jellyfin.Data.Events.Users; - using MediaBrowser.Common; using MediaBrowser.Common.Cryptography; using MediaBrowser.Common.Extensions; diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index e2d7305af4..c2cb677eb5 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -5,7 +5,6 @@ using System.Reflection; using Emby.Drawing; using Emby.Server.Implementations; using Jellyfin.Drawing.Skia; - using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index e927a147aa..7f6b6bcce9 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,6 +1,5 @@ using System.Linq; using System.Threading.Tasks; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index fa34a167b3..7963d0d8c6 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -2,7 +2,6 @@ using System; using System.Linq; using System.Net; using System.Threading.Tasks; - using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 939f61656f..989cc439e6 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -13,7 +13,6 @@ using CommandLine; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; using Jellyfin.Api.Controllers; - using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 932f6bbb40..ea9e9a6fb5 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -7,7 +7,6 @@ using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Common.Net; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 84456f7dcd..c70294b38e 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; - using MediaBrowser.Common.Net; using NetworkCollection; diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs index 05dd8f325e..553e6a9cab 100644 --- a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs @@ -4,7 +4,6 @@ using AutoFixture; using AutoFixture.AutoMoq; using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Constants; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; From c1bfba90813b6780d43f82d4056496f5c776a186 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Mon, 14 Sep 2020 15:57:00 +0100 Subject: [PATCH 0026/1930] Nullable added --- Jellyfin.Server.Implementations/Users/UserManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index ffd0066ee3..bd853f92f7 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -1,3 +1,4 @@ +#nullable enable #pragma warning disable CA1307 using System; From 40464a6fddf3b522c57a72e16bd036fbe8ac4580 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 15 Sep 2020 13:47:01 +0100 Subject: [PATCH 0027/1930] Update LanFilteringMiddleware.cs --- .../Middleware/LanFilteringMiddleware.cs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 7963d0d8c6..a1d21f39e6 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -43,18 +43,6 @@ namespace Jellyfin.Server.Middleware } await _next(httpContext).ConfigureAwait(false); - } - - private static string NormalizeConfiguredLocalAddress(string address) - { - var add = address.AsSpan().Trim('/'); - int index = add.IndexOf('/'); - if (index != -1) - { - add = add.Slice(index + 1); - } - - return add.TrimStart('/').ToString(); - } + } } } From 96c3c4af4237c1fd1955fe5840904015ae592bef Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 15 Sep 2020 13:48:40 +0100 Subject: [PATCH 0028/1930] Update IpBasedAccessValidationMiddleware.cs --- .../Middleware/IpBasedAccessValidationMiddleware.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 7f6b6bcce9..0713d97d65 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Net; using System.Threading.Tasks; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -33,14 +33,14 @@ namespace Jellyfin.Server.Middleware /// The async task. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) { - if (httpContext.Connection.RemoteIpAddress == null) + if (httpContext.IsLocal()) { // Running locally. await _next(httpContext).ConfigureAwait(false); return; } - var remoteIp = httpContext.Connection.RemoteIpAddress; + var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; if (serverConfigurationManager.Configuration.EnableRemoteAccess) { From e6a3518220f159325cdf941fbfbbcd8ba871c28c Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Tue, 15 Sep 2020 18:05:42 +0100 Subject: [PATCH 0029/1930] Uploading latest --- Jellyfin.Networking/Manager/NetworkManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 760938c40f..83661d6b31 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -450,7 +450,7 @@ namespace Jellyfin.Networking.Manager return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } - return new NetCollection(_bindAddresses.Where(p => !p.IsLoopback())); + return new NetCollection(_bindAddresses); } } @@ -1127,7 +1127,7 @@ namespace Jellyfin.Networking.Manager private bool MatchesBindInterface(IPObject source, bool isExternal, out string result) { result = string.Empty; - var nc = new NetCollection(_bindAddresses.Exclude(_bindExclusions).Where(p => !p.IsLoopback())); + var nc = _bindAddresses.Exclude(_bindExclusions); int count = nc.Count; if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) From 0ec3633f9e3d2d3cf78dbcc0fe7d084ac3ccbf3d Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Tue, 15 Sep 2020 18:09:43 +0100 Subject: [PATCH 0030/1930] removing whitespace & upgraded library version --- Jellyfin.Networking/Jellyfin.Networking.csproj | 2 +- Jellyfin.Server/Middleware/LanFilteringMiddleware.cs | 2 +- MediaBrowser.Common/MediaBrowser.Common.csproj | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index b6834cb0ee..454dd9b7df 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -29,7 +29,7 @@ - + diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index a1d21f39e6..1ef460bd76 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -43,6 +43,6 @@ namespace Jellyfin.Server.Middleware } await _next(httpContext).ConfigureAwait(false); - } + } } } diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 0fda47788b..8de2ab8d8d 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -1,4 +1,4 @@ - + @@ -22,7 +22,7 @@ - + From 0496e1817923149f3d99d8e588efcaa2fbc5be1d Mon Sep 17 00:00:00 2001 From: Ryan Petris Date: Sat, 19 Sep 2020 05:13:24 +0000 Subject: [PATCH 0031/1930] Fix HD Home Run streaming. * Use LocalEndPoint instead of RemoteEndPoint when determining local address. * HdHomerunUdpStream.StartStreaming is meant to run until stream is closed, however HdHomerunUdpStream.Open needs to return as soon as stream is open to send stream url back to client. Therefore, StartStreaming should not be awaited on. * TcpClient(IPEndPoint) treats endpoint as the local endpoint; use TcpClient(string, int) instead as it treats endpoint as the remote endpoint. --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 6 +-- .../HdHomerun/HdHomerunUdpStream.cs | 51 ++++++++++--------- 2 files changed, 29 insertions(+), 28 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index d4a88e299f..895a13690e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -111,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public async Task CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) { - using (var client = new TcpClient(new IPEndPoint(remoteIp, HdHomeRunPort))) + using (var client = new TcpClient(remoteIp.ToString(), HdHomeRunPort)) using (var stream = client.GetStream()) { return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); @@ -142,7 +142,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort); - _tcpClient = new TcpClient(_remoteEndPoint); + _tcpClient = new TcpClient(_remoteEndPoint.Address.ToString(), _remoteEndPoint.Port); if (!_lockkey.HasValue) { @@ -221,7 +221,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return; } - using (var tcpClient = new TcpClient(_remoteEndPoint)) + using (var tcpClient = new TcpClient(_remoteEndPoint.Address.ToString(), _remoteEndPoint.Port)) using (var stream = tcpClient.GetStream()) { var commandList = commands.GetCommands(); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 6730751d50..5a95b28b5b 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun try { await tcpClient.ConnectAsync(remoteAddress, HdHomerunManager.HdHomeRunPort).ConfigureAwait(false); - localAddress = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address; + localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address; tcpClient.Close(); } catch (Exception ex) @@ -80,6 +80,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } + if (localAddress.IsIPv4MappedToIPv6) { + localAddress = localAddress.MapToIPv4(); + } + var udpClient = new UdpClient(localPort, AddressFamily.InterNetwork); var hdHomerunManager = new HdHomerunManager(); @@ -110,12 +114,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var taskCompletionSource = new TaskCompletionSource(); - await StartStreaming( + StartStreaming( udpClient, hdHomerunManager, remoteAddress, taskCompletionSource, - LiveStreamCancellationTokenSource.Token).ConfigureAwait(false); + LiveStreamCancellationTokenSource.Token); // OpenedMediaSource.Protocol = MediaProtocol.File; // OpenedMediaSource.Path = tempFile; @@ -131,33 +135,30 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun await taskCompletionSource.Task.ConfigureAwait(false); } - private Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource openTaskCompletionSource, CancellationToken cancellationToken) + private async void StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource openTaskCompletionSource, CancellationToken cancellationToken) { - return Task.Run(async () => + using (udpClient) + using (hdHomerunManager) { - using (udpClient) - using (hdHomerunManager) + try { - try - { - await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException ex) - { - Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); - openTaskCompletionSource.TrySetException(ex); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error opening live stream:"); - openTaskCompletionSource.TrySetException(ex); - } - - EnableStreamSharing = false; + await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException ex) + { + Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress); + openTaskCompletionSource.TrySetException(ex); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error opening live stream:"); + openTaskCompletionSource.TrySetException(ex); } - await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); - }); + EnableStreamSharing = false; + } + + await DeleteTempFiles(new List { TempFilePath }).ConfigureAwait(false); } private async Task CopyTo(UdpClient udpClient, string file, TaskCompletionSource openTaskCompletionSource, CancellationToken cancellationToken) From 361f51ac944184cbde3768818bc68e5cfee8e857 Mon Sep 17 00:00:00 2001 From: Ryan Petris Date: Sat, 19 Sep 2020 22:22:48 +0000 Subject: [PATCH 0032/1930] Use TcpClient.Connect(). --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 55 ++++++++++--------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 895a13690e..cdc8c6870a 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -111,11 +111,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public async Task CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) { - using (var client = new TcpClient(remoteIp.ToString(), HdHomeRunPort)) - using (var stream = client.GetStream()) - { - return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); - } + using var client = new TcpClient(); + client.Connect(remoteIp, HdHomeRunPort); + + using var stream = client.GetStream(); + return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); } private static async Task CheckTunerAvailability(NetworkStream stream, int tuner, CancellationToken cancellationToken) @@ -142,7 +142,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort); - _tcpClient = new TcpClient(_remoteEndPoint.Address.ToString(), _remoteEndPoint.Port); + _tcpClient = new TcpClient(); + _tcpClient.Connect(_remoteEndPoint); if (!_lockkey.HasValue) { @@ -221,30 +222,30 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return; } - using (var tcpClient = new TcpClient(_remoteEndPoint.Address.ToString(), _remoteEndPoint.Port)) - using (var stream = tcpClient.GetStream()) - { - var commandList = commands.GetCommands(); - byte[] buffer = ArrayPool.Shared.Rent(8192); - try - { - foreach (var command in commandList) - { - var channelMsg = CreateSetMessage(_activeTuner, command.Item1, command.Item2, _lockkey); - await stream.WriteAsync(channelMsg, 0, channelMsg.Length, cancellationToken).ConfigureAwait(false); - int receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + using var tcpClient = new TcpClient(); + tcpClient.Connect(_remoteEndPoint); - // parse response to make sure it worked - if (!ParseReturnMessage(buffer, receivedBytes, out _)) - { - return; - } + using var stream = tcpClient.GetStream(); + var commandList = commands.GetCommands(); + byte[] buffer = ArrayPool.Shared.Rent(8192); + try + { + foreach (var command in commandList) + { + var channelMsg = CreateSetMessage(_activeTuner, command.Item1, command.Item2, _lockkey); + await stream.WriteAsync(channelMsg, 0, channelMsg.Length, cancellationToken).ConfigureAwait(false); + int receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + + // parse response to make sure it worked + if (!ParseReturnMessage(buffer, receivedBytes, out _)) + { + return; } } - finally - { - ArrayPool.Shared.Return(buffer); - } + } + finally + { + ArrayPool.Shared.Return(buffer); } } From 37cb4dbca6dd42d004fa389dd2b6fbc07d56b7d4 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Thu, 24 Sep 2020 15:34:49 +0100 Subject: [PATCH 0033/1930] Removed package reference. --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 0793526271..4d7919d8b2 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -22,7 +22,6 @@ - From 28634d3b366c814192a14970e5f790d6cae149bf Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 24 Sep 2020 15:43:06 +0100 Subject: [PATCH 0034/1930] Update DlnaEntryPoint.cs --- Emby.Dlna/Main/DlnaEntryPoint.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 35ec15623c..6f626711a2 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -259,15 +259,16 @@ namespace Emby.Dlna.Main private void RegisterServerEndpoints() { - var bindAddresses = _networkManager.GetInternalBindAddresses() - .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)); - var udn = CreateUuid(_appHost.SystemId); - if (!bindAddresses.Any()) + var ba = new NetCollection( + _networkManager.GetInternalBindAddresses() + .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))); + + if (ba.Count == 0) { // No interfaces returned, so use loopback. - bindAddresses = _networkManager.GetLoopbacks(); + ba = _networkManager.GetLoopbacks(); } foreach (var addr in bindAddresses) From d617c0b8b0bd5cac78e9ba9ce968e890a8d5d43a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 24 Sep 2020 15:47:35 +0100 Subject: [PATCH 0035/1930] Update SystemController.cs --- Jellyfin.Api/Controllers/SystemController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index b87e275d0f..7784e8a119 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -8,7 +8,6 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; - using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; From 8c85cfd01d183b62badb0e8853f29c6a178c9e26 Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Thu, 24 Sep 2020 16:02:29 +0100 Subject: [PATCH 0036/1930] Fixed build --- Emby.Dlna/Main/DlnaEntryPoint.cs | 6 +++--- .../Emby.Server.Implementations.csproj | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 6f626711a2..33a953563b 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -261,14 +261,14 @@ namespace Emby.Dlna.Main { var udn = CreateUuid(_appHost.SystemId); - var ba = new NetCollection( + var bindAddresses = new NetCollection( _networkManager.GetInternalBindAddresses() .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))); - if (ba.Count == 0) + if (bindAddresses.Count == 0) { // No interfaces returned, so use loopback. - ba = _networkManager.GetLoopbacks(); + bindAddresses = _networkManager.GetLoopbacks(); } foreach (var addr in bindAddresses) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 9a860f4d78..f8fef8bcbf 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -22,7 +22,6 @@ - From f97bea53e59b24117e8111467afae37a12d2d80b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 24 Sep 2020 16:11:24 +0100 Subject: [PATCH 0037/1930] Update Emby.Server.Implementations.csproj --- .../Emby.Server.Implementations.csproj | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index f8fef8bcbf..444fee33a6 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -13,7 +13,7 @@ - + @@ -31,6 +31,10 @@ + + + + From 6ca313abc186d45aef8b6d949432a4c9ef9cc1d2 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 25 Sep 2020 23:59:17 +0200 Subject: [PATCH 0038/1930] Add ProgressiveFileStream --- .../Helpers/FileStreamResponseHelpers.cs | 5 +- Jellyfin.Api/Helpers/ProgressiveFileStream.cs | 164 ++++++++++++++++++ 2 files changed, 166 insertions(+), 3 deletions(-) create mode 100644 Jellyfin.Api/Helpers/ProgressiveFileStream.cs diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index 6b516977e8..366301d3ee 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -123,9 +123,8 @@ namespace Jellyfin.Api.Helpers state.Dispose(); } - await new ProgressiveFileCopier(outputPath, job, transcodingJobHelper, CancellationToken.None) - .WriteToAsync(httpContext.Response.Body, CancellationToken.None).ConfigureAwait(false); - return new FileStreamResult(httpContext.Response.Body, contentType); + var stream = new ProgressiveFileStream(outputPath, job, transcodingJobHelper); + return new FileStreamResult(stream, contentType); } finally { diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs new file mode 100644 index 0000000000..e09f3dca94 --- /dev/null +++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs @@ -0,0 +1,164 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Api.Models.PlaybackDtos; +using MediaBrowser.Model.IO; + +namespace Jellyfin.Api.Helpers +{ + /// + /// A progressive file stream for transferring transcoded files as they are written to. + /// + public class ProgressiveFileStream : Stream + { + private readonly FileStream _fileStream; + private readonly TranscodingJobDto? _job; + private readonly TranscodingJobHelper _transcodingJobHelper; + private readonly bool _allowAsyncFileRead; + private int _bytesWritten; + private bool _disposed; + + /// + /// Initializes a new instance of the class. + /// + /// The path to the transcoded file. + /// The transcoding job information. + /// The transcoding job helper. + public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper) + { + _job = job; + _transcodingJobHelper = transcodingJobHelper; + _bytesWritten = 0; + + var fileOptions = FileOptions.SequentialScan; + _allowAsyncFileRead = false; + + // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039 + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + fileOptions |= FileOptions.Asynchronous; + _allowAsyncFileRead = true; + } + + _fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions); + } + + /// + public override bool CanRead => _fileStream.CanRead; + + /// + public override bool CanSeek => false; + + /// + public override bool CanWrite => false; + + /// + public override long Length => throw new NotSupportedException(); + + /// + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + /// + public override void Flush() + { + _fileStream.Flush(); + } + + /// + public override int Read(byte[] buffer, int offset, int count) + { + return _fileStream.Read(buffer, offset, count); + } + + /// + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + var eofCount = 0; + const int EmptyReadLimit = 20; + + int totalBytesRead = 0; + int remainingBytesToRead = count; + + while (eofCount < EmptyReadLimit && remainingBytesToRead > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + int bytesRead; + if (_allowAsyncFileRead) + { + bytesRead = await _fileStream.ReadAsync(buffer, offset, remainingBytesToRead, cancellationToken).ConfigureAwait(false); + } + else + { + bytesRead = _fileStream.Read(buffer, offset, remainingBytesToRead); + } + + remainingBytesToRead -= bytesRead; + if (bytesRead > 0) + { + _bytesWritten += bytesRead; + totalBytesRead += bytesRead; + + if (_job != null) + { + _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten); + } + } + + if (bytesRead == 0) + { + if (_job == null || _job.HasExited) + { + eofCount++; + } + + await Task.Delay(100, cancellationToken).ConfigureAwait(false); + } + else + { + eofCount = 0; + } + } + + return totalBytesRead; + } + + /// + public override long Seek(long offset, SeekOrigin origin) + => throw new NotSupportedException(); + + /// + public override void SetLength(long value) + => throw new NotSupportedException(); + + /// + public override void Write(byte[] buffer, int offset, int count) + => throw new NotSupportedException(); + + /// + protected override void Dispose(bool disposing) + { + if (_disposed) + { + return; + } + + if (disposing) + { + _fileStream.Dispose(); + + if (_job != null) + { + _transcodingJobHelper.OnTranscodeEndRequest(_job); + } + } + + _disposed = true; + } + } +} From 146cad61505147ee1e118135a396eb6ed3e0fc78 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 26 Sep 2020 19:03:23 +0200 Subject: [PATCH 0039/1930] Remove EOF counter --- Jellyfin.Api/Helpers/ProgressiveFileStream.cs | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs index e09f3dca94..b3566b6f80 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs @@ -79,13 +79,10 @@ namespace Jellyfin.Api.Helpers /// public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - var eofCount = 0; - const int EmptyReadLimit = 20; - int totalBytesRead = 0; int remainingBytesToRead = count; - while (eofCount < EmptyReadLimit && remainingBytesToRead > 0) + while (remainingBytesToRead > 0) { cancellationToken.ThrowIfCancellationRequested(); int bytesRead; @@ -109,20 +106,15 @@ namespace Jellyfin.Api.Helpers _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten); } } - - if (bytesRead == 0) + else { if (_job == null || _job.HasExited) { - eofCount++; + break; } await Task.Delay(100, cancellationToken).ConfigureAwait(false); } - else - { - eofCount = 0; - } } return totalBytesRead; @@ -148,17 +140,23 @@ namespace Jellyfin.Api.Helpers return; } - if (disposing) + try { - _fileStream.Dispose(); - - if (_job != null) + if (disposing) { - _transcodingJobHelper.OnTranscodeEndRequest(_job); + _fileStream.Dispose(); + + if (_job != null) + { + _transcodingJobHelper.OnTranscodeEndRequest(_job); + } } } - - _disposed = true; + finally + { + _disposed = true; + base.Dispose(disposing); + } } } } From bdfe7554e951e330b5afb19bda613bf821316a1e Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 28 Sep 2020 07:49:08 +0100 Subject: [PATCH 0040/1930] Update Emby.Dlna/Configuration/DlnaOptions.cs Co-authored-by: Cody Robibero --- Emby.Dlna/Configuration/DlnaOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index 481ff059b5..8b8f100d0a 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -80,7 +80,7 @@ namespace Emby.Dlna.Configuration public bool AutoCreatePlayToProfiles { get; set; } /// - /// Gets or sets a value indicating whether OBSOLETE. + /// Gets or sets a value indicating whether to blast alive messages. /// public bool BlastAliveMessages { get; set; } = true; From ef737a4e8e113c71446bb6a67265f9a7d91cc858 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 28 Sep 2020 07:49:36 +0100 Subject: [PATCH 0041/1930] Update Emby.Dlna/Configuration/DlnaOptions.cs Co-authored-by: Cody Robibero --- Emby.Dlna/Configuration/DlnaOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index 8b8f100d0a..e63a858605 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -85,7 +85,7 @@ namespace Emby.Dlna.Configuration public bool BlastAliveMessages { get; set; } = true; /// - /// gets or sets a value indicating whether OBSOLETE. + /// gets or sets a value indicating whether to send only matched host. /// public bool SendOnlyMatchedHost { get; set; } = true; } From bbe2400b59563991f1689c68ef36d623afd39f0a Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Wed, 30 Sep 2020 17:51:17 +0100 Subject: [PATCH 0042/1930] Updating to NetCollection 1.03 --- .../Jellyfin.Networking.csproj | 3 +- Jellyfin.Networking/Manager/NetworkManager.cs | 150 ++++++++++++------ MediaBrowser.Common/Net/INetworkManager.cs | 17 +- .../Configuration/ServerConfiguration.cs | 23 ++- 4 files changed, 128 insertions(+), 65 deletions(-) diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index 454dd9b7df..06d387dc87 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -28,8 +28,7 @@ - - + diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 83661d6b31..6f2970ef89 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -12,6 +12,7 @@ using MediaBrowser.Model.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using NetworkCollection; +using NetworkCollection.Udp; namespace Jellyfin.Networking.Manager { @@ -125,29 +126,19 @@ namespace Jellyfin.Networking.Manager public event EventHandler? NetworkChanged; /// - /// Gets the unique network location signature, which is updated on every network change. + /// Gets or sets a value indicating whether testing is taking place. /// - public static string NetworkLocationSignature { get; internal set; } = Guid.NewGuid().ToString(); + public static string MockNetworkSettings { get; set; } = string.Empty; /// - /// Gets a value indicating whether IP6 is enabled. + /// Gets or sets a value indicating whether IP6 is enabled. /// - public static bool IsIP6Enabled { get; internal set; } + public bool IsIP6Enabled { get; set; } /// - /// Gets a value indicating whether IP4 is enabled. + /// Gets or sets a value indicating whether IP4 is enabled. /// - public static bool IsIP4Enabled { get; internal set; } = true; - - /// - /// Gets a value indicating whether is multi-socket binding available. - /// - public static bool EnableMultiSocketBinding { get; internal set; } = true; - - /// - /// Gets the number of times the network address has changed. - /// - public static int NetworkChangeCount { get; internal set; } = 1; + public bool IsIP4Enabled { get; set; } /// public NetCollection RemoteAddressFilter { get; private set; } @@ -271,7 +262,7 @@ namespace Jellyfin.Networking.Manager } /// - public NetCollection GetAllBindInterfaces() + public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) { lock (_intLock) { @@ -285,6 +276,11 @@ namespace Jellyfin.Networking.Manager return _interfaceAddresses.Exclude(_bindExclusions); } + if (individualInterfaces) + { + return new NetCollection(_interfaceAddresses); + } + // No bind address and no exclusions, so listen on all interfaces. NetCollection result = new NetCollection(); @@ -311,12 +307,6 @@ namespace Jellyfin.Networking.Manager { if (!string.IsNullOrEmpty(source)) { - if (string.Equals(source, "chromecast", StringComparison.OrdinalIgnoreCase)) - { - // Just assign a variable so has source = true; - return GetBindInterface(IPNetAddress.IP4Loopback, out port); - } - if (IPHost.TryParse(source, out IPHost host)) { return GetBindInterface(host, out port); @@ -572,16 +562,18 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string token, out IPNetAddress result) + public bool TryParseInterface(string token, out NetCollection? result) { + result = null; if (string.IsNullOrEmpty(token)) { - result = IPNetAddress.None; return false; } if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) { + result = new NetCollection(); + _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); // Replace interface tags with the interface IP's. @@ -591,13 +583,14 @@ namespace Jellyfin.Networking.Manager ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { - result = iface; - return true; + result.Add(iface); } } + + return true; } - return IPNetAddress.TryParse(token, out result); + return false; } /// @@ -614,9 +607,27 @@ namespace Jellyfin.Networking.Manager IsIP4Enabled = Socket.OSSupportsIPv6 && config.EnableIPV4; IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; - EnableMultiSocketBinding = config.EnableMultiSocketBinding; + UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding; + + if (string.IsNullOrEmpty(MockNetworkSettings)) + { + InitialiseInterfaces(); + } + else // Used in testing only. + { + // Format is ,,: . Set index to -ve to simulate a gateway. + var interfaceList = MockNetworkSettings.Split(':'); + foreach (var details in interfaceList) + { + var parts = details.Split(','); + var address = IPNetAddress.Parse(parts[0]); + var index = int.Parse(parts[1], CultureInfo.InvariantCulture); + address.Tag = index; + _interfaceAddresses.Add(address); + _interfaceNames.Add(parts[2], Math.Abs(index)); + } + } - InitialiseInterfaces(); InitialiseLAN(config); InitialiseBind(config); InitialiseRemote(config); @@ -671,6 +682,40 @@ namespace Jellyfin.Networking.Manager return str; } + /// + /// Checks the string to see if it matches any interface names. + /// + /// String to check. + /// Interface index number. + /// True if an interface name matches the token. + private bool IsInterface(string token, out int index) + { + index = -1; + + // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. + // Null check required here for automated testing. + if (_interfaceNames != null && token.Length > 1) + { + bool partial = token[^1] == '*'; + if (partial) + { + token = token[0..^1]; + } + + foreach ((string interfc, int interfcIndex) in _interfaceNames) + { + if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || + (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) + { + index = interfcIndex; + return true; + } + } + } + + return false; + } + /// /// Parses strings into the collection, replacing any interface references. /// @@ -680,7 +725,7 @@ namespace Jellyfin.Networking.Manager { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. - if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) + if (IsInterface(token, out int index)) { _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); @@ -774,14 +819,6 @@ namespace Jellyfin.Networking.Manager /// private void OnNetworkChanged() { - // As per UPnP Device Architecture v1.0 Annex A - IPv6 Support. - NetworkLocationSignature = Guid.NewGuid().ToString(); - NetworkChangeCount++; - if (NetworkChangeCount > 99) - { - NetworkChangeCount = 1; - } - if (!_eventfire) { _logger.LogDebug("Network Address Change Event."); @@ -800,20 +837,14 @@ namespace Jellyfin.Networking.Manager /// private void InitialiseOverrides(ServerConfiguration config) { - string[] overrides = config.PublishedServerUriBySubnet; - if (overrides == null) - { - lock (_intLock) - { - _publishedServerUrls.Clear(); - } - - return; - } - lock (_intLock) { _publishedServerUrls.Clear(); + string[] overrides = config.PublishedServerUriBySubnet; + if (overrides == null) + { + return; + } foreach (var entry in overrides) { @@ -833,9 +864,16 @@ namespace Jellyfin.Networking.Manager { _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; } - else if (TryParseInterface(parts[0], out IPNetAddress address)) + else if (TryParseInterface(parts[0], out NetCollection? addresses) && addresses != null) { - _publishedServerUrls[address] = replacement; + foreach (IPNetAddress na in addresses) + { + _publishedServerUrls[na] = replacement; + } + } + else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result)) + { + _publishedServerUrls[result] = replacement; } else { @@ -859,6 +897,14 @@ namespace Jellyfin.Networking.Manager // TODO: end fix. + // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. + if (config.IgnoreVirtualInterfaces) + { + var newList = ba.ToList(); + newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList()); + ba = newList.ToArray(); + } + // Read and parse bind addresses and exclusions, removing ones that don't exist. _bindAddresses = CreateIPCollection(ba).Union(_interfaceAddresses); _bindExclusions = CreateIPCollection(ba, true).Union(_interfaceAddresses); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 32c017aee6..8789cd9d81 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -34,13 +34,24 @@ namespace MediaBrowser.Common.Net /// NetCollection RemoteAddressFilter { get; } + /// + /// Gets or sets a value indicating whether iP6 is enabled. + /// + public bool IsIP6Enabled { get; set; } + + /// + /// Gets or sets a value indicating whether iP4 is enabled. + /// + public bool IsIP4Enabled { get; set; } + /// /// Calculates the list of interfaces to use for Kestrel. /// /// A NetCollection object containing all the interfaces to bind. /// If all the interfaces are specified, and none are excluded, it returns zero items /// to represent any address. - NetCollection GetAllBindInterfaces(); + /// When false, return or for all interfaces. + NetCollection GetAllBindInterfaces(bool individualInterfaces = false); /// /// Returns a collection containing the loopback interfaces. @@ -166,9 +177,9 @@ namespace MediaBrowser.Common.Net /// eg. "eth1", or "TP-LINK Wireless USB Adapter". /// /// Token to parse. - /// Resultant object if successful. + /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string token, out IPNetAddress result); + bool TryParseInterface(string token, out NetCollection? result); /// /// Parses an array of strings into a NetCollection. diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 073a629829..dbfab1fad4 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -1,4 +1,4 @@ -#nullable disable +#nullable enable #pragma warning disable CS1591 #pragma warning disable CA1819 @@ -111,7 +111,7 @@ namespace MediaBrowser.Model.Configuration /// /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. - /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. /// public bool EnableSSDPTracing { get; set; } = false; @@ -131,13 +131,23 @@ namespace MediaBrowser.Model.Configuration /// public int UDPSendDelay { get; set; } = 100; + /// + /// Gets or sets a value indicating whether address names that match should be Ignore for the purposes of binding. + /// + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. . + /// + public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + /// /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. /// public int GatewayMonitorPeriod { get; set; } = 60; /// - /// Gets a value indicating whether is multi-socket binding available. + /// Gets a value indicating whether multi-socket binding is available. /// public bool EnableMultiSocketBinding { get; } = true; @@ -158,7 +168,7 @@ namespace MediaBrowser.Model.Configuration public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); /// - /// Gets or sets a value indicating whether gets or sets Autodiscovery tracing. + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. /// public bool AutoDiscoveryTracing { get; set; } = false; @@ -216,9 +226,7 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets a value indicating whether quick connect is available for use on this server. /// public bool QuickConnectAvailable { get; set; } = false; - - public bool AutoRunWebApp { get; set; } = true; - + /// /// Gets or sets a value indicating whether access outside of the LAN is permitted. /// @@ -419,6 +427,5 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets the known proxies. /// public string[] KnownProxies { get; set; } = Array.Empty(); - } } From 3b64171cde969a7cfca60d28c7782774a173758b Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Wed, 30 Sep 2020 18:02:36 +0100 Subject: [PATCH 0043/1930] Minor change to get it to compile. --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- Jellyfin.Api/Controllers/StartupController.cs | 6 +++--- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index a95cfea07c..66e48ddc65 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1319,7 +1319,7 @@ namespace Emby.Server.Implementations /// public string GetLoopbackHttpApiUrl() { - if (NetworkManager.IsIP6Enabled) + if (NetManager.IsIP6Enabled) { return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort); } diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs index 9c259cc198..e59c6e1ddf 100644 --- a/Jellyfin.Api/Controllers/StartupController.cs +++ b/Jellyfin.Api/Controllers/StartupController.cs @@ -72,9 +72,9 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult UpdateInitialConfiguration([FromBody, Required] StartupConfigurationDto startupConfiguration) { - _config.Configuration.UICulture = startupConfiguration.UICulture; - _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode; - _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage; + _config.Configuration.UICulture = startupConfiguration.UICulture ?? string.Empty; + _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode ?? string.Empty; + _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage ?? string.Empty; _config.SaveConfiguration(); return NoContent(); } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index dbfab1fad4..86b7c4c3d6 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 #pragma warning disable CA1819 From 53d8023defe19ef943f72964d93dbed40b6f1180 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 30 Sep 2020 17:37:30 -0600 Subject: [PATCH 0044/1930] Update all on-disk plugins --- .../ApplicationHost.cs | 94 ++++++--------- .../Updates/InstallationManager.cs | 10 +- MediaBrowser.Common/Plugins/LocalPlugin.cs | 113 ++++++++++++++++++ .../IServerApplicationHost.cs | 10 +- 4 files changed, 162 insertions(+), 65 deletions(-) create mode 100644 MediaBrowser.Common/Plugins/LocalPlugin.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 7a46fdf2e7..984ab41f0a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -30,7 +29,6 @@ using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Devices; using Emby.Server.Implementations.Dto; -using Emby.Server.Implementations.HttpServer; using Emby.Server.Implementations.HttpServer.Security; using Emby.Server.Implementations.IO; using Emby.Server.Implementations.Library; @@ -258,8 +256,8 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - + _jsonSerializer = new JsonSerializer(); + ServiceCollection = serviceCollection; _networkManager = networkManager; @@ -1026,80 +1024,54 @@ namespace Emby.Server.Implementations protected abstract void RestartInternal(); - /// - /// Comparison function used in . - /// - /// Item to compare. - /// Item to compare with. - /// Boolean result of the operation. - private static int VersionCompare( - (Version PluginVersion, string Name, string Path) a, - (Version PluginVersion, string Name, string Path) b) + /// + public IEnumerable GetLocalPlugins(string path, bool cleanup = true) { - int compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture); - - if (compare == 0) - { - return a.PluginVersion.CompareTo(b.PluginVersion); - } - - return compare; - } - - /// - /// Returns a list of plugins to install. - /// - /// Path to check. - /// True if an attempt should be made to delete old plugs. - /// Enumerable list of dlls to load. - private IEnumerable GetPlugins(string path, bool cleanup = true) - { - var dllList = new List(); - var versions = new List<(Version PluginVersion, string Name, string Path)>(); + var minimumVersion = new Version(0, 0, 0, 1); + var versions = new List(); var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); - string metafile; foreach (var dir in directories) { try { - metafile = Path.Combine(dir, "meta.json"); + var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { var manifest = _jsonSerializer.DeserializeFromFile(metafile); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) { - targetAbi = new Version(0, 0, 0, 1); + targetAbi = minimumVersion; } if (!Version.TryParse(manifest.Version, out var version)) { - version = new Version(0, 0, 0, 1); + version = minimumVersion; } if (ApplicationVersion >= targetAbi) { // Only load Plugins if the plugin is built for this version or below. - versions.Add((version, manifest.Name, dir)); + versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir)); } } else { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); - if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) + if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version parsedVersion)) { // Versioned folder. - versions.Add((ver, metafile, dir)); + versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir)); } else { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. - versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + // Un-versioned folder - Add it under the path name and version 0.0.0.1. + versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir)); + } } } catch @@ -1109,14 +1081,14 @@ namespace Emby.Server.Implementations } string lastName = string.Empty; - versions.Sort(VersionCompare); + versions.Sort(LocalPlugin.Compare); // Traverse backwards through the list. // The first item will be the latest version. for (int x = versions.Count - 1; x >= 0; x--) { if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase)) { - dllList.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories)); + versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories)); lastName = versions[x].Name; continue; } @@ -1124,6 +1096,7 @@ namespace Emby.Server.Implementations if (!string.IsNullOrEmpty(lastName) && cleanup) { // Attempt a cleanup of old folders. + versions.RemoveAt(x); try { Logger.LogDebug("Deleting {Path}", versions[x].Path); @@ -1136,7 +1109,7 @@ namespace Emby.Server.Implementations } } - return dllList; + return versions; } /// @@ -1147,21 +1120,24 @@ namespace Emby.Server.Implementations { if (Directory.Exists(ApplicationPaths.PluginsPath)) { - foreach (var file in GetPlugins(ApplicationPaths.PluginsPath)) + foreach (var plugin in GetLocalPlugins(ApplicationPaths.PluginsPath)) { - Assembly plugAss; - try + foreach (var file in plugin.DllFiles) { - plugAss = Assembly.LoadFrom(file); - } - catch (FileLoadException ex) - { - Logger.LogError(ex, "Failed to load assembly {Path}", file); - continue; - } + Assembly plugAss; + try + { + plugAss = Assembly.LoadFrom(file); + } + catch (FileLoadException ex) + { + Logger.LogError(ex, "Failed to load assembly {Path}", file); + continue; + } - Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file); - yield return plugAss; + Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file); + yield return plugAss; + } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 003cf3c740..365d890655 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -15,14 +15,13 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; -using MediaBrowser.Common.System; +using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.IO; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; using Microsoft.Extensions.Logging; -using MediaBrowser.Model.System; namespace Emby.Server.Implementations.Updates { @@ -45,7 +44,7 @@ namespace Emby.Server.Implementations.Updates /// Gets the application host. /// /// The application host. - private readonly IApplicationHost _applicationHost; + private readonly IServerApplicationHost _applicationHost; private readonly IZipClient _zipClient; @@ -63,7 +62,7 @@ namespace Emby.Server.Implementations.Updates public InstallationManager( ILogger logger, - IApplicationHost appHost, + IServerApplicationHost appHost, IApplicationPaths appPaths, IHttpClientFactory httpClientFactory, IJsonSerializer jsonSerializer, @@ -237,7 +236,8 @@ namespace Emby.Server.Implementations.Updates private IEnumerable GetAvailablePluginUpdates(IReadOnlyList pluginCatalog) { - foreach (var plugin in _applicationHost.Plugins) + var plugins = _applicationHost.GetLocalPlugins(_appPaths.PluginsPath); + foreach (var plugin in plugins) { var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version); var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version); diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs new file mode 100644 index 0000000000..e26631615a --- /dev/null +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace MediaBrowser.Common.Plugins +{ + /// + /// Local plugin struct. + /// + public readonly struct LocalPlugin : IEquatable + { + /// + /// Initializes a new instance of the struct. + /// + /// The plugin id. + /// The plugin name. + /// The plugin version. + /// The plugin path. + public LocalPlugin(Guid id, string name, Version version, string path) + { + Id = id; + Name = name; + Version = version; + Path = path; + DllFiles = new List(); + } + + /// + /// Gets the plugin id. + /// + public Guid Id { get; } + + /// + /// Gets the plugin name. + /// + public string Name { get; } + + /// + /// Gets the plugin version. + /// + public Version Version { get; } + + /// + /// Gets the plugin path. + /// + public string Path { get; } + + /// + /// Gets the list of dll files for this plugin. + /// + public List DllFiles { get; } + + /// + /// == operator. + /// + /// Left item. + /// Right item. + /// Comparison result. + public static bool operator ==(LocalPlugin left, LocalPlugin right) + { + return left.Equals(right); + } + + /// + /// != operator. + /// + /// Left item. + /// Right item. + /// Comparison result. + public static bool operator !=(LocalPlugin left, LocalPlugin right) + { + return !(left == right); + } + + /// + /// Compare two . + /// + /// The first item. + /// The second item. + /// Comparison result. + public static int Compare(LocalPlugin a, LocalPlugin b) + { + var compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture); + + // Id is not equal but name is. + if (a.Id != b.Id && compare == 0) + { + compare = a.Id.CompareTo(b.Id); + } + + return compare == 0 ? a.Version.CompareTo(b.Version) : compare; + } + + /// + public override bool Equals(object obj) + { + return obj is LocalPlugin other && this.Equals(other); + } + + /// + public override int GetHashCode() + { + return Name.GetHashCode(StringComparison.OrdinalIgnoreCase); + } + + /// + public bool Equals(LocalPlugin other) + { + return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) + && Id.Equals(other.Id); + } + } +} diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index cfad17fb72..8a55437c5d 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -6,8 +6,8 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; +using MediaBrowser.Common.Plugins; using MediaBrowser.Model.System; -using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller { @@ -119,5 +119,13 @@ namespace MediaBrowser.Controller string ExpandVirtualPath(string path); string ReverseVirtualPath(string path); + + /// + /// Gets the list of local plugins. + /// + /// Plugin base directory. + /// Cleanup old plugins. + /// Enumerable of local plugins. + IEnumerable GetLocalPlugins(string path, bool cleanup = true); } } From c2276b17cb196de44f1bbb42b91b000cde8fdc7f Mon Sep 17 00:00:00 2001 From: Gary Wilber Date: Wed, 30 Sep 2020 19:33:34 -0700 Subject: [PATCH 0045/1930] Increase library scan and metadata refresh speed --- .../ApplicationHost.cs | 1 + MediaBrowser.Controller/Entities/Folder.cs | 220 +++++++++++------- .../Library/TaskMethods.cs | 133 +++++++++++ .../Configuration/ServerConfiguration.cs | 12 + 4 files changed, 283 insertions(+), 83 deletions(-) create mode 100644 MediaBrowser.Controller/Library/TaskMethods.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 7a46fdf2e7..6d7239f724 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -758,6 +758,7 @@ namespace Emby.Server.Implementations BaseItem.FileSystem = _fileSystemManager; BaseItem.UserDataManager = Resolve(); BaseItem.ChannelManager = Resolve(); + TaskMethods.ConfigurationManager = ServerConfigurationManager; Video.LiveTvManager = Resolve(); Folder.UserViewManager = Resolve(); UserView.TVSeriesManager = Resolve(); diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 901ea875bc..666455cff4 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -35,6 +35,46 @@ namespace MediaBrowser.Controller.Entities /// public class Folder : BaseItem { + /// + /// Contains constants used when reporting scan progress. + /// + private static class ProgressHelpers + { + /// + /// Reported after the folders immediate children are retrieved. + /// + public const int RetrievedChildren = 5; + + /// + /// Reported after add, updating, or deleting child items from the LibraryManager. + /// + public const int UpdatedChildItems = 10; + + /// + /// Reported once subfolders are scanned. + /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders]. + /// + public const int ScannedSubfolders = 50; + + /// + /// Reported once metadata is refreshed. + /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed]. + /// + public const int RefreshedMetadata = 100; + + /// + /// Gets the current progress given the previous step, next step, and progress in between. + /// + /// The previous progress step. + /// The next progress step. + /// The current progress step. + /// The progress. + public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress) + { + return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100)); + } + } + public static IUserViewManager UserViewManager { get; set; } /// @@ -327,11 +367,11 @@ namespace MediaBrowser.Controller.Entities return; } - progress.Report(5); + progress.Report(ProgressHelpers.RetrievedChildren); if (recursive) { - ProviderManager.OnRefreshProgress(this, 5); + ProviderManager.OnRefreshProgress(this, ProgressHelpers.RetrievedChildren); } // Build a dictionary of the current children we have now by Id so we can compare quickly and easily @@ -392,11 +432,11 @@ namespace MediaBrowser.Controller.Entities validChildrenNeedGeneration = true; } - progress.Report(10); + progress.Report(ProgressHelpers.UpdatedChildItems); if (recursive) { - ProviderManager.OnRefreshProgress(this, 10); + ProviderManager.OnRefreshProgress(this, ProgressHelpers.UpdatedChildItems); } cancellationToken.ThrowIfCancellationRequested(); @@ -406,11 +446,13 @@ namespace MediaBrowser.Controller.Entities var innerProgress = new ActionableProgress(); var folder = this; - innerProgress.RegisterAction(p => + innerProgress.RegisterAction(innerPercent => { - double newPct = 0.80 * p + 10; - progress.Report(newPct); - ProviderManager.OnRefreshProgress(folder, newPct); + var percent = ProgressHelpers.GetProgress(ProgressHelpers.UpdatedChildItems, ProgressHelpers.ScannedSubfolders, innerPercent); + + progress.Report(percent); + + ProviderManager.OnRefreshProgress(folder, percent); }); if (validChildrenNeedGeneration) @@ -424,11 +466,11 @@ namespace MediaBrowser.Controller.Entities if (refreshChildMetadata) { - progress.Report(90); + progress.Report(ProgressHelpers.ScannedSubfolders); if (recursive) { - ProviderManager.OnRefreshProgress(this, 90); + ProviderManager.OnRefreshProgress(this, ProgressHelpers.ScannedSubfolders); } var container = this as IMetadataContainer; @@ -436,13 +478,15 @@ namespace MediaBrowser.Controller.Entities var innerProgress = new ActionableProgress(); var folder = this; - innerProgress.RegisterAction(p => + innerProgress.RegisterAction(innerPercent => { - double newPct = 0.10 * p + 90; - progress.Report(newPct); + var percent = ProgressHelpers.GetProgress(ProgressHelpers.ScannedSubfolders, ProgressHelpers.RefreshedMetadata, innerPercent); + + progress.Report(percent); + if (recursive) { - ProviderManager.OnRefreshProgress(folder, newPct); + ProviderManager.OnRefreshProgress(folder, percent); } }); @@ -457,55 +501,37 @@ namespace MediaBrowser.Controller.Entities validChildren = Children.ToList(); } - await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken); + await RefreshMetadataRecursive(validChildren, refreshOptions, recursive, innerProgress, cancellationToken).ConfigureAwait(false); } } } - private async Task RefreshMetadataRecursive(List children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress progress, CancellationToken cancellationToken) + private Task RefreshMetadataRecursive(IList children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress progress, CancellationToken cancellationToken) { - var numComplete = 0; - var count = children.Count; - double currentPercent = 0; + var progressableTasks = children + .Select, Task>>(child => + innerProgress => RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken)) + .ToList(); - foreach (var child in children) - { - cancellationToken.ThrowIfCancellationRequested(); - - var innerProgress = new ActionableProgress(); - - // Avoid implicitly captured closure - var currentInnerPercent = currentPercent; - - innerProgress.RegisterAction(p => - { - double innerPercent = currentInnerPercent; - innerPercent += p / count; - progress.Report(innerPercent); - }); - - await RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken) - .ConfigureAwait(false); - - numComplete++; - double percent = numComplete; - percent /= count; - percent *= 100; - currentPercent = percent; - - progress.Report(percent); - } + return RunTasks(progressableTasks, progress, cancellationToken); } private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress progress, CancellationToken cancellationToken) { - var series = container as Series; - if (series != null) - { - await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); - } + // limit the amount of concurrent metadata refreshes + await TaskMethods.RunThrottled( + TaskMethods.SharedThrottleId.RefreshMetadata, + async () => + { + var series = container as Series; + if (series != null) + { + await series.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + } - await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false); + await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false); + }, + cancellationToken).ConfigureAwait(false); } private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress progress, CancellationToken cancellationToken) @@ -520,12 +546,16 @@ namespace MediaBrowser.Controller.Entities { if (refreshOptions.RefreshItem(child)) { - await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false); + // limit the amount of concurrent metadata refreshes + await TaskMethods.RunThrottled( + TaskMethods.SharedThrottleId.RefreshMetadata, + async () => await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false), + cancellationToken).ConfigureAwait(false); } if (recursive && child is Folder folder) { - await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken); + await folder.RefreshMetadataRecursive(folder.Children.ToList(), refreshOptions, true, progress, cancellationToken).ConfigureAwait(false); } } } @@ -538,39 +568,63 @@ namespace MediaBrowser.Controller.Entities /// The progress. /// The cancellation token. /// Task. - private async Task ValidateSubFolders(IList children, IDirectoryService directoryService, IProgress progress, CancellationToken cancellationToken) + private Task ValidateSubFolders(IList children, IDirectoryService directoryService, IProgress progress, CancellationToken cancellationToken) { - var numComplete = 0; - var count = children.Count; - double currentPercent = 0; + var progressableTasks = children + .Select, Task>>(child => + innerProgress => child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)) + .ToList(); - foreach (var child in children) + return RunTasks(progressableTasks, progress, cancellationToken); + } + + /// + /// Runs a set of tasks concurrently with progress. + /// + /// A list of tasks. + /// The progress. + /// The cancellation token. + /// Task. + private async Task RunTasks(IList, Task>> tasks, IProgress progress, CancellationToken cancellationToken) + { + var childrenCount = tasks.Count; + var childrenProgress = new double[childrenCount]; + var actions = new Func[childrenCount]; + + void UpdateProgress() { - cancellationToken.ThrowIfCancellationRequested(); - - var innerProgress = new ActionableProgress(); - - // Avoid implicitly captured closure - var currentInnerPercent = currentPercent; - - innerProgress.RegisterAction(p => - { - double innerPercent = currentInnerPercent; - innerPercent += p / count; - progress.Report(innerPercent); - }); - - await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService) - .ConfigureAwait(false); - - numComplete++; - double percent = numComplete; - percent /= count; - percent *= 100; - currentPercent = percent; - - progress.Report(percent); + progress.Report(childrenProgress.Average()); } + + for (var i = 0; i < childrenCount; i++) + { + var childIndex = i; + var child = tasks[childIndex]; + + actions[childIndex] = async () => + { + var innerProgress = new ActionableProgress(); + + innerProgress.RegisterAction(innerPercent => + { + // round the percent and only update progress if it changed to prevent excessive UpdateProgress calls + var innerPercentRounded = Math.Round(innerPercent); + if (childrenProgress[childIndex] != innerPercentRounded) + { + childrenProgress[childIndex] = innerPercentRounded; + UpdateProgress(); + } + }); + + await tasks[childIndex](innerProgress).ConfigureAwait(false); + + childrenProgress[childIndex] = 100; + + UpdateProgress(); + }; + } + + await TaskMethods.WhenAllThrottled(TaskMethods.SharedThrottleId.ScanFanout, actions, cancellationToken).ConfigureAwait(false); } /// diff --git a/MediaBrowser.Controller/Library/TaskMethods.cs b/MediaBrowser.Controller/Library/TaskMethods.cs new file mode 100644 index 0000000000..66bfbe0d9e --- /dev/null +++ b/MediaBrowser.Controller/Library/TaskMethods.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Configuration; + +namespace MediaBrowser.Controller.Library +{ + /// + /// Helper methods for running tasks concurrently. + /// + public static class TaskMethods + { + private static readonly int _processorCount = Environment.ProcessorCount; + + private static readonly ConcurrentDictionary _sharedThrottlers = new ConcurrentDictionary(); + + /// + /// Throttle id for sharing a concurrency limit. + /// + public enum SharedThrottleId + { + /// + /// Library scan fan out + /// + ScanFanout, + + /// + /// Refresh metadata + /// + RefreshMetadata, + } + + /// + /// Gets or sets the configuration manager. + /// + public static IServerConfigurationManager ConfigurationManager { get; set; } + + /// + /// Similiar to Task.WhenAll but only allows running a certain amount of tasks at the same time. + /// + /// The throttle id. Multiple calls to this method with the same throttle id will share a concurrency limit. + /// List of actions to run. + /// The cancellation token. + /// A representing the result of the asynchronous operation. + public static async Task WhenAllThrottled(SharedThrottleId throttleId, IEnumerable> actions, CancellationToken cancellationToken) + { + var taskThrottler = throttleId == SharedThrottleId.ScanFanout ? + new SemaphoreSlim(GetConcurrencyLimit(throttleId)) : + _sharedThrottlers.GetOrAdd(throttleId, id => new SemaphoreSlim(GetConcurrencyLimit(id))); + + try + { + var tasks = new List(); + + foreach (var action in actions) + { + await taskThrottler.WaitAsync(cancellationToken).ConfigureAwait(false); + + tasks.Add(Task.Run(async () => + { + try + { + await action().ConfigureAwait(false); + } + finally + { + taskThrottler.Release(); + } + })); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + } + finally + { + if (throttleId == SharedThrottleId.ScanFanout) + { + taskThrottler.Dispose(); + } + } + } + + /// + /// Runs a task within a given throttler. + /// + /// The throttle id. Multiple calls to this method with the same throttle id will share a concurrency limit. + /// The action to run. + /// The cancellation token. + /// A representing the result of the asynchronous operation. + public static async Task RunThrottled(SharedThrottleId throttleId, Func action, CancellationToken cancellationToken) + { + if (throttleId == SharedThrottleId.ScanFanout) + { + // just await the task instead + throw new InvalidOperationException("Invalid throttle id"); + } + + var taskThrottler = _sharedThrottlers.GetOrAdd(throttleId, id => new SemaphoreSlim(GetConcurrencyLimit(id))); + + await taskThrottler.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + await action().ConfigureAwait(false); + } + finally + { + taskThrottler.Release(); + } + } + + /// + /// Get the concurrency limit for the given throttle id. + /// + /// The throttle id. + /// The concurrency limit. + private static int GetConcurrencyLimit(SharedThrottleId throttleId) + { + var concurrency = throttleId == SharedThrottleId.RefreshMetadata ? + ConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency : + ConfigurationManager.Configuration.LibraryScanFanoutConcurrency; + + if (concurrency <= 0) + { + concurrency = _processorCount; + } + + return concurrency; + } + } +} diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 8b78ad842e..14bfcbf9e2 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -271,6 +271,16 @@ namespace MediaBrowser.Model.Configuration /// public string[] KnownProxies { get; set; } + /// + /// Gets or sets the how the library scan fans out. + /// + public int LibraryScanFanoutConcurrency { get; set; } + + /// + /// Gets or sets the how many metadata refreshes can run concurrently. + /// + public int LibraryMetadataRefreshConcurrency { get; set; } + /// /// Initializes a new instance of the class. /// @@ -381,6 +391,8 @@ namespace MediaBrowser.Model.Configuration SlowResponseThresholdMs = 500; CorsHosts = new[] { "*" }; KnownProxies = Array.Empty(); + LibraryMetadataRefreshConcurrency = 0; + LibraryScanFanoutConcurrency = 0; } } From ee40f210494985286f5afd37aca4a05dba6f4763 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 1 Oct 2020 18:59:46 +0100 Subject: [PATCH 0046/1930] Update ApplicationHost.cs --- .../ApplicationHost.cs | 371 ++++++------------ 1 file changed, 116 insertions(+), 255 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 7a46fdf2e7..91fb68ed14 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,7 +1,6 @@ #pragma warning disable CS1591 using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -9,7 +8,6 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; -using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; @@ -17,8 +15,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Emby.Dlna; -using Emby.Dlna.Main; -using Emby.Dlna.Ssdp; +using Emby.Dlna.Common; using Emby.Drawing; using Emby.Notifications; using Emby.Photos; @@ -30,13 +27,11 @@ using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Devices; using Emby.Server.Implementations.Dto; -using Emby.Server.Implementations.HttpServer; using Emby.Server.Implementations.HttpServer.Security; using Emby.Server.Implementations.IO; using Emby.Server.Implementations.Library; using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; -using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.Plugins; using Emby.Server.Implementations.QuickConnect; @@ -48,10 +43,13 @@ using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; +using Jellyfin.Networking.Advertising; +using Jellyfin.Networking.Gateway; +using Jellyfin.Networking.Manager; +using Jellyfin.Networking.UPnP; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; -using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -61,7 +59,6 @@ using MediaBrowser.Controller.Chapters; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; -using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -86,11 +83,9 @@ using MediaBrowser.LocalMetadata.Savers; using MediaBrowser.MediaEncoding.BdInfo; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Cryptography; -using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -99,6 +94,7 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Plugins.TheTvdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -119,7 +115,6 @@ namespace Emby.Server.Implementations private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" }; private readonly IFileSystem _fileSystemManager; - private readonly INetworkManager _networkManager; private readonly IXmlSerializer _xmlSerializer; private readonly IJsonSerializer _jsonSerializer; private readonly IStartupOptions _startupOptions; @@ -214,7 +209,7 @@ namespace Emby.Server.Implementations private readonly List _disposableParts = new List(); /// - /// Gets the configuration manager. + /// Gets or sets the configuration manager. /// /// The configuration manager. protected IConfigurationManager ConfigurationManager { get; set; } @@ -247,23 +242,18 @@ namespace Emby.Server.Implementations /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. public ApplicationHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, IFileSystem fileSystem, - INetworkManager networkManager, IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - - ServiceCollection = serviceCollection; + _jsonSerializer = new JsonSerializer(); - _networkManager = networkManager; - networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; + ServiceCollection = serviceCollection; ApplicationPaths = applicationPaths; LoggerFactory = loggerFactory; @@ -271,6 +261,8 @@ namespace Emby.Server.Implementations ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); + NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); + Logger = LoggerFactory.CreateLogger(); _startupOptions = options; @@ -283,20 +275,19 @@ namespace Emby.Server.Implementations fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); - _networkManager.NetworkChanged += OnNetworkChanged; - CertificateInfo = new CertificateInfo { Path = ServerConfigurationManager.Configuration.CertificatePath, Password = ServerConfigurationManager.Configuration.CertificatePassword }; Certificate = GetCertificate(CertificateInfo); - - ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; - ApplicationVersionString = ApplicationVersion.ToString(3); - ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; } + /// + /// Gets the NetworkManager instance. + /// + public INetworkManager NetManager { get; internal set; } + public string ExpandVirtualPath(string path) { var appPaths = ApplicationPaths; @@ -313,27 +304,17 @@ namespace Emby.Server.Implementations .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase); } - private string[] GetConfiguredLocalSubnets() - { - return ServerConfigurationManager.Configuration.LocalNetworkSubnets; - } - - private void OnNetworkChanged(object sender, EventArgs e) - { - _validAddressResults.Clear(); - } + /// + public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version; /// - public Version ApplicationVersion { get; } - - /// - public string ApplicationVersionString { get; } + public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3); /// /// Gets the current application user agent. /// /// The application user agent. - public string ApplicationUserAgent { get; } + public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString; /// /// Gets the email address for use within a comment section of a user agent field. @@ -403,7 +384,7 @@ namespace Emby.Server.Implementations /// /// Resolves this instance. /// - /// The type + /// The type. /// ``0. public T Resolve() => ServiceProvider.GetService(); @@ -499,21 +480,6 @@ namespace Emby.Server.Implementations HttpsPort = ServerConfiguration.DefaultHttpsPort; } - if (Plugins != null) - { - var pluginBuilder = new StringBuilder(); - - foreach (var plugin in Plugins) - { - pluginBuilder.Append(plugin.Name) - .Append(' ') - .Append(plugin.Version) - .AppendLine(); - } - - Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); - } - DiscoverTypes(); RegisterServices(); @@ -538,7 +504,10 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(_fileSystemManager); ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(_networkManager); + ServiceCollection.AddSingleton(NetManager); + ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -550,8 +519,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -628,8 +595,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -785,6 +750,21 @@ namespace Emby.Server.Implementations .Where(i => i != null) .ToArray(); + if (Plugins != null) + { + var pluginBuilder = new StringBuilder(); + + foreach (var plugin in Plugins) + { + pluginBuilder.Append(plugin.Name) + .Append(' ') + .Append(plugin.Version) + .AppendLine(); + } + + Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); + } + _urlPrefixes = GetUrlPrefixes().ToArray(); _webSocketManager.Init(GetExports()); @@ -819,38 +799,6 @@ namespace Emby.Server.Implementations { try { - if (plugin is IPluginAssembly assemblyPlugin) - { - var assembly = plugin.GetType().Assembly; - var assemblyName = assembly.GetName(); - var assemblyFilePath = assembly.Location; - - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - - assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); - - try - { - var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); - if (idAttributes.Length > 0) - { - var attribute = (GuidAttribute)idAttributes[0]; - var assemblyId = new Guid(attribute.Value); - - assemblyPlugin.SetId(assemblyId); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName); - } - } - - if (plugin is IHasPluginConfiguration hasPluginConfiguration) - { - hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); - } - plugin.RegisterServices(ServiceCollection); } catch (Exception ex) @@ -880,6 +828,21 @@ namespace Emby.Server.Implementations try { exportedTypes = ass.GetExportedTypes(); + + try + { + Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + if (reg != null) + { + var pluginRegistration = Activator.CreateInstance(reg); + reg.InvokeMember("RegisterServices", BindingFlags.InvokeMethod, null, pluginRegistration, new object[] { ServiceCollection }, CultureInfo.InvariantCulture); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Error registering {Assembly} with D.I.", ass.FullName); + continue; + } } catch (FileNotFoundException ex) { @@ -1088,7 +1051,7 @@ namespace Emby.Server.Implementations { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) { @@ -1097,9 +1060,9 @@ namespace Emby.Server.Implementations } else { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. + // Un-versioned folder - Add it under the path name and version 0.0.0.1. versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + } } } catch @@ -1186,9 +1149,6 @@ namespace Emby.Server.Implementations // MediaEncoding yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly; - // Dlna - yield return typeof(DlnaEntryPoint).Assembly; - // Local metadata yield return typeof(BoxSetXmlSaver).Assembly; @@ -1209,13 +1169,10 @@ namespace Emby.Server.Implementations /// /// Gets the system status. /// - /// The cancellation token. + /// Where this request originated. /// SystemInfo. - public async Task GetSystemInfo(CancellationToken cancellationToken) + public SystemInfo GetSystemInfo(IPAddress source) { - var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - var transcodingTempPath = ConfigurationManager.GetTranscodePath(); - return new SystemInfo { HasPendingRestart = HasPendingRestart, @@ -1235,9 +1192,9 @@ namespace Emby.Server.Implementations CanSelfRestart = CanSelfRestart, CanLaunchWebBrowser = CanLaunchWebBrowser, HasUpdateAvailable = HasUpdateAvailable, - TranscodingTempPath = transcodingTempPath, + TranscodingTempPath = ConfigurationManager.GetTranscodePath(), ServerName = FriendlyName, - LocalAddress = localAddress, + LocalAddress = GetSmartApiUrl(source), SupportsLibraryMonitor = true, EncoderLocation = _mediaEncoder.EncoderLocation, SystemArchitecture = RuntimeInformation.OSArchitecture, @@ -1246,14 +1203,12 @@ namespace Emby.Server.Implementations } public IEnumerable GetWakeOnLanInfo() - => _networkManager.GetMacAddresses() + => NetManager.GetMacAddresses() .Select(i => new WakeOnLanInfo(i)) .ToList(); - public async Task GetPublicSystemInfo(CancellationToken cancellationToken) + public PublicSystemInfo GetPublicSystemInfo(IPAddress source) { - var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); - return new PublicSystemInfo { Version = ApplicationVersionString, @@ -1261,7 +1216,7 @@ namespace Emby.Server.Implementations Id = SystemId, OperatingSystem = OperatingSystem.Id.ToString(), ServerName = FriendlyName, - LocalAddress = localAddress, + LocalAddress = GetSmartApiUrl(source), StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted }; } @@ -1270,186 +1225,92 @@ namespace Emby.Server.Implementations public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps; /// - public async Task GetLocalApiUrl(CancellationToken cancellationToken) + public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) { - try + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) { - // Return the first matched address, if found, or the first known local address - var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false); - if (addresses.Count == 0) - { - return null; - } - - return GetLocalApiUrl(addresses[0]); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error getting local Ip address information"); + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); } - return null; + string smart = NetManager.GetBindInterface(ipAddress, out port); + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return smart.Trim('/'); + } + + return GetLocalApiUrl(smart.Trim('/'), null, port); } - /// - /// Removes the scope id from IPv6 addresses. - /// - /// The IPv6 address. - /// The IPv6 address without the scope id. - private ReadOnlySpan RemoveScopeId(ReadOnlySpan address) + public string GetSmartApiUrl(HttpRequest request, int? port = null) { - var index = address.IndexOf('%'); - if (index == -1) + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) { - return address; + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); } - return address.Slice(0, index); + string smart = NetManager.GetBindInterface(request, out port); + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return smart.Trim('/'); + } + + return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port); } - /// - public string GetLocalApiUrl(IPAddress ipAddress) + public string GetSmartApiUrl(string hostname, int? port = null) { - if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) + // Published server ends with a / + if (_startupOptions.PublishedServerUrl != null) { - var str = RemoveScopeId(ipAddress.ToString()); - Span span = new char[str.Length + 2]; - span[0] = '['; - str.CopyTo(span.Slice(1)); - span[^1] = ']'; - - return GetLocalApiUrl(span); + // Published server ends with a '/', so we need to remove it. + return _startupOptions.PublishedServerUrl.ToString().Trim('/'); } - return GetLocalApiUrl(ipAddress.ToString()); + string smart = NetManager.GetBindInterface(hostname, out port); + + // If the smartAPI doesn't start with http then treat it as a host or ip. + if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return smart.Trim('/'); + } + + return GetLocalApiUrl(smart.Trim('/'), null, port); } /// public string GetLoopbackHttpApiUrl() { + if (NetManager.IsIP6Enabled) + { + return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort); + } + return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort); } /// - public string GetLocalApiUrl(ReadOnlySpan host, string scheme = null, int? port = null) + public string GetLocalApiUrl(string host, string scheme = null, int? port = null) { // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does // not. For consistency, always trim the trailing slash. return new UriBuilder { Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp), - Host = host.ToString(), + Host = host, Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort), Path = ServerConfigurationManager.Configuration.BaseUrl }.ToString().TrimEnd('/'); } - public Task> GetLocalIpAddresses(CancellationToken cancellationToken) - { - return GetLocalIpAddressesInternal(true, 0, cancellationToken); - } - - private async Task> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken) - { - var addresses = ServerConfigurationManager - .Configuration - .LocalNetworkAddresses - .Select(x => NormalizeConfiguredLocalAddress(x)) - .Where(i => i != null) - .ToList(); - - if (addresses.Count == 0) - { - addresses.AddRange(_networkManager.GetLocalIpAddresses()); - } - - var resultList = new List(); - - foreach (var address in addresses) - { - if (!allowLoopback) - { - if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback)) - { - continue; - } - } - - if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false)) - { - resultList.Add(address); - - if (limit > 0 && resultList.Count >= limit) - { - return resultList; - } - } - } - - return resultList; - } - - public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan address) - { - var index = address.Trim('/').IndexOf('/'); - if (index != -1) - { - address = address.Slice(index + 1); - } - - if (IPAddress.TryParse(address.Trim('/'), out IPAddress result)) - { - return result; - } - - return null; - } - - private readonly ConcurrentDictionary _validAddressResults = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - private async Task IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken) - { - if (address.Equals(IPAddress.Loopback) - || address.Equals(IPAddress.IPv6Loopback)) - { - return true; - } - - var apiUrl = GetLocalApiUrl(address) + "/system/ping"; - - if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult)) - { - return cachedResult; - } - - try - { - using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); - using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); - var result = await System.Text.Json.JsonSerializer.DeserializeAsync(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); - var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); - - _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid); - Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid); - return valid; - } - catch (OperationCanceledException) - { - Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); - throw; - } - catch (Exception ex) - { - Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false); - - _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); - return false; - } - } - + /// + /// Gets the servers friendly name. + /// public string FriendlyName => string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) ? Environment.MachineName @@ -1521,7 +1382,7 @@ namespace Emby.Server.Implementations foreach (var assembly in assemblies) { - Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName); + Logger.LogDebug("Found API endpoints in plugin {name}", assembly.FullName); yield return assembly; } } From 0738a2dc4b64c3656cc8a613d1dc5b2c09ab0240 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 1 Oct 2020 19:22:58 +0100 Subject: [PATCH 0047/1930] Update ApplicationHost.cs --- .../ApplicationHost.cs | 358 +++++++++++++----- 1 file changed, 256 insertions(+), 102 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 91fb68ed14..f36bc0eef2 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -8,6 +9,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Http; +using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; @@ -15,7 +17,8 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Emby.Dlna; -using Emby.Dlna.Common; +using Emby.Dlna.Main; +using Emby.Dlna.Ssdp; using Emby.Drawing; using Emby.Notifications; using Emby.Photos; @@ -27,11 +30,13 @@ using Emby.Server.Implementations.Cryptography; using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Devices; using Emby.Server.Implementations.Dto; +using Emby.Server.Implementations.HttpServer; using Emby.Server.Implementations.HttpServer.Security; using Emby.Server.Implementations.IO; using Emby.Server.Implementations.Library; using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; +using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.Plugins; using Emby.Server.Implementations.QuickConnect; @@ -43,13 +48,10 @@ using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; -using Jellyfin.Networking.Advertising; -using Jellyfin.Networking.Gateway; -using Jellyfin.Networking.Manager; -using Jellyfin.Networking.UPnP; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -59,6 +61,7 @@ using MediaBrowser.Controller.Chapters; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; +using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -83,9 +86,11 @@ using MediaBrowser.LocalMetadata.Savers; using MediaBrowser.MediaEncoding.BdInfo; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Cryptography; +using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; @@ -94,7 +99,6 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Plugins.TheTvdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -115,6 +119,7 @@ namespace Emby.Server.Implementations private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" }; private readonly IFileSystem _fileSystemManager; + private readonly INetworkManager _networkManager; private readonly IXmlSerializer _xmlSerializer; private readonly IJsonSerializer _jsonSerializer; private readonly IStartupOptions _startupOptions; @@ -209,7 +214,7 @@ namespace Emby.Server.Implementations private readonly List _disposableParts = new List(); /// - /// Gets or sets the configuration manager. + /// Gets the configuration manager. /// /// The configuration manager. protected IConfigurationManager ConfigurationManager { get; set; } @@ -242,27 +247,30 @@ namespace Emby.Server.Implementations /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. /// Instance of the interface. public ApplicationHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, IFileSystem fileSystem, + INetworkManager networkManager, IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - + _jsonSerializer = new JsonSerializer(); + ServiceCollection = serviceCollection; + _networkManager = networkManager; + networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; + ApplicationPaths = applicationPaths; LoggerFactory = loggerFactory; _fileSystemManager = fileSystem; ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); - NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); - Logger = LoggerFactory.CreateLogger(); _startupOptions = options; @@ -275,18 +283,19 @@ namespace Emby.Server.Implementations fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); + _networkManager.NetworkChanged += OnNetworkChanged; + CertificateInfo = new CertificateInfo { Path = ServerConfigurationManager.Configuration.CertificatePath, Password = ServerConfigurationManager.Configuration.CertificatePassword }; Certificate = GetCertificate(CertificateInfo); - } - /// - /// Gets the NetworkManager instance. - /// - public INetworkManager NetManager { get; internal set; } + ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; + ApplicationVersionString = ApplicationVersion.ToString(3); + ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; + } public string ExpandVirtualPath(string path) { @@ -304,17 +313,27 @@ namespace Emby.Server.Implementations .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase); } - /// - public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version; + private string[] GetConfiguredLocalSubnets() + { + return ServerConfigurationManager.Configuration.LocalNetworkSubnets; + } + + private void OnNetworkChanged(object sender, EventArgs e) + { + _validAddressResults.Clear(); + } /// - public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3); + public Version ApplicationVersion { get; } + + /// + public string ApplicationVersionString { get; } /// /// Gets the current application user agent. /// /// The application user agent. - public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString; + public string ApplicationUserAgent { get; } /// /// Gets the email address for use within a comment section of a user agent field. @@ -384,7 +403,7 @@ namespace Emby.Server.Implementations /// /// Resolves this instance. /// - /// The type. + /// The type /// ``0. public T Resolve() => ServiceProvider.GetService(); @@ -480,6 +499,21 @@ namespace Emby.Server.Implementations HttpsPort = ServerConfiguration.DefaultHttpsPort; } + if (Plugins != null) + { + var pluginBuilder = new StringBuilder(); + + foreach (var plugin in Plugins) + { + pluginBuilder.Append(plugin.Name) + .Append(' ') + .Append(plugin.Version) + .AppendLine(); + } + + Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); + } + DiscoverTypes(); RegisterServices(); @@ -504,10 +538,7 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(_fileSystemManager); ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(NetManager); - ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(_networkManager); ServiceCollection.AddSingleton(); @@ -519,6 +550,8 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -595,6 +628,8 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -750,21 +785,6 @@ namespace Emby.Server.Implementations .Where(i => i != null) .ToArray(); - if (Plugins != null) - { - var pluginBuilder = new StringBuilder(); - - foreach (var plugin in Plugins) - { - pluginBuilder.Append(plugin.Name) - .Append(' ') - .Append(plugin.Version) - .AppendLine(); - } - - Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); - } - _urlPrefixes = GetUrlPrefixes().ToArray(); _webSocketManager.Init(GetExports()); @@ -799,6 +819,38 @@ namespace Emby.Server.Implementations { try { + if (plugin is IPluginAssembly assemblyPlugin) + { + var assembly = plugin.GetType().Assembly; + var assemblyName = assembly.GetName(); + var assemblyFilePath = assembly.Location; + + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + + assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); + + try + { + var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); + if (idAttributes.Length > 0) + { + var attribute = (GuidAttribute)idAttributes[0]; + var assemblyId = new Guid(attribute.Value); + + assemblyPlugin.SetId(assemblyId); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName); + } + } + + if (plugin is IHasPluginConfiguration hasPluginConfiguration) + { + hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); + } + plugin.RegisterServices(ServiceCollection); } catch (Exception ex) @@ -828,7 +880,7 @@ namespace Emby.Server.Implementations try { exportedTypes = ass.GetExportedTypes(); - + try { Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); @@ -1051,7 +1103,7 @@ namespace Emby.Server.Implementations { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) { @@ -1060,9 +1112,9 @@ namespace Emby.Server.Implementations } else { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. + // Un-versioned folder - Add it under the path name and version 0.0.0.1. versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + } } } catch @@ -1149,6 +1201,9 @@ namespace Emby.Server.Implementations // MediaEncoding yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly; + // Dlna + yield return typeof(DlnaEntryPoint).Assembly; + // Local metadata yield return typeof(BoxSetXmlSaver).Assembly; @@ -1169,10 +1224,13 @@ namespace Emby.Server.Implementations /// /// Gets the system status. /// - /// Where this request originated. + /// The cancellation token. /// SystemInfo. - public SystemInfo GetSystemInfo(IPAddress source) + public async Task GetSystemInfo(CancellationToken cancellationToken) { + var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + var transcodingTempPath = ConfigurationManager.GetTranscodePath(); + return new SystemInfo { HasPendingRestart = HasPendingRestart, @@ -1192,9 +1250,9 @@ namespace Emby.Server.Implementations CanSelfRestart = CanSelfRestart, CanLaunchWebBrowser = CanLaunchWebBrowser, HasUpdateAvailable = HasUpdateAvailable, - TranscodingTempPath = ConfigurationManager.GetTranscodePath(), + TranscodingTempPath = transcodingTempPath, ServerName = FriendlyName, - LocalAddress = GetSmartApiUrl(source), + LocalAddress = localAddress, SupportsLibraryMonitor = true, EncoderLocation = _mediaEncoder.EncoderLocation, SystemArchitecture = RuntimeInformation.OSArchitecture, @@ -1203,12 +1261,14 @@ namespace Emby.Server.Implementations } public IEnumerable GetWakeOnLanInfo() - => NetManager.GetMacAddresses() + => _networkManager.GetMacAddresses() .Select(i => new WakeOnLanInfo(i)) .ToList(); - public PublicSystemInfo GetPublicSystemInfo(IPAddress source) + public async Task GetPublicSystemInfo(CancellationToken cancellationToken) { + var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false); + return new PublicSystemInfo { Version = ApplicationVersionString, @@ -1216,7 +1276,7 @@ namespace Emby.Server.Implementations Id = SystemId, OperatingSystem = OperatingSystem.Id.ToString(), ServerName = FriendlyName, - LocalAddress = GetSmartApiUrl(source), + LocalAddress = localAddress, StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted }; } @@ -1225,92 +1285,186 @@ namespace Emby.Server.Implementations public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps; /// - public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) + public async Task GetLocalApiUrl(CancellationToken cancellationToken) { - // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + try { - // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + // Return the first matched address, if found, or the first known local address + var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false); + if (addresses.Count == 0) + { + return null; + } + + return GetLocalApiUrl(addresses[0]); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error getting local Ip address information"); } - string smart = NetManager.GetBindInterface(ipAddress, out port); - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - - return GetLocalApiUrl(smart.Trim('/'), null, port); + return null; } - public string GetSmartApiUrl(HttpRequest request, int? port = null) + /// + /// Removes the scope id from IPv6 addresses. + /// + /// The IPv6 address. + /// The IPv6 address without the scope id. + private ReadOnlySpan RemoveScopeId(ReadOnlySpan address) { - // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + var index = address.IndexOf('%'); + if (index == -1) { - // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + return address; } - string smart = NetManager.GetBindInterface(request, out port); - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - - return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port); + return address.Slice(0, index); } - public string GetSmartApiUrl(string hostname, int? port = null) + /// + public string GetLocalApiUrl(IPAddress ipAddress) { - // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { - // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + var str = RemoveScopeId(ipAddress.ToString()); + Span span = new char[str.Length + 2]; + span[0] = '['; + str.CopyTo(span.Slice(1)); + span[^1] = ']'; + + return GetLocalApiUrl(span); } - string smart = NetManager.GetBindInterface(hostname, out port); - - // If the smartAPI doesn't start with http then treat it as a host or ip. - if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - return smart.Trim('/'); - } - - return GetLocalApiUrl(smart.Trim('/'), null, port); + return GetLocalApiUrl(ipAddress.ToString()); } /// public string GetLoopbackHttpApiUrl() { - if (NetManager.IsIP6Enabled) - { - return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort); - } - return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort); } /// - public string GetLocalApiUrl(string host, string scheme = null, int? port = null) + public string GetLocalApiUrl(ReadOnlySpan host, string scheme = null, int? port = null) { // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does // not. For consistency, always trim the trailing slash. return new UriBuilder { Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp), - Host = host, + Host = host.ToString(), Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort), Path = ServerConfigurationManager.Configuration.BaseUrl }.ToString().TrimEnd('/'); } - /// - /// Gets the servers friendly name. - /// + public Task> GetLocalIpAddresses(CancellationToken cancellationToken) + { + return GetLocalIpAddressesInternal(true, 0, cancellationToken); + } + + private async Task> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken) + { + var addresses = ServerConfigurationManager + .Configuration + .LocalNetworkAddresses + .Select(x => NormalizeConfiguredLocalAddress(x)) + .Where(i => i != null) + .ToList(); + + if (addresses.Count == 0) + { + addresses.AddRange(_networkManager.GetLocalIpAddresses()); + } + + var resultList = new List(); + + foreach (var address in addresses) + { + if (!allowLoopback) + { + if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback)) + { + continue; + } + } + + if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false)) + { + resultList.Add(address); + + if (limit > 0 && resultList.Count >= limit) + { + return resultList; + } + } + } + + return resultList; + } + + public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan address) + { + var index = address.Trim('/').IndexOf('/'); + if (index != -1) + { + address = address.Slice(index + 1); + } + + if (IPAddress.TryParse(address.Trim('/'), out IPAddress result)) + { + return result; + } + + return null; + } + + private readonly ConcurrentDictionary _validAddressResults = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + private async Task IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken) + { + if (address.Equals(IPAddress.Loopback) + || address.Equals(IPAddress.IPv6Loopback)) + { + return true; + } + + var apiUrl = GetLocalApiUrl(address) + "/system/ping"; + + if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult)) + { + return cachedResult; + } + + try + { + using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); + using var response = await _httpClientFactory.CreateClient(NamedClient.Default) + .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + + await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var result = await System.Text.Json.JsonSerializer.DeserializeAsync(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); + + _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid); + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid); + return valid; + } + catch (OperationCanceledException) + { + Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled"); + throw; + } + catch (Exception ex) + { + Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false); + + _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false); + return false; + } + } + public string FriendlyName => string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) ? Environment.MachineName @@ -1382,7 +1536,7 @@ namespace Emby.Server.Implementations foreach (var assembly in assemblies) { - Logger.LogDebug("Found API endpoints in plugin {name}", assembly.FullName); + Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName); yield return assembly; } } From 688d098d61027bc10da7b0dbbb4f89a185e07444 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 1 Oct 2020 20:51:25 +0100 Subject: [PATCH 0048/1930] Update Emby.Server.Implementations.csproj --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 444fee33a6..4d7919d8b2 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -13,7 +13,7 @@ - + From 02de44ec0c1e81fac698425ebf54fbe97e7aea41 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 1 Oct 2020 20:54:39 +0100 Subject: [PATCH 0049/1930] Update BaseAuthorizationHandler.cs --- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index e245b57681..d732b6bc6a 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,4 +1,4 @@ -using System.Security.Claims; +using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; From 3ad62329731c1156566bd707f21cad60e74f9a5f Mon Sep 17 00:00:00 2001 From: Stanislav Ionascu Date: Thu, 24 Sep 2020 08:41:42 +0200 Subject: [PATCH 0050/1930] Add probe / direct-stream / transcoding support for BluRays This commit (and ffmpeg built with libbluray support), adds support for playback of bluray images (bd-iso) and bluray folders. --- .../MediaEncoder/EncodingManager.cs | 20 ++++----- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 4 +- .../MediaEncoding/EncodingHelper.cs | 24 +---------- .../MediaEncoding/IMediaEncoder.cs | 11 ++--- .../MediaEncoding/MediaEncoderHelpers.cs | 10 +---- .../Attachments/AttachmentExtractor.cs | 16 +++---- .../Encoder/EncodingUtils.cs | 14 ++++--- .../Encoder/MediaEncoder.cs | 42 ++++++++++++------- .../Subtitles/SubtitleEncoder.cs | 36 ++++++++-------- .../MediaInfo/FFProbeProvider.cs | 5 --- .../MediaInfo/VideoImageProvider.cs | 21 ++++++++-- 11 files changed, 101 insertions(+), 102 deletions(-) diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index 438bbe24a5..791d009637 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -12,6 +12,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -81,12 +82,7 @@ namespace Emby.Server.Implementations.MediaEncoder return false; } - if (video.VideoType == VideoType.Iso) - { - return false; - } - - if (video.VideoType == VideoType.BluRay || video.VideoType == VideoType.Dvd) + if (video.VideoType == VideoType.Dvd) { return false; } @@ -140,15 +136,19 @@ namespace Emby.Server.Implementations.MediaEncoder // Add some time for the first chapter to make sure we don't end up with a black image var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks); - var protocol = MediaProtocol.File; - - var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, null, Array.Empty()); + var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, Array.Empty()); Directory.CreateDirectory(Path.GetDirectoryName(path)); var container = video.Container; + var mediaSource = new MediaSourceInfo + { + VideoType = video.VideoType, + IsoType = video.IsoType, + Protocol = video.PathProtocol.Value, + }; - var tempFile = await _encoder.ExtractVideoImage(inputPath, container, protocol, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false); + var tempFile = await _encoder.ExtractVideoImage(inputPath, container, mediaSource, video.GetDefaultVideoStream(), video.Video3DFormat, time, cancellationToken).ConfigureAwait(false); File.Copy(tempFile, path, true); try diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 64d1227f7c..465857b01e 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -762,7 +762,7 @@ namespace Jellyfin.Api.Helpers private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource) { - if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && _isoManager.CanMount(state.MediaPath)) + if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && state.IsoType == IsoType.Dvd && _isoManager.CanMount(state.MediaPath)) { state.IsoMount = await _isoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false); } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index c5529ad5bd..7481cc7b96 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -379,25 +379,9 @@ namespace MediaBrowser.Controller.MediaEncoding public string GetInputPathArgument(EncodingJobInfo state) { - var protocol = state.InputProtocol; var mediaPath = state.MediaPath ?? string.Empty; - string[] inputPath; - if (state.IsInputVideo - && !(state.VideoType == VideoType.Iso && state.IsoMount == null)) - { - inputPath = MediaEncoderHelpers.GetInputArgument( - _fileSystem, - mediaPath, - state.IsoMount, - state.PlayableStreamFileNames); - } - else - { - inputPath = new[] { mediaPath }; - } - - return _mediaEncoder.GetInputArgument(inputPath, protocol); + return _mediaEncoder.GetInputArgument(mediaPath, state.MediaSource); } /// @@ -2546,14 +2530,10 @@ namespace MediaBrowser.Controller.MediaEncoding { state.VideoType = mediaSource.VideoType.Value; - if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd) + if (mediaSource.VideoType.Value == VideoType.Dvd) { state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, mediaSource.VideoType.Value).Select(Path.GetFileName).ToArray(); } - else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.BluRay) - { - state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.BluRay).Select(Path.GetFileName).ToArray(); - } else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.Dvd) { state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.Dvd).Select(Path.GetFileName).ToArray(); diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 17d6dc5d27..5c070122d0 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -61,9 +62,9 @@ namespace MediaBrowser.Controller.MediaEncoding /// /// Extracts the video image. /// - Task ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); + Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); - Task ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken); + Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken); /// /// Extracts the video images on interval. @@ -71,7 +72,7 @@ namespace MediaBrowser.Controller.MediaEncoding Task ExtractVideoImagesOnInterval(string[] inputFiles, string container, MediaStream videoStream, - MediaProtocol protocol, + MediaSourceInfo mediaSource, Video3DFormat? threedFormat, TimeSpan interval, string targetDirectory, @@ -91,9 +92,9 @@ namespace MediaBrowser.Controller.MediaEncoding /// Gets the input argument. /// /// The input files. - /// The protocol. + /// The mediaSource. /// System.String. - string GetInputArgument(IReadOnlyList inputFiles, MediaProtocol protocol); + string GetInputArgument(IReadOnlyList inputFiles, MediaSourceInfo mediaSource); /// /// Gets the time parameter. diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs index ce53c23ad2..df2d2fa57b 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs @@ -18,19 +18,13 @@ namespace MediaBrowser.Controller.MediaEncoding /// /// The file system. /// The video path. - /// The iso mount. /// The playable stream file names. /// string[]. - public static string[] GetInputArgument(IFileSystem fileSystem, string videoPath, IIsoMount isoMount, IReadOnlyCollection playableStreamFileNames) + public static string[] GetInputArgument(IFileSystem fileSystem, string videoPath, IReadOnlyCollection playableStreamFileNames) { if (playableStreamFileNames.Count > 0) { - if (isoMount == null) - { - return GetPlayableStreamFiles(fileSystem, videoPath, playableStreamFileNames); - } - - return GetPlayableStreamFiles(fileSystem, isoMount.MountedPath, playableStreamFileNames); + return GetPlayableStreamFiles(fileSystem, videoPath, playableStreamFileNames); } return new[] { videoPath }; diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index 21b5d0c5be..466fd75e15 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -87,19 +87,19 @@ namespace MediaBrowser.MediaEncoding.Attachments MediaAttachment mediaAttachment, CancellationToken cancellationToken) { - var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource.Protocol, mediaAttachment, cancellationToken).ConfigureAwait(false); + var attachmentPath = await GetReadableFile(mediaSource.Path, mediaSource.Path, mediaSource, mediaAttachment, cancellationToken).ConfigureAwait(false); return File.OpenRead(attachmentPath); } private async Task GetReadableFile( string mediaPath, string inputFile, - MediaProtocol protocol, + MediaSourceInfo mediaSource, MediaAttachment mediaAttachment, CancellationToken cancellationToken) { - var outputPath = GetAttachmentCachePath(mediaPath, protocol, mediaAttachment.Index); - await ExtractAttachment(inputFile, protocol, mediaAttachment.Index, outputPath, cancellationToken) + var outputPath = GetAttachmentCachePath(mediaPath, mediaSource, mediaAttachment.Index); + await ExtractAttachment(inputFile, mediaSource, mediaAttachment.Index, outputPath, cancellationToken) .ConfigureAwait(false); return outputPath; @@ -107,7 +107,7 @@ namespace MediaBrowser.MediaEncoding.Attachments private async Task ExtractAttachment( string inputFile, - MediaProtocol protocol, + MediaSourceInfo mediaSource, int attachmentStreamIndex, string outputPath, CancellationToken cancellationToken) @@ -121,7 +121,7 @@ namespace MediaBrowser.MediaEncoding.Attachments if (!File.Exists(outputPath)) { await ExtractAttachmentInternal( - _mediaEncoder.GetInputArgument(new[] { inputFile }, protocol), + _mediaEncoder.GetInputArgument(new[] { inputFile }, mediaSource), attachmentStreamIndex, outputPath, cancellationToken).ConfigureAwait(false); @@ -234,10 +234,10 @@ namespace MediaBrowser.MediaEncoding.Attachments } } - private string GetAttachmentCachePath(string mediaPath, MediaProtocol protocol, int attachmentStreamIndex) + private string GetAttachmentCachePath(string mediaPath, MediaSourceInfo mediaSource, int attachmentStreamIndex) { string filename; - if (protocol == MediaProtocol.File) + if (mediaSource.Protocol == MediaProtocol.File) { var date = _fileSystem.GetLastWriteTimeUtc(mediaPath); filename = (mediaPath + attachmentStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture)).GetMD5().ToString("D", CultureInfo.InvariantCulture); diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs index 63310fdf6b..b1fcba2d1e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs @@ -10,7 +10,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { public static class EncodingUtils { - public static string GetInputArgument(IReadOnlyList inputFiles, MediaProtocol protocol) + public static string GetInputArgument(string inputPrefix, IReadOnlyList inputFiles, MediaProtocol protocol) { if (protocol != MediaProtocol.File) { @@ -19,15 +19,16 @@ namespace MediaBrowser.MediaEncoding.Encoder return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", url); } - return GetConcatInputArgument(inputFiles); + return GetConcatInputArgument(inputFiles, inputPrefix); } /// /// Gets the concat input argument. /// /// The input files. + /// The input prefix. /// System.String. - private static string GetConcatInputArgument(IReadOnlyList inputFiles) + private static string GetConcatInputArgument(IReadOnlyList inputFiles, string inputPrefix) { // Get all streams // If there's more than one we'll need to use the concat command @@ -39,15 +40,16 @@ namespace MediaBrowser.MediaEncoding.Encoder } // Determine the input path for video files - return GetFileInputArgument(inputFiles[0]); + return GetFileInputArgument(inputFiles[0], inputPrefix); } /// /// Gets the file input argument. /// /// The path. + /// The path prefix. /// System.String. - private static string GetFileInputArgument(string path) + private static string GetFileInputArgument(string path, string inputPrefix) { if (path.IndexOf("://", StringComparison.Ordinal) != -1) { @@ -57,7 +59,7 @@ namespace MediaBrowser.MediaEncoding.Encoder // Quotes are valid path characters in linux and they need to be escaped here with a leading \ path = NormalizePath(path); - return string.Format(CultureInfo.InvariantCulture, "file:\"{0}\"", path); + return string.Format(CultureInfo.InvariantCulture, "{1}:\"{0}\"", path, inputPrefix); } /// diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 5a3a9185d7..edf83c8161 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -18,6 +18,7 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.MediaEncoding.Probing; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; @@ -319,7 +320,7 @@ namespace MediaBrowser.MediaEncoding.Encoder { var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters; - var inputFiles = MediaEncoderHelpers.GetInputArgument(_fileSystem, request.MediaSource.Path, request.MountedIso, request.PlayableStreamFileNames); + var inputFiles = MediaEncoderHelpers.GetInputArgument(_fileSystem, request.MediaSource.Path, request.PlayableStreamFileNames); var probeSize = EncodingHelper.GetProbeSizeArgument(inputFiles.Length); string analyzeDuration; @@ -340,7 +341,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var forceEnableLogging = request.MediaSource.Protocol != MediaProtocol.File; return GetMediaInfoInternal( - GetInputArgument(inputFiles, request.MediaSource.Protocol), + GetInputArgument(inputFiles, request.MediaSource), request.MediaSource.Path, request.MediaSource.Protocol, extractChapters, @@ -355,11 +356,19 @@ namespace MediaBrowser.MediaEncoding.Encoder /// Gets the input argument. /// /// The input files. - /// The protocol. + /// The mediaSource. /// System.String. /// Unrecognized InputType. - public string GetInputArgument(IReadOnlyList inputFiles, MediaProtocol protocol) - => EncodingUtils.GetInputArgument(inputFiles, protocol); + public string GetInputArgument(IReadOnlyList inputFiles, MediaSourceInfo mediaSource) + { + var prefix = "file"; + if (mediaSource.VideoType == VideoType.BluRay || mediaSource.VideoType == VideoType.Iso) + { + prefix = "bluray"; + } + + return EncodingUtils.GetInputArgument(prefix, inputFiles, mediaSource.Protocol); + } /// /// Gets the media info internal. @@ -457,17 +466,22 @@ namespace MediaBrowser.MediaEncoding.Encoder public Task ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken) { - return ExtractImage(new[] { path }, null, null, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken); + var mediaSource = new MediaSourceInfo + { + Protocol = MediaProtocol.File + }; + + return ExtractImage(new[] { path }, null, null, imageStreamIndex, mediaSource, true, null, null, cancellationToken); } - public Task ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) + public Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) { - return ExtractImage(inputFiles, container, videoStream, null, protocol, false, threedFormat, offset, cancellationToken); + return ExtractImage(inputFiles, container, videoStream, null, mediaSource, false, threedFormat, offset, cancellationToken); } - public Task ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken) + public Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken) { - return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, protocol, false, null, null, cancellationToken); + return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, mediaSource, false, null, null, cancellationToken); } private async Task ExtractImage( @@ -475,13 +489,13 @@ namespace MediaBrowser.MediaEncoding.Encoder string container, MediaStream videoStream, int? imageStreamIndex, - MediaProtocol protocol, + MediaSourceInfo mediaSource, bool isAudio, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) { - var inputArgument = GetInputArgument(inputFiles, protocol); + var inputArgument = GetInputArgument(inputFiles, mediaSource); if (isAudio) { @@ -671,7 +685,7 @@ namespace MediaBrowser.MediaEncoding.Encoder string[] inputFiles, string container, MediaStream videoStream, - MediaProtocol protocol, + MediaSourceInfo mediaSource, Video3DFormat? threedFormat, TimeSpan interval, string targetDirectory, @@ -679,7 +693,7 @@ namespace MediaBrowser.MediaEncoding.Encoder int? maxWidth, CancellationToken cancellationToken) { - var inputArgument = GetInputArgument(inputFiles, protocol); + var inputArgument = GetInputArgument(inputFiles, mediaSource); var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(_usCulture); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 0a9958b9eb..4fa145d962 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -187,7 +187,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path); } - var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, protocol, subtitleStream, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); var stream = await GetSubtitleStream(fileInfo.Path, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false); @@ -221,7 +221,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles private async Task GetReadableFile( string mediaPath, string[] inputFiles, - MediaProtocol protocol, + MediaSourceInfo mediaSource, MediaStream subtitleStream, CancellationToken cancellationToken) { @@ -252,9 +252,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles } // Extract - var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat); + var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, "." + outputFormat); - await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken) + await ExtractTextSubtitle(inputFiles, mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken) .ConfigureAwait(false); return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false); @@ -266,14 +266,14 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (GetReader(currentFormat, false) == null) { // Convert - var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt"); + var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, ".srt"); - await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false); + await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false); return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true); } - return new SubtitleInfo(subtitleStream.Path, protocol, currentFormat, true); + return new SubtitleInfo(subtitleStream.Path, mediaSource.Protocol, currentFormat, true); } private ISubtitleParser GetReader(string format, bool throwIfMissing) @@ -363,11 +363,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// /// The input path. /// The language. - /// The input protocol. + /// The input mediaSource. /// The output path. /// The cancellation token. /// Task. - private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken) + private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken) { var semaphore = GetLock(outputPath); @@ -377,7 +377,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { if (!File.Exists(outputPath)) { - await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false); + await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false); } } finally @@ -391,14 +391,14 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// /// The input path. /// The language. - /// The input protocol. + /// The input mediaSource. /// The output path. /// The cancellation token. /// Task. /// /// The inputPath or outputPath is null. /// - private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken) + private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(inputPath)) { @@ -412,7 +412,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); - var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false); + var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false); // FFmpeg automatically convert character encoding when it is UTF-16 // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event" @@ -516,7 +516,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Extracts the text subtitle. /// /// The input files. - /// The protocol. + /// The mediaSource. /// Index of the subtitle stream. /// The output codec. /// The output path. @@ -525,7 +525,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Must use inputPath list overload. private async Task ExtractTextSubtitle( string[] inputFiles, - MediaProtocol protocol, + MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputCodec, string outputPath, @@ -540,7 +540,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!File.Exists(outputPath)) { await ExtractTextSubtitleInternal( - _mediaEncoder.GetInputArgument(inputFiles, protocol), + _mediaEncoder.GetInputArgument(inputFiles, mediaSource), subtitleStreamIndex, outputCodec, outputPath, @@ -706,9 +706,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension) + private string GetSubtitleCachePath(string mediaPath, MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension) { - if (protocol == MediaProtocol.File) + if (mediaSource.Protocol == MediaProtocol.File) { var ticksParam = string.Empty; diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index c61187fdf6..648329757f 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -150,11 +150,6 @@ namespace MediaBrowser.Providers.MediaInfo public Task FetchVideoInfo(T item, MetadataRefreshOptions options, CancellationToken cancellationToken) where T : Video { - if (item.VideoType == VideoType.Iso) - { - return _cachedTask; - } - if (item.IsPlaceHolder) { return _cachedTask; diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index fc38d3832a..9ef393ec20 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -9,6 +9,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; @@ -50,7 +51,7 @@ namespace MediaBrowser.Providers.MediaInfo } // No support for this - if (video.VideoType == VideoType.Iso || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay) + if (video.VideoType == VideoType.Dvd) { return Task.FromResult(new DynamicImageResponse { HasImage = false }); } @@ -72,7 +73,6 @@ namespace MediaBrowser.Providers.MediaInfo var inputPath = MediaEncoderHelpers.GetInputArgument( _fileSystem, item.Path, - null, item.GetPlayableStreamFileNames()); var mediaStreams = @@ -107,7 +107,14 @@ namespace MediaBrowser.Providers.MediaInfo } } - extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, imageStream, videoIndex, cancellationToken).ConfigureAwait(false); + MediaSourceInfo mediaSource = new MediaSourceInfo + { + VideoType = item.VideoType, + IsoType = item.IsoType, + Protocol = item.PathProtocol.Value, + }; + + extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, mediaSource, imageStream, videoIndex, cancellationToken).ConfigureAwait(false); } else { @@ -119,8 +126,14 @@ namespace MediaBrowser.Providers.MediaInfo : TimeSpan.FromSeconds(10); var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); + var mediaSource = new MediaSourceInfo + { + VideoType = item.VideoType, + IsoType = item.IsoType, + Protocol = item.PathProtocol.Value, + }; - extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, protocol, videoStream, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false); + extractedImagePath = await _mediaEncoder.ExtractVideoImage(inputPath, item.Container, mediaSource, videoStream, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false); } return new DynamicImageResponse From cd4641dca02bae552cc7ea1942b0efbd4b791bcb Mon Sep 17 00:00:00 2001 From: Stanislav Ionascu Date: Thu, 1 Oct 2020 22:20:28 +0200 Subject: [PATCH 0051/1930] Remove PlayableStreamFileNames as unused Since ffmpeg can play and transcode ISO files and BDMV folders directly, there's no use of that property. --- .../MediaEncoder/EncodingManager.cs | 2 +- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 5 -- MediaBrowser.Controller/Entities/Video.cs | 45 ---------------- .../MediaEncoding/EncodingHelper.cs | 34 +------------ .../MediaEncoding/EncodingJobInfo.cs | 5 -- .../MediaEncoding/IMediaEncoder.cs | 10 ++-- .../MediaEncoding/MediaEncoderHelpers.cs | 27 ---------- .../MediaEncoding/MediaInfoRequest.cs | 11 ---- .../Attachments/AttachmentExtractor.cs | 2 +- .../Encoder/EncodingUtils.cs | 23 +++------ .../Encoder/MediaEncoder.cs | 51 ++++++++----------- .../Subtitles/SubtitleEncoder.cs | 25 +++------ .../MediaInfo/FFProbeVideoInfo.cs | 4 +- .../MediaInfo/VideoImageProvider.cs | 5 +- 14 files changed, 44 insertions(+), 205 deletions(-) diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index 791d009637..f27305cbed 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.MediaEncoder // Add some time for the first chapter to make sure we don't end up with a black image var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(_firstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks); - var inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, video.Path, Array.Empty()); + var inputPath = video.Path; Directory.CreateDirectory(Path.GetDirectoryName(path)); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 465857b01e..cc9dcd10e1 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -762,11 +762,6 @@ namespace Jellyfin.Api.Helpers private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource) { - if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && state.IsoType == IsoType.Dvd && _isoManager.CanMount(state.MediaPath)) - { - state.IsoMount = await _isoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false); - } - if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId)) { var liveStreamResponse = await _mediaSourceManager.OpenLiveStream( diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 07f3818811..6320b01b87 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -143,26 +143,6 @@ namespace MediaBrowser.Controller.Entities /// The video3 D format. public Video3DFormat? Video3DFormat { get; set; } - public string[] GetPlayableStreamFileNames() - { - var videoType = VideoType; - - if (videoType == VideoType.Iso && IsoType == Model.Entities.IsoType.BluRay) - { - videoType = VideoType.BluRay; - } - else if (videoType == VideoType.Iso && IsoType == Model.Entities.IsoType.Dvd) - { - videoType = VideoType.Dvd; - } - else - { - return Array.Empty(); - } - - throw new NotImplementedException(); - } - /// /// Gets or sets the aspect ratio. /// @@ -415,31 +395,6 @@ namespace MediaBrowser.Controller.Entities return updateType; } - public static string[] QueryPlayableStreamFiles(string rootPath, VideoType videoType) - { - if (videoType == VideoType.Dvd) - { - return FileSystem.GetFiles(rootPath, new[] { ".vob" }, false, true) - .OrderByDescending(i => i.Length) - .ThenBy(i => i.FullName) - .Take(1) - .Select(i => i.FullName) - .ToArray(); - } - - if (videoType == VideoType.BluRay) - { - return FileSystem.GetFiles(rootPath, new[] { ".m2ts" }, false, true) - .OrderByDescending(i => i.Length) - .ThenBy(i => i.FullName) - .Take(1) - .Select(i => i.FullName) - .ToArray(); - } - - return Array.Empty(); - } - /// /// Gets a value indicating whether [is3 D]. /// diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 7481cc7b96..cf9bf0b5e8 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2323,18 +2323,10 @@ namespace MediaBrowser.Controller.MediaEncoding } } - public string GetProbeSizeArgument(int numInputFiles) - => numInputFiles > 1 ? "-probesize " + _configuration.GetFFmpegProbeSize() : string.Empty; - - public string GetAnalyzeDurationArgument(int numInputFiles) - => numInputFiles > 1 ? "-analyzeduration " + _configuration.GetFFmpegAnalyzeDuration() : string.Empty; - public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions) { var inputModifier = string.Empty; - - var numInputFiles = state.PlayableStreamFileNames.Length > 0 ? state.PlayableStreamFileNames.Length : 1; - var probeSizeArgument = GetProbeSizeArgument(numInputFiles); + var probeSizeArgument = string.Empty; string analyzeDurationArgument; if (state.MediaSource.AnalyzeDurationMs.HasValue) @@ -2343,7 +2335,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else { - analyzeDurationArgument = GetAnalyzeDurationArgument(numInputFiles); + analyzeDurationArgument = string.Empty; } if (!string.IsNullOrEmpty(probeSizeArgument)) @@ -2526,28 +2518,6 @@ namespace MediaBrowser.Controller.MediaEncoding state.IsoType = mediaSource.IsoType; - if (mediaSource.VideoType.HasValue) - { - state.VideoType = mediaSource.VideoType.Value; - - if (mediaSource.VideoType.Value == VideoType.Dvd) - { - state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, mediaSource.VideoType.Value).Select(Path.GetFileName).ToArray(); - } - else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.Dvd) - { - state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.Dvd).Select(Path.GetFileName).ToArray(); - } - else - { - state.PlayableStreamFileNames = Array.Empty(); - } - } - else - { - state.PlayableStreamFileNames = Array.Empty(); - } - if (mediaSource.Timestamp.HasValue) { state.InputTimestamp = mediaSource.Timestamp.Value; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index c7ec878d2d..c93822f0b5 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -33,10 +33,6 @@ namespace MediaBrowser.Controller.MediaEncoding public bool IsInputVideo { get; set; } - public IIsoMount IsoMount { get; set; } - - public string[] PlayableStreamFileNames { get; set; } - public string OutputAudioCodec { get; set; } public int? OutputVideoBitrate { get; set; } @@ -308,7 +304,6 @@ namespace MediaBrowser.Controller.MediaEncoding { TranscodingType = jobType; RemoteHttpHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - PlayableStreamFileNames = Array.Empty(); SupportedAudioCodecs = Array.Empty(); SupportedVideoCodecs = Array.Empty(); SupportedSubtitleCodecs = Array.Empty(); diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 5c070122d0..2560d0e31d 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -62,14 +62,14 @@ namespace MediaBrowser.Controller.MediaEncoding /// /// Extracts the video image. /// - Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); + Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); - Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken); + Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken); /// /// Extracts the video images on interval. /// - Task ExtractVideoImagesOnInterval(string[] inputFiles, + Task ExtractVideoImagesOnInterval(string inputFile, string container, MediaStream videoStream, MediaSourceInfo mediaSource, @@ -91,10 +91,10 @@ namespace MediaBrowser.Controller.MediaEncoding /// /// Gets the input argument. /// - /// The input files. + /// The input file. /// The mediaSource. /// System.String. - string GetInputArgument(IReadOnlyList inputFiles, MediaSourceInfo mediaSource); + string GetInputArgument(string inputFile, MediaSourceInfo mediaSource); /// /// Gets the time parameter. diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs index df2d2fa57b..281d503721 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs @@ -13,32 +13,5 @@ namespace MediaBrowser.Controller.MediaEncoding /// public static class MediaEncoderHelpers { - /// - /// Gets the input argument. - /// - /// The file system. - /// The video path. - /// The playable stream file names. - /// string[]. - public static string[] GetInputArgument(IFileSystem fileSystem, string videoPath, IReadOnlyCollection playableStreamFileNames) - { - if (playableStreamFileNames.Count > 0) - { - return GetPlayableStreamFiles(fileSystem, videoPath, playableStreamFileNames); - } - - return new[] { videoPath }; - } - - private static string[] GetPlayableStreamFiles(IFileSystem fileSystem, string rootPath, IEnumerable filenames) - { - var allFiles = fileSystem - .GetFilePaths(rootPath, true) - .ToArray(); - - return filenames.Select(name => allFiles.FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase))) - .Where(f => !string.IsNullOrEmpty(f)) - .ToArray(); - } } } diff --git a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs index 59729de49c..2cb04bdc4f 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs @@ -1,9 +1,7 @@ #pragma warning disable CS1591 -using System; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.MediaEncoding { @@ -14,14 +12,5 @@ namespace MediaBrowser.Controller.MediaEncoding public bool ExtractChapters { get; set; } public DlnaProfileType MediaType { get; set; } - - public IIsoMount MountedIso { get; set; } - - public string[] PlayableStreamFileNames { get; set; } - - public MediaInfoRequest() - { - PlayableStreamFileNames = Array.Empty(); - } } } diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index 466fd75e15..c4a2d7779a 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -121,7 +121,7 @@ namespace MediaBrowser.MediaEncoding.Attachments if (!File.Exists(outputPath)) { await ExtractAttachmentInternal( - _mediaEncoder.GetInputArgument(new[] { inputFile }, mediaSource), + _mediaEncoder.GetInputArgument(inputFile, mediaSource), attachmentStreamIndex, outputPath, cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs index b1fcba2d1e..d0ea0429b5 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs @@ -1,46 +1,35 @@ #pragma warning disable CS1591 using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.MediaEncoding.Encoder { public static class EncodingUtils { - public static string GetInputArgument(string inputPrefix, IReadOnlyList inputFiles, MediaProtocol protocol) + public static string GetInputArgument(string inputPrefix, string inputFile, MediaProtocol protocol) { if (protocol != MediaProtocol.File) { - var url = inputFiles[0]; - - return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", url); + return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", inputFile); } - return GetConcatInputArgument(inputFiles, inputPrefix); + return GetConcatInputArgument(inputFile, inputPrefix); } /// /// Gets the concat input argument. /// - /// The input files. + /// The input file. /// The input prefix. /// System.String. - private static string GetConcatInputArgument(IReadOnlyList inputFiles, string inputPrefix) + private static string GetConcatInputArgument(string inputFile, string inputPrefix) { // Get all streams // If there's more than one we'll need to use the concat command - if (inputFiles.Count > 1) - { - var files = string.Join("|", inputFiles.Select(NormalizePath)); - - return string.Format(CultureInfo.InvariantCulture, "concat:\"{0}\"", files); - } - // Determine the input path for video files - return GetFileInputArgument(inputFiles[0], inputPrefix); + return GetFileInputArgument(inputFile, inputPrefix); } /// diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index edf83c8161..3657f7e311 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -83,8 +83,6 @@ namespace MediaBrowser.MediaEncoding.Encoder _jsonSerializerOptions = JsonDefaults.GetOptions(); } - private EncodingHelper EncodingHelper => _encodingHelperFactory.Value; - /// public string EncoderPath => _ffmpegPath; @@ -319,33 +317,24 @@ namespace MediaBrowser.MediaEncoding.Encoder public Task GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken) { var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters; + var inputFile = request.MediaSource.Path; - var inputFiles = MediaEncoderHelpers.GetInputArgument(_fileSystem, request.MediaSource.Path, request.PlayableStreamFileNames); - - var probeSize = EncodingHelper.GetProbeSizeArgument(inputFiles.Length); - string analyzeDuration; + string analyzeDuration = string.Empty; if (request.MediaSource.AnalyzeDurationMs > 0) { analyzeDuration = "-analyzeduration " + (request.MediaSource.AnalyzeDurationMs * 1000).ToString(); } - else - { - analyzeDuration = EncodingHelper.GetAnalyzeDurationArgument(inputFiles.Length); - } - - probeSize = probeSize + " " + analyzeDuration; - probeSize = probeSize.Trim(); var forceEnableLogging = request.MediaSource.Protocol != MediaProtocol.File; return GetMediaInfoInternal( - GetInputArgument(inputFiles, request.MediaSource), + GetInputArgument(inputFile, request.MediaSource), request.MediaSource.Path, request.MediaSource.Protocol, extractChapters, - probeSize, + analyzeDuration, request.MediaType == DlnaProfileType.Audio, request.MediaSource.VideoType, forceEnableLogging, @@ -355,11 +344,11 @@ namespace MediaBrowser.MediaEncoding.Encoder /// /// Gets the input argument. /// - /// The input files. + /// The input file. /// The mediaSource. /// System.String. /// Unrecognized InputType. - public string GetInputArgument(IReadOnlyList inputFiles, MediaSourceInfo mediaSource) + public string GetInputArgument(string inputFile, MediaSourceInfo mediaSource) { var prefix = "file"; if (mediaSource.VideoType == VideoType.BluRay || mediaSource.VideoType == VideoType.Iso) @@ -367,7 +356,7 @@ namespace MediaBrowser.MediaEncoding.Encoder prefix = "bluray"; } - return EncodingUtils.GetInputArgument(prefix, inputFiles, mediaSource.Protocol); + return EncodingUtils.GetInputArgument(prefix, inputFile, mediaSource.Protocol); } /// @@ -471,21 +460,21 @@ namespace MediaBrowser.MediaEncoding.Encoder Protocol = MediaProtocol.File }; - return ExtractImage(new[] { path }, null, null, imageStreamIndex, mediaSource, true, null, null, cancellationToken); + return ExtractImage(path, null, null, imageStreamIndex, mediaSource, true, null, null, cancellationToken); } - public Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) + public Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) { - return ExtractImage(inputFiles, container, videoStream, null, mediaSource, false, threedFormat, offset, cancellationToken); + return ExtractImage(inputFile, container, videoStream, null, mediaSource, false, threedFormat, offset, cancellationToken); } - public Task ExtractVideoImage(string[] inputFiles, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken) + public Task ExtractVideoImage(string inputFile, string container, MediaSourceInfo mediaSource, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken) { - return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, mediaSource, false, null, null, cancellationToken); + return ExtractImage(inputFile, container, imageStream, imageStreamIndex, mediaSource, false, null, null, cancellationToken); } private async Task ExtractImage( - string[] inputFiles, + string inputFile, string container, MediaStream videoStream, int? imageStreamIndex, @@ -495,7 +484,7 @@ namespace MediaBrowser.MediaEncoding.Encoder TimeSpan? offset, CancellationToken cancellationToken) { - var inputArgument = GetInputArgument(inputFiles, mediaSource); + var inputArgument = GetInputArgument(inputFile, mediaSource); if (isAudio) { @@ -572,8 +561,8 @@ namespace MediaBrowser.MediaEncoding.Encoder var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) : string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg); - var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); - var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); + var probeSizeArgument = string.Empty; + var analyzeDurationArgument = string.Empty; if (!string.IsNullOrWhiteSpace(probeSizeArgument)) { @@ -682,7 +671,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } public async Task ExtractVideoImagesOnInterval( - string[] inputFiles, + string inputFile, string container, MediaStream videoStream, MediaSourceInfo mediaSource, @@ -693,7 +682,7 @@ namespace MediaBrowser.MediaEncoding.Encoder int? maxWidth, CancellationToken cancellationToken) { - var inputArgument = GetInputArgument(inputFiles, mediaSource); + var inputArgument = GetInputArgument(inputFile, mediaSource); var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(_usCulture); @@ -709,8 +698,8 @@ namespace MediaBrowser.MediaEncoding.Encoder var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf); - var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); - var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); + var probeSizeArgument = string.Empty; + var analyzeDurationArgument = string.Empty; if (!string.IsNullOrWhiteSpace(probeSizeArgument)) { diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 4fa145d962..ed6c568c57 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -168,18 +168,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles MediaStream subtitleStream, CancellationToken cancellationToken) { - string[] inputFiles; - - if (mediaSource.VideoType.HasValue - && (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)) - { - var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id)); - inputFiles = mediaSourceItem.GetPlayableStreamFileNames(); - } - else - { - inputFiles = new[] { mediaSource.Path }; - } + var inputFile = mediaSource.Path; var protocol = mediaSource.Protocol; if (subtitleStream.IsExternal) @@ -187,7 +176,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path); } - var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetReadableFile(mediaSource.Path, inputFile, mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); var stream = await GetSubtitleStream(fileInfo.Path, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false); @@ -220,7 +209,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles private async Task GetReadableFile( string mediaPath, - string[] inputFiles, + string inputFile, MediaSourceInfo mediaSource, MediaStream subtitleStream, CancellationToken cancellationToken) @@ -254,7 +243,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles // Extract var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, "." + outputFormat); - await ExtractTextSubtitle(inputFiles, mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken) + await ExtractTextSubtitle(inputFile, mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken) .ConfigureAwait(false); return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false); @@ -515,7 +504,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// /// Extracts the text subtitle. /// - /// The input files. + /// The input file. /// The mediaSource. /// Index of the subtitle stream. /// The output codec. @@ -524,7 +513,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Task. /// Must use inputPath list overload. private async Task ExtractTextSubtitle( - string[] inputFiles, + string inputFile, MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputCodec, @@ -540,7 +529,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!File.Exists(outputPath)) { await ExtractTextSubtitleInternal( - _mediaEncoder.GetInputArgument(inputFiles, mediaSource), + _mediaEncoder.GetInputArgument(inputFile, mediaSource), subtitleStreamIndex, outputCodec, outputPath, diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 776dee7802..6d39c091ef 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -116,7 +116,7 @@ namespace MediaBrowser.Providers.MediaInfo streamFileNames = Array.Empty(); } - mediaInfoResult = await GetMediaInfo(item, streamFileNames, cancellationToken).ConfigureAwait(false); + mediaInfoResult = await GetMediaInfo(item, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } @@ -128,7 +128,6 @@ namespace MediaBrowser.Providers.MediaInfo private Task GetMediaInfo( Video item, - string[] streamFileNames, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -145,7 +144,6 @@ namespace MediaBrowser.Providers.MediaInfo return _mediaEncoder.GetMediaInfo( new MediaInfoRequest { - PlayableStreamFileNames = streamFileNames, ExtractChapters = true, MediaType = DlnaProfileType.Video, MediaSource = new MediaSourceInfo diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index 9ef393ec20..c36c3af6a7 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -70,10 +70,7 @@ namespace MediaBrowser.Providers.MediaInfo { var protocol = item.PathProtocol ?? MediaProtocol.File; - var inputPath = MediaEncoderHelpers.GetInputArgument( - _fileSystem, - item.Path, - item.GetPlayableStreamFileNames()); + var inputPath = item.Path; var mediaStreams = item.GetMediaStreams(); From 8f2fbf7a99c5f67daf2a1589fa12b1287a076bed Mon Sep 17 00:00:00 2001 From: Gary Wilber Date: Thu, 1 Oct 2020 16:24:35 -0700 Subject: [PATCH 0052/1930] Switch to TPL dataflow for subfolder scan --- .../ApplicationHost.cs | 1 - MediaBrowser.Controller/Entities/Folder.cs | 173 +++++++++++------- .../Library/TaskMethods.cs | 133 -------------- .../MediaBrowser.Controller.csproj | 3 +- 4 files changed, 106 insertions(+), 204 deletions(-) delete mode 100644 MediaBrowser.Controller/Library/TaskMethods.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 6d7239f724..7a46fdf2e7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -758,7 +758,6 @@ namespace Emby.Server.Implementations BaseItem.FileSystem = _fileSystemManager; BaseItem.UserDataManager = Resolve(); BaseItem.ChannelManager = Resolve(); - TaskMethods.ConfigurationManager = ServerConfigurationManager; Video.LiveTvManager = Resolve(); Folder.UserViewManager = Resolve(); UserView.TVSeriesManager = Resolve(); diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 666455cff4..8cea8755cb 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Progress; @@ -35,45 +36,16 @@ namespace MediaBrowser.Controller.Entities /// public class Folder : BaseItem { - /// - /// Contains constants used when reporting scan progress. - /// - private static class ProgressHelpers - { - /// - /// Reported after the folders immediate children are retrieved. - /// - public const int RetrievedChildren = 5; + private static Lazy _metadataRefreshThrottler = new Lazy(() => { + var concurrency = ConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency; - /// - /// Reported after add, updating, or deleting child items from the LibraryManager. - /// - public const int UpdatedChildItems = 10; - - /// - /// Reported once subfolders are scanned. - /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders]. - /// - public const int ScannedSubfolders = 50; - - /// - /// Reported once metadata is refreshed. - /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed]. - /// - public const int RefreshedMetadata = 100; - - /// - /// Gets the current progress given the previous step, next step, and progress in between. - /// - /// The previous progress step. - /// The next progress step. - /// The current progress step. - /// The progress. - public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress) + if (concurrency <= 0) { - return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100)); + concurrency = Environment.ProcessorCount; } - } + + return new SemaphoreSlim(concurrency); + }); public static IUserViewManager UserViewManager { get; set; } @@ -508,19 +480,17 @@ namespace MediaBrowser.Controller.Entities private Task RefreshMetadataRecursive(IList children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress progress, CancellationToken cancellationToken) { - var progressableTasks = children - .Select, Task>>(child => - innerProgress => RefreshChildMetadata(child, refreshOptions, recursive && child.IsFolder, innerProgress, cancellationToken)) - .ToList(); - - return RunTasks(progressableTasks, progress, cancellationToken); + return RunTasks( + (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken), + children, + progress, + cancellationToken); } private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress progress, CancellationToken cancellationToken) { // limit the amount of concurrent metadata refreshes - await TaskMethods.RunThrottled( - TaskMethods.SharedThrottleId.RefreshMetadata, + await RunMetadataRefresh( async () => { var series = container as Series; @@ -547,8 +517,7 @@ namespace MediaBrowser.Controller.Entities if (refreshOptions.RefreshItem(child)) { // limit the amount of concurrent metadata refreshes - await TaskMethods.RunThrottled( - TaskMethods.SharedThrottleId.RefreshMetadata, + await RunMetadataRefresh( async () => await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); } @@ -570,38 +539,33 @@ namespace MediaBrowser.Controller.Entities /// Task. private Task ValidateSubFolders(IList children, IDirectoryService directoryService, IProgress progress, CancellationToken cancellationToken) { - var progressableTasks = children - .Select, Task>>(child => - innerProgress => child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)) - .ToList(); - - return RunTasks(progressableTasks, progress, cancellationToken); + return RunTasks( + (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService), + children, + progress, + cancellationToken); } /// - /// Runs a set of tasks concurrently with progress. + /// Runs an action block on a list of children. /// - /// A list of tasks. + /// The task to run for each child. + /// The list of children. /// The progress. /// The cancellation token. /// Task. - private async Task RunTasks(IList, Task>> tasks, IProgress progress, CancellationToken cancellationToken) + private async Task RunTasks(Func, Task> task, IList children, IProgress progress, CancellationToken cancellationToken) { - var childrenCount = tasks.Count; + var childrenCount = children.Count; var childrenProgress = new double[childrenCount]; - var actions = new Func[childrenCount]; void UpdateProgress() { progress.Report(childrenProgress.Average()); } - for (var i = 0; i < childrenCount; i++) - { - var childIndex = i; - var child = tasks[childIndex]; - - actions[childIndex] = async () => + var actionBlock = new ActionBlock( + async i => { var innerProgress = new ActionableProgress(); @@ -609,22 +573,33 @@ namespace MediaBrowser.Controller.Entities { // round the percent and only update progress if it changed to prevent excessive UpdateProgress calls var innerPercentRounded = Math.Round(innerPercent); - if (childrenProgress[childIndex] != innerPercentRounded) + if (childrenProgress[i] != innerPercentRounded) { - childrenProgress[childIndex] = innerPercentRounded; + childrenProgress[i] = innerPercentRounded; UpdateProgress(); } }); - await tasks[childIndex](innerProgress).ConfigureAwait(false); + await task(children[i], innerProgress).ConfigureAwait(false); - childrenProgress[childIndex] = 100; + childrenProgress[i] = 100; UpdateProgress(); - }; + }, + new ExecutionDataflowBlockOptions + { + MaxDegreeOfParallelism = ConfigurationManager.Configuration.LibraryScanFanoutConcurrency, + CancellationToken = cancellationToken, + }); + + for (var i = 0; i < childrenCount; i++) + { + actionBlock.Post(i); } - await TaskMethods.WhenAllThrottled(TaskMethods.SharedThrottleId.ScanFanout, actions, cancellationToken).ConfigureAwait(false); + actionBlock.Complete(); + + await actionBlock.Completion.ConfigureAwait(false); } /// @@ -1272,6 +1247,26 @@ namespace MediaBrowser.Controller.Entities return true; } + /// + /// Runs multiple metadata refreshes concurrently. + /// + /// The action to run. + /// The cancellation token. + /// A representing the result of the asynchronous operation. + private static async Task RunMetadataRefresh(Func action, CancellationToken cancellationToken) + { + await _metadataRefreshThrottler.Value.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + await action().ConfigureAwait(false); + } + finally + { + _metadataRefreshThrottler.Value.Release(); + } + } + public List GetChildren(User user, bool includeLinkedChildren) { if (user == null) @@ -1819,5 +1814,45 @@ namespace MediaBrowser.Controller.Entities } } } + + /// + /// Contains constants used when reporting scan progress. + /// + private static class ProgressHelpers + { + /// + /// Reported after the folders immediate children are retrieved. + /// + public const int RetrievedChildren = 5; + + /// + /// Reported after add, updating, or deleting child items from the LibraryManager. + /// + public const int UpdatedChildItems = 10; + + /// + /// Reported once subfolders are scanned. + /// When scanning subfolders, the progress will be between [UpdatedItems, ScannedSubfolders]. + /// + public const int ScannedSubfolders = 50; + + /// + /// Reported once metadata is refreshed. + /// When refreshing metadata, the progress will be between [ScannedSubfolders, MetadataRefreshed]. + /// + public const int RefreshedMetadata = 100; + + /// + /// Gets the current progress given the previous step, next step, and progress in between. + /// + /// The previous progress step. + /// The next progress step. + /// The current progress step. + /// The progress. + public static double GetProgress(int previousProgressStep, int nextProgressStep, double currentProgress) + { + return previousProgressStep + ((nextProgressStep - previousProgressStep) * (currentProgress / 100)); + } + } } } diff --git a/MediaBrowser.Controller/Library/TaskMethods.cs b/MediaBrowser.Controller/Library/TaskMethods.cs deleted file mode 100644 index 66bfbe0d9e..0000000000 --- a/MediaBrowser.Controller/Library/TaskMethods.cs +++ /dev/null @@ -1,133 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller.Configuration; - -namespace MediaBrowser.Controller.Library -{ - /// - /// Helper methods for running tasks concurrently. - /// - public static class TaskMethods - { - private static readonly int _processorCount = Environment.ProcessorCount; - - private static readonly ConcurrentDictionary _sharedThrottlers = new ConcurrentDictionary(); - - /// - /// Throttle id for sharing a concurrency limit. - /// - public enum SharedThrottleId - { - /// - /// Library scan fan out - /// - ScanFanout, - - /// - /// Refresh metadata - /// - RefreshMetadata, - } - - /// - /// Gets or sets the configuration manager. - /// - public static IServerConfigurationManager ConfigurationManager { get; set; } - - /// - /// Similiar to Task.WhenAll but only allows running a certain amount of tasks at the same time. - /// - /// The throttle id. Multiple calls to this method with the same throttle id will share a concurrency limit. - /// List of actions to run. - /// The cancellation token. - /// A representing the result of the asynchronous operation. - public static async Task WhenAllThrottled(SharedThrottleId throttleId, IEnumerable> actions, CancellationToken cancellationToken) - { - var taskThrottler = throttleId == SharedThrottleId.ScanFanout ? - new SemaphoreSlim(GetConcurrencyLimit(throttleId)) : - _sharedThrottlers.GetOrAdd(throttleId, id => new SemaphoreSlim(GetConcurrencyLimit(id))); - - try - { - var tasks = new List(); - - foreach (var action in actions) - { - await taskThrottler.WaitAsync(cancellationToken).ConfigureAwait(false); - - tasks.Add(Task.Run(async () => - { - try - { - await action().ConfigureAwait(false); - } - finally - { - taskThrottler.Release(); - } - })); - } - - await Task.WhenAll(tasks).ConfigureAwait(false); - } - finally - { - if (throttleId == SharedThrottleId.ScanFanout) - { - taskThrottler.Dispose(); - } - } - } - - /// - /// Runs a task within a given throttler. - /// - /// The throttle id. Multiple calls to this method with the same throttle id will share a concurrency limit. - /// The action to run. - /// The cancellation token. - /// A representing the result of the asynchronous operation. - public static async Task RunThrottled(SharedThrottleId throttleId, Func action, CancellationToken cancellationToken) - { - if (throttleId == SharedThrottleId.ScanFanout) - { - // just await the task instead - throw new InvalidOperationException("Invalid throttle id"); - } - - var taskThrottler = _sharedThrottlers.GetOrAdd(throttleId, id => new SemaphoreSlim(GetConcurrencyLimit(id))); - - await taskThrottler.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - await action().ConfigureAwait(false); - } - finally - { - taskThrottler.Release(); - } - } - - /// - /// Get the concurrency limit for the given throttle id. - /// - /// The throttle id. - /// The concurrency limit. - private static int GetConcurrencyLimit(SharedThrottleId throttleId) - { - var concurrency = throttleId == SharedThrottleId.RefreshMetadata ? - ConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency : - ConfigurationManager.Configuration.LibraryScanFanoutConcurrency; - - if (concurrency <= 0) - { - concurrency = _processorCount; - } - - return concurrency; - } - } -} diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 6544704065..243b8cd02b 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -16,7 +16,8 @@ - + + From ac6d51554c7b358980e6ba181a21b54424d64b69 Mon Sep 17 00:00:00 2001 From: Gary Wilber Date: Thu, 1 Oct 2020 16:25:01 -0700 Subject: [PATCH 0053/1930] Fix lastProgressMessageTimes dictionary errors --- .../EntryPoints/LibraryChangedNotifier.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index c9d21d9638..2e9d638ec7 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -43,7 +44,7 @@ namespace Emby.Server.Implementations.EntryPoints private readonly List _itemsAdded = new List(); private readonly List _itemsRemoved = new List(); private readonly List _itemsUpdated = new List(); - private readonly Dictionary _lastProgressMessageTimes = new Dictionary(); + private readonly ConcurrentDictionary _lastProgressMessageTimes = new ConcurrentDictionary(); public LibraryChangedNotifier( ILibraryManager libraryManager, @@ -97,7 +98,7 @@ namespace Emby.Server.Implementations.EntryPoints } } - _lastProgressMessageTimes[item.Id] = DateTime.UtcNow; + _lastProgressMessageTimes.AddOrUpdate(item.Id, key => DateTime.UtcNow, (key, existing) => DateTime.UtcNow); var dict = new Dictionary(); dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture); @@ -139,6 +140,8 @@ namespace Emby.Server.Implementations.EntryPoints private void OnProviderRefreshCompleted(object sender, GenericEventArgs e) { OnProviderRefreshProgress(sender, new GenericEventArgs>(new Tuple(e.Argument, 100))); + + _lastProgressMessageTimes.TryRemove(e.Argument.Id, out DateTime removed); } private static bool EnableRefreshMessage(BaseItem item) From a51adec836ae967a827cdddffc5572ef621b69d3 Mon Sep 17 00:00:00 2001 From: Gary Wilber Date: Fri, 2 Oct 2020 18:26:10 -0700 Subject: [PATCH 0054/1930] fix parallelism when set to 0 --- MediaBrowser.Controller/Entities/Folder.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 8cea8755cb..db59cdc314 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -564,6 +564,9 @@ namespace MediaBrowser.Controller.Entities progress.Report(childrenProgress.Average()); } + var fanoutConcurrency = ConfigurationManager.Configuration.LibraryScanFanoutConcurrency; + var parallelism = fanoutConcurrency == 0 ? Environment.ProcessorCount : fanoutConcurrency; + var actionBlock = new ActionBlock( async i => { @@ -588,7 +591,7 @@ namespace MediaBrowser.Controller.Entities }, new ExecutionDataflowBlockOptions { - MaxDegreeOfParallelism = ConfigurationManager.Configuration.LibraryScanFanoutConcurrency, + MaxDegreeOfParallelism = parallelism, CancellationToken = cancellationToken, }); From ba685d8092aae223e3b5a48c4bc331e2266318ef Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 3 Oct 2020 09:08:28 +0100 Subject: [PATCH 0055/1930] Update ApplicationHost.cs --- .../ApplicationHost.cs | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f36bc0eef2..a3e9693b3a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -128,7 +128,7 @@ namespace Emby.Server.Implementations private ISessionManager _sessionManager; private IHttpClientFactory _httpClientFactory; private IWebSocketManager _webSocketManager; - + private Dictionary _pluginRegistrations; private string[] _urlPrefixes; /// @@ -258,10 +258,12 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - + _jsonSerializer = new JsonSerializer(); + ServiceCollection = serviceCollection; + _pluginRegistrations = new Dictionary(); + _networkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -499,24 +501,11 @@ namespace Emby.Server.Implementations HttpsPort = ServerConfiguration.DefaultHttpsPort; } - if (Plugins != null) - { - var pluginBuilder = new StringBuilder(); - - foreach (var plugin in Plugins) - { - pluginBuilder.Append(plugin.Name) - .Append(' ') - .Append(plugin.Version) - .AppendLine(); - } - - Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); - } - DiscoverTypes(); RegisterServices(); + + RegisterPlugIns(); } /// @@ -781,10 +770,24 @@ namespace Emby.Server.Implementations ConfigurationManager.AddParts(GetExports()); _plugins = GetExports() - .Select(LoadPlugin) .Where(i => i != null) .ToArray(); + if (Plugins != null) + { + var pluginBuilder = new StringBuilder(); + + foreach (var plugin in Plugins) + { + pluginBuilder.Append(plugin.Name) + .Append(' ') + .Append(plugin.Version) + .AppendLine(); + } + + Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); + } + _urlPrefixes = GetUrlPrefixes().ToArray(); _webSocketManager.Init(GetExports()); @@ -850,8 +853,6 @@ namespace Emby.Server.Implementations { hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); } - - plugin.RegisterServices(ServiceCollection); } catch (Exception ex) { @@ -872,6 +873,24 @@ namespace Emby.Server.Implementations _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray(); } + private void RegisterPlugIns() + { + foreach ((var pluginType, var assembly) in _pluginRegistrations) + { + try + { + var pluginRegistration = Activator.CreateInstance(pluginType); + pluginType.InvokeMember("RegisterServices", BindingFlags.InvokeMethod, null, pluginRegistration, new object[] { ServiceCollection }, CultureInfo.InvariantCulture); + } + catch (Exception ex) + { + Logger.LogError(ex, "Error registering {Assembly} with D.I.", assembly); + } + } + + _pluginRegistrations.Clear(); + } + private IEnumerable GetTypes(IEnumerable assemblies) { foreach (var ass in assemblies) @@ -880,20 +899,11 @@ namespace Emby.Server.Implementations try { exportedTypes = ass.GetExportedTypes(); - - try + + Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + if (reg != null) { - Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - if (reg != null) - { - var pluginRegistration = Activator.CreateInstance(reg); - reg.InvokeMember("RegisterServices", BindingFlags.InvokeMethod, null, pluginRegistration, new object[] { ServiceCollection }, CultureInfo.InvariantCulture); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Error registering {Assembly} with D.I.", ass.FullName); - continue; + _pluginRegistrations.Add(ass, reg); } } catch (FileNotFoundException ex) @@ -1103,7 +1113,7 @@ namespace Emby.Server.Implementations { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) { @@ -1114,7 +1124,7 @@ namespace Emby.Server.Implementations { // Un-versioned folder - Add it under the path name and version 0.0.0.1. versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + } } } catch From 298a322ac1b8aece032511c39c3e3397dd09a0c4 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 3 Oct 2020 09:13:04 +0100 Subject: [PATCH 0056/1930] Update ApplicationHost.cs --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index a3e9693b3a..2bd3649840 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -903,7 +903,7 @@ namespace Emby.Server.Implementations Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (reg != null) { - _pluginRegistrations.Add(ass, reg); + _pluginRegistrations.Add(reg, ass); } } catch (FileNotFoundException ex) From 2929ce6e0dd8f3308bd1249e8b5eb1cf8edba008 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 3 Oct 2020 09:18:00 +0100 Subject: [PATCH 0057/1930] Update ApplicationHost.cs --- Emby.Server.Implementations/ApplicationHost.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 2bd3649840..3419675c36 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1540,6 +1540,7 @@ namespace Emby.Server.Implementations public IEnumerable GetApiPluginAssemblies() { var assemblies = _allConcreteTypes + .Select(LoadPlugin) .Where(i => typeof(ControllerBase).IsAssignableFrom(i)) .Select(i => i.Assembly) .Distinct(); From 7459baac8bf9bac4a29469eeead1204b1c0114b2 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 3 Oct 2020 09:23:12 +0100 Subject: [PATCH 0058/1930] Update ApplicationHost.cs --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 3419675c36..d14e503b06 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -770,6 +770,7 @@ namespace Emby.Server.Implementations ConfigurationManager.AddParts(GetExports()); _plugins = GetExports() + .Select(LoadPlugin) .Where(i => i != null) .ToArray(); @@ -1540,7 +1541,6 @@ namespace Emby.Server.Implementations public IEnumerable GetApiPluginAssemblies() { var assemblies = _allConcreteTypes - .Select(LoadPlugin) .Where(i => typeof(ControllerBase).IsAssignableFrom(i)) .Select(i => i.Assembly) .Distinct(); From 763862cbd879aceed9277d79c5e38e851403cfe6 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 3 Oct 2020 13:36:53 +0200 Subject: [PATCH 0059/1930] Defer image pre-fetching until the end of a refresh/scan --- .../Library/ImageFetcherPostScanTask.cs | 118 ++++++++++++++++++ .../Library/LibraryManager.cs | 45 +++++-- MediaBrowser.Controller/Entities/BaseItem.cs | 1 - MediaBrowser.Controller/Entities/Folder.cs | 5 - .../Library/ILibraryManager.cs | 2 + .../Manager/MetadataService.cs | 10 +- 6 files changed, 158 insertions(+), 23 deletions(-) create mode 100644 Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs new file mode 100644 index 0000000000..94d7f3cd64 --- /dev/null +++ b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Concurrent; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Data.Events; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using Microsoft.Extensions.Logging; + +namespace Emby.Server.Implementations.Library +{ + /// + /// Test. + /// + public class ImageFetcherPostScanTask : ILibraryPostScanTask + { + private readonly ILibraryManager _libraryManager; + private readonly IProviderManager _providerManager; + private readonly ILogger _logger; + private readonly SemaphoreSlim _imageFetcherLock; + + private ConcurrentDictionary _queuedItems; + + /// + /// Initializes a new instance of the class. + /// + /// Some stuff. + public ImageFetcherPostScanTask( + ILibraryManager libraryManager, + IProviderManager providerManager, + ILogger logger) + { + _libraryManager = libraryManager; + _providerManager = providerManager; + _logger = logger; + _queuedItems = new ConcurrentDictionary(); + _imageFetcherLock = new SemaphoreSlim(1, 1); + _libraryManager.ItemAdded += OnLibraryManagerItemAddedOrUpdated; + _libraryManager.ItemUpdated += OnLibraryManagerItemAddedOrUpdated; + _providerManager.RefreshCompleted += OnProviderManagerRefreshCompleted; + } + + /// + public async Task Run(IProgress progress, CancellationToken cancellationToken) + { + // Sometimes a library scan will cause this to run twice if there's an item refresh going on. + await _imageFetcherLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + var now = DateTime.UtcNow; + var itemGuids = _queuedItems.Keys.ToList(); + + for (var i = 0; i < itemGuids.Count; i++) + { + if (!_queuedItems.TryGetValue(itemGuids[i], out var queuedItem)) + { + continue; + } + + _logger.LogDebug( + "Updating remote images for item {ItemId} with media type {ItemMediaType}", + queuedItem.item.Id.ToString("N", CultureInfo.InvariantCulture), + queuedItem.item.GetType()); + await _libraryManager.UpdateImagesAsync(queuedItem.item, queuedItem.updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); + + _queuedItems.TryRemove(queuedItem.item.Id, out _); + } + + if (itemGuids.Count > 0) + { + _logger.LogInformation( + "Finished updating/pre-fetching {NumberOfImages} images. Elapsed time: {TimeElapsed}s.", + itemGuids.Count.ToString(CultureInfo.InvariantCulture), + (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + } + else + { + _logger.LogDebug("No images were updated."); + } + } + finally + { + _imageFetcherLock.Release(); + } + } + + private void OnLibraryManagerItemAddedOrUpdated(object sender, ItemChangeEventArgs itemChangeEventArgs) + { + if (!_queuedItems.ContainsKey(itemChangeEventArgs.Item.Id) && itemChangeEventArgs.Item.ImageInfos.Length > 0) + { + _queuedItems.AddOrUpdate( + itemChangeEventArgs.Item.Id, + (itemChangeEventArgs.Item, itemChangeEventArgs.UpdateReason), + (key, existingValue) => existingValue); + } + } + + private void OnProviderManagerRefreshCompleted(object sender, GenericEventArgs e) + { + if (!_queuedItems.ContainsKey(e.Argument.Id) && e.Argument.ImageInfos.Length > 0) + { + _queuedItems.AddOrUpdate( + e.Argument.Id, + (e.Argument, ItemUpdateType.None), + (key, existingValue) => existingValue); + } + + // The RefreshCompleted event is a bit awkward in that it seems to _only_ be fired on + // the item that was refreshed regardless of children refreshes. So we take it as a signal + // that the refresh is entirely completed. + Run(null, CancellationToken.None).GetAwaiter().GetResult(); + } + } +} diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 00282b71a5..74788a320f 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -857,7 +857,21 @@ namespace Emby.Server.Implementations.Library /// Task{Person}. public Person GetPerson(string name) { - return CreateItemByName(Person.GetPath, name, new DtoOptions(true)); + var path = Person.GetPath(name); + var id = GetItemByNameId(path); + if (!(GetItemById(id) is Person item)) + { + item = new Person + { + Name = name, + Id = id, + DateCreated = DateTime.UtcNow, + DateModified = DateTime.UtcNow, + Path = path + }; + } + + return item; } /// @@ -1940,19 +1954,9 @@ namespace Emby.Server.Implementations.Library } /// - public async Task UpdateItemsAsync(IReadOnlyList items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) + public Task UpdateItemsAsync(IReadOnlyList items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) { - foreach (var item in items) - { - if (item.IsFileProtocol) - { - ProviderManager.SaveMetadata(item, updateReason); - } - - item.DateLastSaved = DateTime.UtcNow; - - await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); - } + RunMetadataSavers(items, updateReason); _itemRepository.SaveItems(items, cancellationToken); @@ -1983,12 +1987,27 @@ namespace Emby.Server.Implementations.Library } } } + + return Task.CompletedTask; } /// public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken); + public void RunMetadataSavers(IReadOnlyList items, ItemUpdateType updateReason) + { + foreach (var item in items) + { + if (item.IsFileProtocol) + { + ProviderManager.SaveMetadata(item, updateReason); + } + + item.DateLastSaved = DateTime.UtcNow; + } + } + /// /// Reports the item removed. /// diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 68126bd8a8..0e99646084 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1433,7 +1433,6 @@ namespace MediaBrowser.Controller.Entities new List(); var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false); - await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh if (ownedItemsChanged) { diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 11542c1cad..b8737b48cd 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -352,11 +352,6 @@ namespace MediaBrowser.Controller.Entities { await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false); } - else - { - // metadata is up-to-date; make sure DB has correct images dimensions and hash - await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false); - } continue; } diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 804170d5c9..d329495b9c 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -567,5 +567,7 @@ namespace MediaBrowser.Controller.Library void AddExternalSubtitleStreams(List streams, string videoPath, string[] files); + + void RunMetadataSavers(IReadOnlyList items, ItemUpdateType updateReason); } } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index f110eafa5a..7ca51f4b5a 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -231,14 +231,14 @@ namespace MediaBrowser.Providers.Manager private async Task SavePeopleMetadataAsync(List people, LibraryOptions libraryOptions, CancellationToken cancellationToken) { + var personsToSave = new List(); + foreach (var person in people) { cancellationToken.ThrowIfCancellationRequested(); if (person.ProviderIds.Count > 0 || !string.IsNullOrWhiteSpace(person.ImageUrl)) { - var updateType = ItemUpdateType.MetadataDownload; - var saveEntity = false; var personEntity = LibraryManager.GetPerson(person.Name); foreach (var id in person.ProviderIds) @@ -255,15 +255,17 @@ namespace MediaBrowser.Providers.Manager await AddPersonImageAsync(personEntity, libraryOptions, person.ImageUrl, cancellationToken).ConfigureAwait(false); saveEntity = true; - updateType |= ItemUpdateType.ImageUpdate; } if (saveEntity) { - await personEntity.UpdateToRepositoryAsync(updateType, cancellationToken).ConfigureAwait(false); + personsToSave.Add(personEntity); } } } + + LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload); + LibraryManager.CreateItems(personsToSave, null, CancellationToken.None); } private async Task AddPersonImageAsync(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken) From 5d3449e9dc8c43efa16669a390870c52676bcba5 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 3 Oct 2020 13:39:39 +0200 Subject: [PATCH 0060/1930] Fix xml doc comment --- Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs index 94d7f3cd64..49f920edae 100644 --- a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs +++ b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs @@ -13,7 +13,7 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library { /// - /// Test. + /// A library post scan/refresh task for pre-fetching remote images. /// public class ImageFetcherPostScanTask : ILibraryPostScanTask { From 1b18f86c8b92eb0c75ee6db27eaffce918afa988 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 3 Oct 2020 13:52:51 +0200 Subject: [PATCH 0061/1930] Add missing parameter comments. --- .../Library/ImageFetcherPostScanTask.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs index 49f920edae..66540b4d40 100644 --- a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs +++ b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs @@ -27,7 +27,9 @@ namespace Emby.Server.Implementations.Library /// /// Initializes a new instance of the class. /// - /// Some stuff. + /// An instance of . + /// An instance of . + /// An instance of . public ImageFetcherPostScanTask( ILibraryManager libraryManager, IProviderManager providerManager, From 53af1e34553917d00e17465f345ea530f04beddf Mon Sep 17 00:00:00 2001 From: Jim Cartlidge Date: Sun, 4 Oct 2020 09:56:33 +0100 Subject: [PATCH 0062/1930] Updatig netcollection & re-inserting BOM --- Emby.Dlna/Main/DlnaEntryPoint.cs | 14 +++++++------- Emby.Server.Implementations/ApplicationHost.cs | 8 ++++---- .../LiveTv/LiveTvMediaSourceProvider.cs | 3 +-- .../TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 3 ++- Emby.Server.Implementations/Udp/UdpServer.cs | 2 +- Jellyfin.Networking/Jellyfin.Networking.csproj | 2 +- RSSDP/SsdpCommunicationsServer.cs | 2 +- RSSDP/SsdpDevicePublisher.cs | 7 ++++--- 8 files changed, 21 insertions(+), 20 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 33a953563b..a644d2c8cc 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -271,33 +271,33 @@ namespace Emby.Dlna.Main bindAddresses = _networkManager.GetLoopbacks(); } - foreach (var addr in bindAddresses) + foreach (IPNetAddress address in bindAddresses) { - if (addr.AddressFamily == AddressFamily.InterNetworkV6) + if (address.AddressFamily == AddressFamily.InterNetworkV6) { // Not supporting IPv6 right now continue; } // Limit to LAN addresses only - if (!_networkManager.IsInLocalNetwork(addr)) + if (!_networkManager.IsInLocalNetwork(address)) { continue; } var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {0} on {1}", fullService, addr); + _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); var descriptorUri = "/dlna/" + udn + "/description.xml"; - var uri = new Uri(_appHost.GetSmartApiUrl(addr.Address) + descriptorUri); + var uri = new Uri(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri, // Must point to the URL that serves your devices UPnP description document. - Address = addr.Address, - SubnetMask = ((IPNetAddress)addr).Mask, // MIGRATION: This fields is going. + Address = address.Address, + SubnetMask = address.Mask, FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 66e48ddc65..77584e9d0d 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -262,8 +262,8 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - + _jsonSerializer = new JsonSerializer(); + ServiceCollection = serviceCollection; ApplicationPaths = applicationPaths; @@ -1079,7 +1079,7 @@ namespace Emby.Server.Implementations { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) { @@ -1248,7 +1248,7 @@ namespace Emby.Server.Implementations OperatingSystem = OperatingSystem.Id.ToString(), ServerName = FriendlyName, LocalAddress = GetSmartApiUrl(source), - StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted + StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted }; } diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 598cf0af7c..3a738fd5d2 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -76,7 +76,6 @@ namespace Emby.Server.Implementations.LiveTv } var list = sources.ToList(); - var serverUrl = _appHost.GetSmartApiUrl(string.Empty); foreach (var source in list) { @@ -103,7 +102,7 @@ namespace Emby.Server.Implementations.LiveTv // Dummy this up so that direct play checks can still run if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http) { - source.Path = serverUrl; + source.Path = _appHost.GetSmartApiUrl(string.Empty); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index a8d2a27f78..cfc5278ece 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -16,6 +16,7 @@ using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging; +using NetworkCollection.Udp; namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { @@ -57,7 +58,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var mediaSource = OriginalMediaSource; var uri = new Uri(mediaSource.Path); - var localPort = 50000; // Will return to random after next PR. + var localPort = UdpHelper.GetRandomUnusedUdpPort(); Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath)); diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 3dc34da5cf..4fd7ac0c18 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Udp { string localUrl = !string.IsNullOrEmpty(_config[AddressOverrideConfigKey]) ? _config[AddressOverrideConfigKey] - : _appHost.GetSmartApiUrl(string.Empty); // MIGRATION: Temp value. + : _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address); if (!string.IsNullOrEmpty(localUrl)) { diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index 06d387dc87..7f01f149ec 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -28,7 +28,7 @@ - + diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index ea9e9a6fb5..8f1f0fa613 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -352,7 +352,7 @@ namespace Rssdp.Infrastructure if (_enableMultiSocketBinding) { - foreach (var address in _networkManager.GetAllBindInterfaces()) + foreach (var address in _networkManager.GetInternalBindAddresses()) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index c70294b38e..ca382c905a 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -301,9 +301,10 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { - var ip1 = new IPNetAddress(device.ToRootDevice().Address, device.ToRootDevice().SubnetMask); - var ip2 = new IPNetAddress(remoteEndPoint.Address, device.ToRootDevice().SubnetMask); - if (!_sendOnlyMatchedHost || ip1.NetworkAddress.Equals(ip2.NetworkAddress)) + var root = device.ToRootDevice(); + var source = new IPNetAddress(root.Address, root.SubnetMask); + var destination = new IPNetAddress(remoteEndPoint.Address, root.SubnetMask); + if (!_sendOnlyMatchedHost || source.NetworkAddress.Equals(destination.NetworkAddress)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } From 04552e86fb9467a121bb079da2cadecd1af2e7fc Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:00:51 +0100 Subject: [PATCH 0063/1930] Update DefaultAuthorizationHandler.cs --- .../DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index e988ca6cd1..b5913daab9 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; From a3a2ca412b126413cce80525c9df2ee130f100df Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:01:10 +0100 Subject: [PATCH 0064/1930] Update DownloadHandler.cs --- Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs index cea5ac4734..b61680ab1a 100644 --- a/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs +++ b/Jellyfin.Api/Auth/DownloadPolicy/DownloadHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; From 34ef6492ee3ef4be695af7b16aaf4b319c5ffa63 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:01:32 +0100 Subject: [PATCH 0065/1930] Update FirstTimeOrIgnoreParentalControlSetupHandler.cs --- .../FirstTimeOrIgnoreParentalControlSetupHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs index 96cf4db4b5..31482a930f 100644 --- a/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs +++ b/Jellyfin.Api/Auth/FirstTimeOrIgnoreParentalControlSetupPolicy/FirstTimeOrIgnoreParentalControlSetupHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; From 168a4ec2f2de2aba191660bb471d18a482eb9d0b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:01:56 +0100 Subject: [PATCH 0066/1930] Update IgnoreParentalControlHandler.cs --- .../IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs index 3eb3ac6cdc..5213bc4cb7 100644 --- a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs +++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; From b5ea16cf7bc7d8fe881ae4b6a5734455fe76005d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:02:13 +0100 Subject: [PATCH 0067/1930] Update LocalAccessOrRequiresElevationHandler.cs --- .../LocalAccessOrRequiresElevationHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index 7bede142e0..14722aa57e 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using Jellyfin.Api.Constants; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; From eaf684a68c8432b6411b5c77db34fe1d865f4aee Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:02:35 +0100 Subject: [PATCH 0068/1930] Update DynamicHlsHelper.cs --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 1d330a3357..af0519ffa8 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; From bb4c668650bc5e96dd8f290b4309014e8142f1ea Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:02:52 +0100 Subject: [PATCH 0069/1930] Update LocalAccessHandler.cs --- Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs index 2999c6c8a8..af73352bcc 100644 --- a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs @@ -1,4 +1,4 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; From 5360f5a43dd5f0c862aff32a48d66b37f5376eef Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:03:08 +0100 Subject: [PATCH 0070/1930] Update UserController.cs --- Jellyfin.Api/Controllers/UserController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 9e61b2b8ad..50bb8bb2aa 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; From 7f1ec1b569053165d05f5bf6a1f6bc4bcc8cdb67 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:03:34 +0100 Subject: [PATCH 0071/1930] Update MediaInfoHelper.cs --- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index b4b6e2d35c..1207fb5134 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Linq; using System.Text.Json; From 29133b6452533c6a1ca1e38cd34977e512ac18de Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:04:43 +0100 Subject: [PATCH 0072/1930] Update PathSubstitution.cs --- MediaBrowser.Model/Configuration/PathSubstitution.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs index 40eb36c2ea..a066886e2b 100644 --- a/MediaBrowser.Model/Configuration/PathSubstitution.cs +++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable #pragma warning disable CS1591 #pragma warning disable CA1819 From fae70bbbcfc75c06c6681bc34044944a26d58771 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:05:38 +0100 Subject: [PATCH 0073/1930] Update LocalAccessHandlerTests.cs --- .../Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs index 553e6a9cab..09ffa84689 100644 --- a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; using AutoFixture; using AutoFixture.AutoMoq; From 2e3901252a02c79efa53f21f4695e45f6c580a59 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 4 Oct 2020 10:07:05 +0100 Subject: [PATCH 0074/1930] Update UserManager.cs --- Jellyfin.Server.Implementations/Users/UserManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index bd853f92f7..8f04baa089 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable #pragma warning disable CA1307 using System; From 4a81ee43dc7aed94012c312a8262a1426be9b6d9 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 6 Oct 2020 23:36:48 +0200 Subject: [PATCH 0075/1930] Add try-catch to avoid crashing the whole thing --- .../Library/ImageFetcherPostScanTask.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs index 66540b4d40..b18a0c1a80 100644 --- a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs +++ b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs @@ -8,6 +8,7 @@ using Jellyfin.Data.Events; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library @@ -63,11 +64,20 @@ namespace Emby.Server.Implementations.Library continue; } + var itemId = queuedItem.item.Id.ToString("N", CultureInfo.InvariantCulture); + var itemType = queuedItem.item.GetType(); _logger.LogDebug( "Updating remote images for item {ItemId} with media type {ItemMediaType}", - queuedItem.item.Id.ToString("N", CultureInfo.InvariantCulture), - queuedItem.item.GetType()); - await _libraryManager.UpdateImagesAsync(queuedItem.item, queuedItem.updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); + itemId, + itemType); + try + { + await _libraryManager.UpdateImagesAsync(queuedItem.item, queuedItem.updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); + } + catch (HttpException ex) + { + _logger.LogError(ex, "Failed to fetch images for {Type} item with id {ItemId}", itemType, itemId); + } _queuedItems.TryRemove(queuedItem.item.Id, out _); } From a3f0843ac97c64a8a412d707baa9870d0e53dcff Mon Sep 17 00:00:00 2001 From: Greenback Date: Thu, 8 Oct 2020 19:00:30 +0100 Subject: [PATCH 0076/1930] Updated NetworkManager to PR1 --- .../Configuration/NetworkConfiguration.cs | 223 ++++++++++++++++++ .../NetworkConfigurationExtensions.cs | 21 ++ .../NetworkConfigurationFactory.cs | 27 +++ Jellyfin.Networking/Manager/NetworkManager.cs | 131 +++++----- MediaBrowser.Common/Net/INetworkManager.cs | 21 +- 5 files changed, 338 insertions(+), 85 deletions(-) create mode 100644 Jellyfin.Networking/Configuration/NetworkConfiguration.cs create mode 100644 Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs create mode 100644 Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs new file mode 100644 index 0000000000..38f11153ab --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -0,0 +1,223 @@ +#pragma warning disable CA1819 // Properties should not return arrays + +using System; +using MediaBrowser.Model.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public class NetworkConfiguration + { + private string _baseUrl = string.Empty; + + /// + /// Gets the default http port. + /// + public const int DefaultHttpPort = 8096; + + /// + /// Gets the default https port. + /// + public const int DefaultHttpsPort = 8920; + + /// + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// + public bool RequireHttps { get; set; } = false; + + /// + /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. + /// + public string BaseUrl + { + get => _baseUrl; + set + { + // Normalize the start of the string + if (string.IsNullOrWhiteSpace(value)) + { + // If baseUrl is empty, set an empty prefix string + _baseUrl = string.Empty; + return; + } + + if (value[0] != '/') + { + // If baseUrl was not configured with a leading slash, append one for consistency + value = "/" + value; + } + + // Normalize the end of the string + if (value[value.Length - 1] == '/') + { + // If baseUrl was configured with a trailing slash, remove it for consistency + value = value.Remove(value.Length - 1); + } + + _baseUrl = value; + } + } + + /// + /// Gets or sets the public HTTPS port. + /// + /// The public HTTPS port. + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets the HTTP server port number. + /// + /// The HTTP server port number. + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets the HTTPS server port number. + /// + /// The HTTPS server port number. + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets a value indicating whether to use HTTPS. + /// + /// + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for and . + /// + public bool EnableHttps { get; set; } = false; + + /// + /// Gets or sets the public mapped port. + /// + /// The public mapped port. + public int PublicPort { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.. + /// + public bool UPnPCreateHttpPortMap { get; set; } = false; + + /// + /// Gets or sets the UDPPortRange + /// Gets or sets client udp port range.. + /// + public string UDPPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether gets or sets IPV6 capability.. + /// + public bool EnableIPV6 { get; set; } = false; + + /// + /// Gets or sets a value indicating whether gets or sets IPV4 capability.. + /// + public bool EnableIPV4 { get; set; } = true; + + /// + /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.. + /// + public bool EnableSSDPTracing { get; set; } = false; + + /// + /// Gets or sets the SSDPTracingFilter + /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.. + /// + public string SSDPTracingFilter { get; set; } = string.Empty; + + /// + /// Gets or sets the number of times SSDP UDP messages are sent.. + /// + public int UDPSendCount { get; set; } = 2; + + /// + /// Gets or sets the delay between each groups of SSDP messages (in ms).. + /// + public int UDPSendDelay { get; set; } = 100; + + /// + /// Gets or sets a value indicating whether address names that match should be Ignore for the purposes of binding.. + /// + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// + /// Gets or sets the VirtualInterfaceNames + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. .. + /// + public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + + /// + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.. + /// + public int GatewayMonitorPeriod { get; set; } = 60; + + /// + /// Gets a value indicating whether multi-socket binding is available.. + /// + public bool EnableMultiSocketBinding { get; } = true; + + /// + /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. + /// Depending on the address range implemented ULA ranges might not be used.. + /// + public bool TrustAllIP6Interfaces { get; set; } = false; + + /// + /// Gets or sets the ports that HDHomerun uses.. + /// + public string HDHomerunPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets the PublishedServerUriBySubnet + /// Gets or sets PublishedServerUri to advertise for specific subnets.. + /// + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.. + /// + public bool AutoDiscoveryTracing { get; set; } = false; + + /// + /// Gets or sets a value indicating whether Autodiscovery is enabled.. + /// + public bool AutoDiscovery { get; set; } = true; + + /// + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with .. + /// + public string[] RemoteIPFilter { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist.. + /// + public bool IsRemoteIPFilterBlacklist { get; set; } = false; + + /// + /// Gets or sets a value indicating whether to enable automatic port forwarding.. + /// + public bool EnableUPnP { get; set; } = false; + + /// + /// Gets or sets a value indicating whether access outside of the LAN is permitted.. + /// + public bool EnableRemoteAccess { get; set; } = true; + + /// + /// Gets or sets the subnets that are deemed to make up the LAN.. + /// + public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); + + /// + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.. + /// + public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); + + /// + /// Gets or sets the known proxies. + /// + public string[] KnownProxies { get; set; } = Array.Empty(); + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs new file mode 100644 index 0000000000..e77b17ba92 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -0,0 +1,21 @@ +using Jellyfin.Networking.Configuration; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public static class NetworkConfigurationExtensions + { + /// + /// Retrieves the network configuration. + /// + /// The . + /// The . + public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) + { + return config.GetConfiguration("network"); + } + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs new file mode 100644 index 0000000000..ac0485d871 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public class NetworkConfigurationFactory : IConfigurationFactory + { + /// + /// The GetConfigurations. + /// + /// The . + public IEnumerable GetConfigurations() + { + return new[] + { + new ConfigurationStore + { + Key = "network", + ConfigurationType = typeof(NetworkConfiguration) + } + }; + } + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 6f2970ef89..491fe824da 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -6,9 +6,9 @@ using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; -using MediaBrowser.Model.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using NetworkCollection; @@ -24,7 +24,7 @@ namespace Jellyfin.Networking.Manager /// /// Contains the description of the interface along with its index. /// - private readonly SortedList _interfaceNames; + private readonly Dictionary _interfaceNames; /// /// Threading lock for network interfaces. @@ -96,7 +96,7 @@ namespace Jellyfin.Networking.Manager /// /// IServerConfigurationManager instance. /// Logger to use for messages. -#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in InitialiseLAN function. Compiler doesn't yet recognise this. +#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this. public NetworkManager(IConfigurationManager configurationManager, ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -104,15 +104,9 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses = new NetCollection(unique: false); _macAddresses = new List(); - _interfaceNames = new SortedList(); + _interfaceNames = new Dictionary(); _publishedServerUrls = new Dictionary(); - UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); - if (!IsIP6Enabled && !IsIP4Enabled) - { - throw new ApplicationException("IPv4 and IPv6 cannot both be disabled."); - } - NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; @@ -182,7 +176,7 @@ namespace Jellyfin.Networking.Manager lock (_intLock) { - return _internalInterfaces.Where(i => i.Address.Equals(address) && (i.Tag < 0)).Any(); + return _internalInterfaces.Where(i => i.Address.Equals(address) && i.Tag < 0).Any(); } } @@ -212,49 +206,46 @@ namespace Jellyfin.Networking.Manager /// public bool IsExcluded(EndPoint ip) { - if (ip != null) - { - return _excludedSubnets.Contains(((IPEndPoint)ip).Address); - } - - return false; + return ip != null && IsExcluded(((IPEndPoint)ip).Address); } /// public NetCollection CreateIPCollection(string[] values, bool bracketed = false) { NetCollection col = new NetCollection(); - if (values != null) + if (values == null) { - for (int a = 0; a < values.Length; a++) - { - string v = values[a].Trim(); + return col; + } - try + for (int a = 0; a < values.Length; a++) + { + string v = values[a].Trim(); + + try + { + if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) { - if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) + if (bracketed) { - if (bracketed) - { - AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); - } - } - else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) - { - if (bracketed) - { - AddToCollection(col, v.Substring(1)); - } - } - else if (!bracketed) - { - AddToCollection(col, v); + AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); } } - catch (ArgumentException e) + else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) { - _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); + if (bracketed) + { + AddToCollection(col, v.Substring(1)); + } } + else if (!bracketed) + { + AddToCollection(col, v); + } + } + catch (ArgumentException e) + { + _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); } } @@ -305,12 +296,9 @@ namespace Jellyfin.Networking.Manager /// public string GetBindInterface(string source, out int? port) { - if (!string.IsNullOrEmpty(source)) + if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host)) { - if (IPHost.TryParse(source, out IPHost host)) - { - return GetBindInterface(host, out port); - } + return GetBindInterface(host, out port); } return GetBindInterface(IPHost.None, out port); @@ -345,7 +333,6 @@ namespace Jellyfin.Networking.Manager public string GetBindInterface(IPObject source, out int? port) { port = null; - bool isChromeCast = source == IPNetAddress.IP4Loopback; // Do we have a source? bool haveSource = !source.Address.Equals(IPAddress.None); bool isExternal = false; @@ -354,7 +341,7 @@ namespace Jellyfin.Networking.Manager { if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) { - _logger.LogWarning("IPv6 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); + _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) @@ -364,7 +351,7 @@ namespace Jellyfin.Networking.Manager isExternal = !IsInLocalNetwork(source); - if (MatchesPublishedServerUrl(source, isExternal, isChromeCast, out string result, out port)) + if (MatchesPublishedServerUrl(source, isExternal, out string result, out port)) { _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, result, port); return result; @@ -529,12 +516,7 @@ namespace Jellyfin.Networking.Manager { lock (_intLock) { - if (_bindExclusions.Count > 0) - { - return _bindExclusions.Contains(address); - } - - return false; + return _bindExclusions.Contains(address); } } @@ -596,16 +578,20 @@ namespace Jellyfin.Networking.Manager /// /// Reloads all settings and re-initialises the instance. /// - /// to use. - public void UpdateSettings(ServerConfiguration config) + /// The configuration to use. + public void UpdateSettings(object configuration) { - if (config == null) - { - throw new ArgumentNullException(nameof(config)); - } + NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); IsIP4Enabled = Socket.OSSupportsIPv6 && config.EnableIPV4; IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; + + if (!IsIP6Enabled && !IsIP4Enabled) + { + _logger.LogError("IPv4 and IPv6 cannot both be disabled."); + IsIP4Enabled = true; + } + TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding; @@ -655,7 +641,7 @@ namespace Jellyfin.Networking.Manager private void ConfigurationUpdated(object? sender, EventArgs args) { - UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration); + UpdateSettings(_configurationManager.GetNetworkConfiguration()); } /// @@ -804,7 +790,7 @@ namespace Jellyfin.Networking.Manager await Task.Delay(2000).ConfigureAwait(false); InitialiseInterfaces(); // Recalculate LAN caches. - InitialiseLAN((ServerConfiguration)_configurationManager.CommonConfiguration); + InitialiseLAN(_configurationManager.GetNetworkConfiguration()); NetworkChanged?.Invoke(this, EventArgs.Empty); } @@ -835,7 +821,7 @@ namespace Jellyfin.Networking.Manager /// format is subnet=ipaddress|host|uri /// when subnet = 0.0.0.0, any external address matches. /// - private void InitialiseOverrides(ServerConfiguration config) + private void InitialiseOverrides(NetworkConfiguration config) { lock (_intLock) { @@ -884,7 +870,7 @@ namespace Jellyfin.Networking.Manager } } - private void InitialiseBind(ServerConfiguration config) + private void InitialiseBind(NetworkConfiguration config) { string[] ba = config.LocalNetworkAddresses; @@ -912,7 +898,7 @@ namespace Jellyfin.Networking.Manager _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); } - private void InitialiseRemote(ServerConfiguration config) + private void InitialiseRemote(NetworkConfiguration config) { RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); } @@ -920,7 +906,7 @@ namespace Jellyfin.Networking.Manager /// /// Initialises internal LAN cache settings. /// - private void InitialiseLAN(ServerConfiguration config) + private void InitialiseLAN(NetworkConfiguration config) { lock (_intLock) { @@ -1029,8 +1015,7 @@ namespace Jellyfin.Networking.Manager }; int tag = nw.Tag; - /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */ - if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback()) + if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback()) { // -ve Tags signify the interface has a gateway. nw.Tag *= -1; @@ -1051,8 +1036,7 @@ namespace Jellyfin.Networking.Manager }; int tag = nw.Tag; - /* Mono on OSX doesn't give any gateway addresses, so check DNS entries */ - if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback()) + if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback()) { // -ve Tags signify the interface has a gateway. nw.Tag *= -1; @@ -1112,11 +1096,10 @@ namespace Jellyfin.Networking.Manager /// /// IP source address to use. /// True if the source is in the external subnet. - /// True if the request is for a chromecast device. /// The published server url that matches the source address. /// The resultant port, if one exists. /// True if a match is found. - private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, bool isChromeCast, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port) { bindPreference = string.Empty; port = null; @@ -1130,7 +1113,7 @@ namespace Jellyfin.Networking.Manager bindPreference = addr.Value; break; } - else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && (isExternal || isChromeCast)) + else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal) { // External. bindPreference = addr.Value; @@ -1241,7 +1224,7 @@ namespace Jellyfin.Networking.Manager } /// - /// Attempts to match the source against am external interface. + /// Attempts to match the source against an external interface. /// /// IP source address to use. /// The result, if a match is found. diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 8789cd9d81..f60f369d6a 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; -using MediaBrowser.Model.Configuration; using Microsoft.AspNetCore.Http; using NetworkCollection; @@ -27,7 +26,7 @@ namespace MediaBrowser.Common.Net /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIP6Interfaces { get; } + bool TrustAllIP6Interfaces { get; } /// /// Gets the remote address filter. @@ -37,12 +36,12 @@ namespace MediaBrowser.Common.Net /// /// Gets or sets a value indicating whether iP6 is enabled. /// - public bool IsIP6Enabled { get; set; } + bool IsIP6Enabled { get; set; } /// /// Gets or sets a value indicating whether iP4 is enabled. /// - public bool IsIP4Enabled { get; set; } + bool IsIP4Enabled { get; set; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -57,7 +56,7 @@ namespace MediaBrowser.Common.Net /// Returns a collection containing the loopback interfaces. /// /// Netcollection. - public NetCollection GetLoopbacks(); + NetCollection GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -93,7 +92,7 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See above). + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. @@ -103,7 +102,7 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See above). + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. @@ -113,7 +112,7 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See above). + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. @@ -138,7 +137,7 @@ namespace MediaBrowser.Common.Net /// /// IP to check. Can be an IPAddress or an IPObject. /// Result of the check. - public bool IsGatewayInterface(object? addressObj); + bool IsGatewayInterface(object? addressObj); /// /// Returns true if the address is a private address. @@ -226,7 +225,7 @@ namespace MediaBrowser.Common.Net /// /// Reloads all settings and re-initialises the instance. /// - /// to use. - public void UpdateSettings(ServerConfiguration config); + /// The configuration to use. + void UpdateSettings(object configuration); } } From deb4d27857089e8f3a3602399c5b52ad8df170f2 Mon Sep 17 00:00:00 2001 From: Greenback Date: Thu, 8 Oct 2020 19:00:55 +0100 Subject: [PATCH 0077/1930] Moved all settings across to network.xml --- .../AppBase/BaseConfigurationManager.cs | 7 +- .../ApplicationHost.cs | 38 +++++++--- .../EntryPoints/ExternalPortForwarding.cs | 11 +-- .../Controllers/ConfigurationController.cs | 12 ++++ Jellyfin.Api/Controllers/StartupController.cs | 8 ++- Jellyfin.Api/Helpers/ClassMigrationHelper.cs | 70 +++++++++++++++++++ .../ApiApplicationBuilderExtensions.cs | 5 +- .../BaseUrlRedirectionMiddleware.cs | 3 +- .../IpBasedAccessValidationMiddleware.cs | 5 +- .../Middleware/LanFilteringMiddleware.cs | 3 +- Jellyfin.Server/Startup.cs | 5 +- .../Configuration/IConfigurationManager.cs | 3 +- 12 files changed, 143 insertions(+), 27 deletions(-) create mode 100644 Jellyfin.Api/Helpers/ClassMigrationHelper.cs diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 4ab0a2a3f2..fa4b3080c9 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -10,6 +10,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; +using Microsoft.EntityFrameworkCore.Migrations.Operations; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.AppBase @@ -268,7 +269,7 @@ namespace Emby.Server.Implementations.AppBase } /// - public object GetConfiguration(string key) + public object GetConfiguration(string key, Type objectType = null) { return _configurations.GetOrAdd(key, k => { @@ -277,12 +278,12 @@ namespace Emby.Server.Implementations.AppBase var configurationInfo = _configurationStores .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase)); - if (configurationInfo == null) + if (configurationInfo == null && objectType == null) { throw new ResourceNotFoundException("Configuration with key " + key + " not found."); } - var configurationType = configurationInfo.ConfigurationType; + var configurationType = configurationInfo?.ConfigurationType ?? objectType; lock (_configurationSyncLock) { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 77584e9d0d..9d70c15269 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -16,6 +16,7 @@ using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; +using System.Xml.Serialization; using Emby.Dlna; using Emby.Dlna.Main; using Emby.Dlna.Ssdp; @@ -48,6 +49,8 @@ using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; +using Jellyfin.Api.Migrations; +using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; @@ -100,6 +103,7 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Plugins.TheTvdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; +using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; @@ -273,6 +277,7 @@ namespace Emby.Server.Implementations ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); + NetManager.UpdateSettings(GetNetworkConfiguration()); Logger = LoggerFactory.CreateLogger(); @@ -298,6 +303,21 @@ namespace Emby.Server.Implementations ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; } + private NetworkConfiguration GetNetworkConfiguration() + { + string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml"); + if (!File.Exists(path)) + { + var networkSettings = new NetworkConfiguration(); + ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings); + _xmlSerializer.SerializeToFile(networkSettings, path); + + return networkSettings; + } + + return (NetworkConfiguration)ConfigurationManager.GetConfiguration("network", typeof(NetworkConfiguration)); + } + public string ExpandVirtualPath(string path) { var appPaths = ApplicationPaths; @@ -480,14 +500,15 @@ namespace Emby.Server.Implementations /// public void Init() { - HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber; - HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber; + var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); + HttpPort = networkConfiguration.HttpServerPortNumber; + HttpsPort = networkConfiguration.HttpsPortNumber; // Safeguard against invalid configuration if (HttpPort == HttpsPort) { - HttpPort = ServerConfiguration.DefaultHttpPort; - HttpsPort = ServerConfiguration.DefaultHttpsPort; + HttpPort = NetworkConfiguration.DefaultHttpPort; + HttpsPort = NetworkConfiguration.DefaultHttpsPort; } if (Plugins != null) @@ -929,9 +950,10 @@ namespace Emby.Server.Implementations // Don't do anything if these haven't been set yet if (HttpPort != 0 && HttpsPort != 0) { + var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); // Need to restart if ports have changed - if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort || - ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort) + if (networkConfiguration.HttpServerPortNumber != HttpPort || + networkConfiguration.HttpsPortNumber != HttpsPort) { if (ServerConfigurationManager.Configuration.IsPortAuthorized) { @@ -1253,7 +1275,7 @@ namespace Emby.Server.Implementations } /// - public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps; + public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps; /// public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) @@ -1337,7 +1359,7 @@ namespace Emby.Server.Implementations Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp), Host = host, Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort), - Path = ServerConfigurationManager.Configuration.BaseUrl + Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl }.ToString().TrimEnd('/'); } diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 2e8cc76d23..14201ead29 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -8,6 +8,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; +using Jellyfin.Networking.Configuration; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Plugins; @@ -56,7 +57,7 @@ namespace Emby.Server.Implementations.EntryPoints private string GetConfigIdentifier() { const char Separator = '|'; - var config = _config.Configuration; + var config = _config.GetNetworkConfiguration(); return new StringBuilder(32) .Append(config.EnableUPnP).Append(Separator) @@ -93,7 +94,8 @@ namespace Emby.Server.Implementations.EntryPoints private void Start() { - if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess) + var config = _config.GetNetworkConfiguration(); + if (!config.EnableUPnP || !config.EnableRemoteAccess) { return; } @@ -156,11 +158,12 @@ namespace Emby.Server.Implementations.EntryPoints private IEnumerable CreatePortMaps(INatDevice device) { - yield return CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort); + var config = _config.GetNetworkConfiguration(); + yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort); if (_appHost.ListenWithHttps) { - yield return CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort); + yield return CreatePortMap(device, _appHost.HttpsPort, config.PublicHttpsPort); } } diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index e1c9f69f61..09d72e8b10 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -4,7 +4,9 @@ using System.Text.Json; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using Jellyfin.Api.Migrations; using Jellyfin.Api.Models.ConfigurationDtos; +using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; @@ -49,6 +51,10 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetConfiguration() { + // TODO: Temp workaround until the web can be changed. + var net = _configurationManager.GetNetworkConfiguration(); + ClassMigrationHelper.CopyProperties(net, _configurationManager.Configuration); + return _configurationManager.Configuration; } @@ -64,6 +70,12 @@ namespace Jellyfin.Api.Controllers public ActionResult UpdateConfiguration([FromBody, Required] ServerConfiguration configuration) { _configurationManager.ReplaceConfiguration(configuration); + + // TODO: Temp workaround until the web can be changed. + var network = _configurationManager.GetNetworkConfiguration(); + ClassMigrationHelper.CopyProperties(configuration, network); + _configurationManager.SaveConfiguration("Network", network); + return NoContent(); } diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs index e59c6e1ddf..d9cb34557b 100644 --- a/Jellyfin.Api/Controllers/StartupController.cs +++ b/Jellyfin.Api/Controllers/StartupController.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Models.StartupDtos; +using Jellyfin.Networking.Configuration; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; @@ -89,9 +90,10 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SetRemoteAccess([FromBody, Required] StartupRemoteAccessDto startupRemoteAccessDto) { - _config.Configuration.EnableRemoteAccess = startupRemoteAccessDto.EnableRemoteAccess; - _config.Configuration.EnableUPnP = startupRemoteAccessDto.EnableAutomaticPortMapping; - _config.SaveConfiguration(); + NetworkConfiguration settings = _config.GetNetworkConfiguration(); + settings.EnableRemoteAccess = startupRemoteAccessDto.EnableRemoteAccess; + settings.EnableUPnP = startupRemoteAccessDto.EnableAutomaticPortMapping; + _config.SaveConfiguration("network", settings); return NoContent(); } diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs new file mode 100644 index 0000000000..123fd012de --- /dev/null +++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs @@ -0,0 +1,70 @@ +using System; +using System.Reflection; + +namespace Jellyfin.Api.Migrations +{ + /// + /// A static class for reflection type functions. Temporary until web changed. + /// + public static class ClassMigrationHelper + { + /// + /// Extension for 'Object' that copies the properties to a destination object. + /// + /// The source. + /// The destination. + public static void CopyProperties(this object source, object destination) + { + // If any this null throw an exception + if (source == null || destination == null) + { + throw new Exception("Source or/and Destination Objects are null"); + } + + // Getting the Types of the objects + Type typeDest = destination.GetType(); + Type typeSrc = source.GetType(); + + // Iterate the Properties of the source instance and populate them from their desination counterparts. + PropertyInfo[] srcProps = typeSrc.GetProperties(); + foreach (PropertyInfo srcProp in srcProps) + { + if (!srcProp.CanRead) + { + continue; + } + + var targetProperty = typeDest.GetProperty(srcProp.Name); + if (targetProperty == null) + { + continue; + } + + if (!targetProperty.CanWrite) + { + continue; + } + + var obj = targetProperty.GetSetMethod(true); + if (obj != null && obj.IsPrivate) + { + continue; + } + + var target = targetProperty.GetSetMethod(); + if (target != null && (target.Attributes & MethodAttributes.Static) != 0) + { + continue; + } + + if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)) + { + continue; + } + + // Passed all tests, lets set the value + targetProperty.SetValue(destination, srcProp.GetValue(source, null), null); + } + } + } +} diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index c7fbfa4d02..6bf6f383fc 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Jellyfin.Networking.Configuration; using Jellyfin.Server.Middleware; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Builder; @@ -24,8 +25,8 @@ namespace Jellyfin.Server.Extensions // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. - var baseUrl = serverConfigurationManager.Configuration.BaseUrl.Trim('/'); - var apiDocBaseUrl = serverConfigurationManager.Configuration.BaseUrl; + var baseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl.Trim('/'); + var apiDocBaseUrl = serverConfigurationManager.GetNetworkConfiguration().BaseUrl; if (!string.IsNullOrEmpty(baseUrl)) { baseUrl += '/'; diff --git a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs index 9316737bdf..c23da2fd63 100644 --- a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs +++ b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; @@ -42,7 +43,7 @@ namespace Jellyfin.Server.Middleware public async Task Invoke(HttpContext httpContext, IServerConfigurationManager serverConfigurationManager) { var localPath = httpContext.Request.Path.ToString(); - var baseUrlPrefix = serverConfigurationManager.Configuration.BaseUrl; + var baseUrlPrefix = serverConfigurationManager.GetNetworkConfiguration().BaseUrl; if (string.Equals(localPath, baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, baseUrlPrefix, StringComparison.OrdinalIgnoreCase) diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 0713d97d65..6f636819fc 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,5 +1,6 @@ using System.Net; using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -42,7 +43,7 @@ namespace Jellyfin.Server.Middleware var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; - if (serverConfigurationManager.Configuration.EnableRemoteAccess) + if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. @@ -52,7 +53,7 @@ namespace Jellyfin.Server.Middleware { // remoteAddressFilter is a whitelist or blacklist. bool isListed = remoteAddressFilter.Contains(remoteIp); - if (!serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist) + if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist) { // Black list, so flip over. isListed = !isListed; diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 1ef460bd76..1f4e80053d 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -2,6 +2,7 @@ using System; using System.Linq; using System.Net; using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; @@ -37,7 +38,7 @@ namespace Jellyfin.Server.Middleware { var host = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; - if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.Configuration.EnableRemoteAccess) + if (!networkManager.IsInLocalNetwork(host) && !serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess) { return; } diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 2f4620aa63..3484598b8c 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -2,6 +2,7 @@ using System; using System.ComponentModel; using System.Net.Http.Headers; using Jellyfin.Api.TypeConverters; +using Jellyfin.Networking.Configuration; using Jellyfin.Server.Extensions; using Jellyfin.Server.Implementations; using Jellyfin.Server.Middleware; @@ -52,7 +53,7 @@ namespace Jellyfin.Server { options.HttpsPort = _serverApplicationHost.HttpsPort; }); - services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.Configuration.KnownProxies); + services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration().KnownProxies); services.AddJellyfinApiSwagger(); @@ -96,7 +97,7 @@ namespace Jellyfin.Server app.UseBaseUrlRedirection(); // Wrap rest of configuration so everything only listens on BaseUrl. - app.Map(_serverConfigurationManager.Configuration.BaseUrl, mainApp => + app.Map(_serverConfigurationManager.GetNetworkConfiguration().BaseUrl, mainApp => { if (env.IsDevelopment()) { diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index fe726090d6..7bcd4d8ed3 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -50,8 +50,9 @@ namespace MediaBrowser.Common.Configuration /// Gets the configuration. /// /// The key. + /// Optional parameter containing the key object to create, if it hasn't been registered. /// System.Object. - object GetConfiguration(string key); + object GetConfiguration(string key, Type objectType = null); /// /// Gets the type of the configuration. From 39754b840dc818f6c809c37813208e1ff06a50a9 Mon Sep 17 00:00:00 2001 From: Greenback Date: Thu, 8 Oct 2020 19:16:47 +0100 Subject: [PATCH 0078/1930] minor fixes --- .../Configuration/NetworkConfiguration.cs | 4 ++-- Jellyfin.Networking/Manager/NetworkManager.cs | 19 ++++++++++--------- .../Configuration/ServerConfiguration.cs | 4 ++-- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 38f11153ab..aa75ac305d 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -105,12 +105,12 @@ namespace Jellyfin.Networking.Configuration public string UDPPortRange { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether gets or sets IPV6 capability.. + /// Gets or sets a value indicating whether IPV6 capability is enabled. /// public bool EnableIPV6 { get; set; } = false; /// - /// Gets or sets a value indicating whether gets or sets IPV4 capability.. + /// Gets or sets a value indicating whether IPV6 capability is enabled. /// public bool EnableIPV4 { get; set; } = true; diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 491fe824da..a094212d37 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -346,7 +346,7 @@ namespace Jellyfin.Networking.Manager if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) { - _logger.LogWarning("IPv4 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected."); + _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } isExternal = !IsInLocalNetwork(source); @@ -872,28 +872,29 @@ namespace Jellyfin.Networking.Manager private void InitialiseBind(NetworkConfiguration config) { - string[] ba = config.LocalNetworkAddresses; + string[] lanAddresses = config.LocalNetworkAddresses; // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 - if (ba.Length == 1 && ba[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) + if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) { - ba = ba[0].Split(','); + lanAddresses = lanAddresses[0].Split(','); } + // TODO: end fix. // TODO: end fix. // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. if (config.IgnoreVirtualInterfaces) { - var newList = ba.ToList(); + var newList = lanAddresses.ToList(); newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList()); - ba = newList.ToArray(); + lanAddresses = newList.ToArray(); } // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(ba).Union(_interfaceAddresses); - _bindExclusions = CreateIPCollection(ba, true).Union(_interfaceAddresses); + _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); + _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); } @@ -923,7 +924,7 @@ namespace Jellyfin.Networking.Manager // If no LAN addresses are specified - all private subnets are deemed to be the LAN _usingPrivateAddresses = _lanSubnets.Count == 0; - // NOTE: The order of the commands in this statement matters. + // NOTE: The order of the commands in this statement matters, otherwise the lists won't initialise correctly. if (_usingPrivateAddresses) { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 86b7c4c3d6..a40105212b 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -99,12 +99,12 @@ namespace MediaBrowser.Model.Configuration public string UDPPortRange { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// Gets or sets a value indicating whether IPV6 capability is enabled. /// public bool EnableIPV6 { get; set; } = false; /// - /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// Gets or sets a value indicating whether IPV4 capability is enabled. /// public bool EnableIPV4 { get; set; } = true; From 8a4f81c9a7a03c6a45a8a9331f71ba06ae0ce521 Mon Sep 17 00:00:00 2001 From: Greenback Date: Fri, 9 Oct 2020 14:04:55 +0100 Subject: [PATCH 0079/1930] Updated networkmanager to the lastest. --- Jellyfin.Networking/Manager/NetworkManager.cs | 254 ++++++++---------- 1 file changed, 113 insertions(+), 141 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index a094212d37..26614c85e0 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -45,6 +45,8 @@ namespace Jellyfin.Networking.Manager private readonly IConfigurationManager _configurationManager; + private readonly object _eventFireLock; + /// /// Holds the bind address overrides. /// @@ -106,6 +108,7 @@ namespace Jellyfin.Networking.Manager _macAddresses = new List(); _interfaceNames = new Dictionary(); _publishedServerUrls = new Dictionary(); + _eventFireLock = new object(); NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; @@ -158,10 +161,7 @@ namespace Jellyfin.Networking.Manager public List GetMacAddresses() { // Populated in construction - so always has values. - lock (_intLock) - { - return _macAddresses.ToList(); - } + return _macAddresses.ToList(); } /// @@ -174,10 +174,7 @@ namespace Jellyfin.Networking.Manager _ => IPAddress.None }; - lock (_intLock) - { - return _internalInterfaces.Where(i => i.Address.Equals(address) && i.Tag < 0).Any(); - } + return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); } /// @@ -224,14 +221,14 @@ namespace Jellyfin.Networking.Manager try { - if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) + if (v.StartsWith('[') && v.EndsWith(']')) { if (bracketed) { - AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); + AddToCollection(col, v.Substring(1, v.Length - 2)); } } - else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) + else if (v.StartsWith('!')) { if (bracketed) { @@ -255,42 +252,39 @@ namespace Jellyfin.Networking.Manager /// public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) { - lock (_intLock) + int count = _bindAddresses.Count; + + if (count == 0) { - int count = _bindAddresses.Count; - - if (count == 0) + if (_bindExclusions.Count > 0) { - if (_bindExclusions.Count > 0) - { - // Return all the interfaces except the ones specifically excluded. - return _interfaceAddresses.Exclude(_bindExclusions); - } - - if (individualInterfaces) - { - return new NetCollection(_interfaceAddresses); - } - - // No bind address and no exclusions, so listen on all interfaces. - NetCollection result = new NetCollection(); - - if (IsIP4Enabled) - { - result.Add(IPAddress.Any); - } - - if (IsIP6Enabled) - { - result.Add(IPAddress.IPv6Any); - } - - return result; + // Return all the interfaces except the ones specifically excluded. + return _interfaceAddresses.Exclude(_bindExclusions); } - // Remove any excluded bind interfaces. - return _bindAddresses.Exclude(_bindExclusions); + if (individualInterfaces) + { + return new NetCollection(_interfaceAddresses); + } + + // No bind address and no exclusions, so listen on all interfaces. + NetCollection result = new NetCollection(); + + if (IsIP4Enabled) + { + result.Add(IPAddress.Any); + } + + if (IsIP6Enabled) + { + result.Add(IPAddress.IPv6Any); + } + + return result; } + + // Remove any excluded bind interfaces. + return _bindAddresses.Exclude(_bindExclusions); } /// @@ -351,84 +345,78 @@ namespace Jellyfin.Networking.Manager isExternal = !IsInLocalNetwork(source); - if (MatchesPublishedServerUrl(source, isExternal, out string result, out port)) + if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) { - _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, result, port); - return result; + _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, res, port); + return res; } } - _logger.LogDebug("GetBindInterface: Souce: {0}, External: {1}:", haveSource, isExternal); + _logger.LogDebug("GetBindInterface: Source: {0}, External: {1}:", haveSource, isExternal); // No preference given, so move on to bind addresses. - lock (_intLock) + if (MatchesBindInterface(source, isExternal, out string result)) { - if (MatchesBindInterface(source, isExternal, out string result)) - { - return result; - } - - if (isExternal && MatchesExternalInterface(source, out result)) - { - return result; - } - - // Get the first LAN interface address that isn't a loopback. - var interfaces = new NetCollection(_interfaceAddresses - .Exclude(_bindExclusions) - .Where(p => IsInLocalNetwork(p)) - .OrderBy(p => p.Tag)); - - if (interfaces.Count > 0) - { - if (haveSource) - { - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in interfaces) - { - if (intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result); - return result; - } - } - } - - result = FormatIP6String(interfaces.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result); - return result; - } - - // There isn't any others, so we'll use the loopback. - result = IsIP6Enabled ? "::" : "127.0.0.1"; - _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result); return result; } + + if (isExternal && MatchesExternalInterface(source, out result)) + { + return result; + } + + // Get the first LAN interface address that isn't a loopback. + var interfaces = new NetCollection(_interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => IsInLocalNetwork(p)) + .OrderBy(p => p.Tag)); + + if (interfaces.Count > 0) + { + if (haveSource) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in interfaces) + { + if (intf.Contains(source)) + { + result = FormatIP6String(intf.Address); + _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result); + return result; + } + } + } + + result = FormatIP6String(interfaces.First().Address); + _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result); + return result; + } + + // There isn't any others, so we'll use the loopback. + result = IsIP6Enabled ? "::" : "127.0.0.1"; + _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result); + return result; } /// public NetCollection GetInternalBindAddresses() { - lock (_intLock) + int count = _bindAddresses.Count; + + if (count == 0) { - int count = _bindAddresses.Count; - - if (count == 0) + if (_bindExclusions.Count > 0) { - if (_bindExclusions.Count > 0) - { - // Return all the internal interfaces except the ones excluded. - return new NetCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); - } - - // No bind address, so return all internal interfaces. - return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + // Return all the internal interfaces except the ones excluded. + return new NetCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); } - return new NetCollection(_bindAddresses); + // No bind address, so return all internal interfaces. + return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } + + return new NetCollection(_bindAddresses); } /// @@ -450,11 +438,8 @@ namespace Jellyfin.Networking.Manager return true; } - lock (_intLock) - { - // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); - } + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); } /// @@ -462,10 +447,7 @@ namespace Jellyfin.Networking.Manager { if (IPHost.TryParse(address, out IPHost ep)) { - lock (_intLock) - { - return _lanSubnets.Contains(ep) && !_excludedSubnets.Contains(ep); - } + return _lanSubnets.Contains(ep) && !_excludedSubnets.Contains(ep); } return false; @@ -485,11 +467,8 @@ namespace Jellyfin.Networking.Manager return true; } - lock (_intLock) - { - // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); - } + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); } /// @@ -514,33 +493,24 @@ namespace Jellyfin.Networking.Manager /// public bool IsExcludedInterface(IPAddress address) { - lock (_intLock) - { - return _bindExclusions.Contains(address); - } + return _bindExclusions.Contains(address); } /// public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) { - lock (_intLock) + if (filter == null) { - if (filter == null) - { - return NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)); - } - - return _lanSubnets.Exclude(filter); + return NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)); } + + return _lanSubnets.Exclude(filter); } /// public bool IsValidInterfaceAddress(IPAddress address) { - lock (_intLock) - { - return _interfaceAddresses.Contains(address); - } + return _interfaceAddresses.Contains(address); } /// @@ -583,7 +553,7 @@ namespace Jellyfin.Networking.Manager { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); - IsIP4Enabled = Socket.OSSupportsIPv6 && config.EnableIPV4; + IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4; IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; if (!IsIP6Enabled && !IsIP4Enabled) @@ -761,7 +731,7 @@ namespace Jellyfin.Networking.Manager /// Handler for network change events. /// /// Sender. - /// Network availablity information. + /// Network availability information. private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { _logger.LogDebug("Network availability changed."); @@ -805,12 +775,15 @@ namespace Jellyfin.Networking.Manager /// private void OnNetworkChanged() { - if (!_eventfire) + lock (_eventFireLock) { - _logger.LogDebug("Network Address Change Event."); - // As network events tend to fire one after the other only fire once every second. - _eventfire = true; - _ = OnNetworkChangeAsync(); + if (!_eventfire) + { + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + OnNetworkChangeAsync().GetAwaiter().GetResult(); + } } } @@ -881,8 +854,7 @@ namespace Jellyfin.Networking.Manager lanAddresses = lanAddresses[0].Split(','); } - // TODO: end fix. - // TODO: end fix. + // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334 // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. if (config.IgnoreVirtualInterfaces) @@ -924,7 +896,7 @@ namespace Jellyfin.Networking.Manager // If no LAN addresses are specified - all private subnets are deemed to be the LAN _usingPrivateAddresses = _lanSubnets.Count == 0; - // NOTE: The order of the commands in this statement matters, otherwise the lists won't initialise correctly. + // NOTE: The order of the commands in this statement matters. if (_usingPrivateAddresses) { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); @@ -975,7 +947,7 @@ namespace Jellyfin.Networking.Manager /// /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. - /// Generate a list of all active mac addresses that aren't loopback addreses. + /// Generate a list of all active mac addresses that aren't loopback addresses. /// private void InitialiseInterfaces() { From 3119acd5027509b384d7e122dba20b9212ebddf8 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 9 Oct 2020 07:43:02 -0600 Subject: [PATCH 0080/1930] Remove tvdb plugin from server. --- .../ApplicationHost.cs | 2 - .../Configuration/PluginConfiguration.cs | 10 - .../Plugins/TheTvdb/Plugin.cs | 29 -- .../Plugins/TheTvdb/TvdbClientManager.cs | 288 ------------ .../TheTvdb/TvdbEpisodeImageProvider.cs | 130 ------ .../Plugins/TheTvdb/TvdbEpisodeProvider.cs | 261 ----------- .../TheTvdb/TvdbPersonImageProvider.cs | 113 ----- .../TheTvdb/TvdbSeasonImageProvider.cs | 155 ------- .../TheTvdb/TvdbSeriesImageProvider.cs | 153 ------- .../Plugins/TheTvdb/TvdbSeriesProvider.cs | 417 ------------------ .../Plugins/TheTvdb/TvdbUtils.cs | 39 -- .../TV/TvdbEpisodeExternalId.cs | 28 -- MediaBrowser.Providers/TV/TvdbExternalId.cs | 28 -- .../TV/TvdbSeasonExternalId.cs | 28 -- MediaBrowser.Providers/TV/Zap2ItExternalId.cs | 1 - 15 files changed, 1682 deletions(-) delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/Configuration/PluginConfiguration.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/Plugin.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeasonImageProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesImageProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs delete mode 100644 MediaBrowser.Providers/Plugins/TheTvdb/TvdbUtils.cs delete mode 100644 MediaBrowser.Providers/TV/TvdbEpisodeExternalId.cs delete mode 100644 MediaBrowser.Providers/TV/TvdbExternalId.cs delete mode 100644 MediaBrowser.Providers/TV/TvdbSeasonExternalId.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0c8b0339bd..8f27445a67 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -96,7 +96,6 @@ using MediaBrowser.Model.System; using MediaBrowser.Model.Tasks; using MediaBrowser.Providers.Chapters; using MediaBrowser.Providers.Manager; -using MediaBrowser.Providers.Plugins.TheTvdb; using MediaBrowser.Providers.Plugins.Tmdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; @@ -537,7 +536,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(_fileSystemManager); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(_networkManager); diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/TheTvdb/Configuration/PluginConfiguration.cs deleted file mode 100644 index 690a52c4d3..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/Configuration/PluginConfiguration.cs +++ /dev/null @@ -1,10 +0,0 @@ -#pragma warning disable CS1591 - -using MediaBrowser.Model.Plugins; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class PluginConfiguration : BasePluginConfiguration - { - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/Plugin.cs b/MediaBrowser.Providers/Plugins/TheTvdb/Plugin.cs deleted file mode 100644 index e7079ed3cd..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/Plugin.cs +++ /dev/null @@ -1,29 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Plugins; -using MediaBrowser.Model.Serialization; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class Plugin : BasePlugin - { - public static Plugin Instance { get; private set; } - - public override Guid Id => new Guid("a677c0da-fac5-4cde-941a-7134223f14c8"); - - public override string Name => "TheTVDB"; - - public override string Description => "Get metadata for movies and other video content from TheTVDB."; - - // TODO remove when plugin removed from server. - public override string ConfigurationFileName => "Jellyfin.Plugin.TheTvdb.xml"; - - public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) - : base(applicationPaths, xmlSerializer) - { - Instance = this; - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs deleted file mode 100644 index 5e9a4a2252..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs +++ /dev/null @@ -1,288 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using Microsoft.Extensions.Caching.Memory; -using TvDbSharper; -using TvDbSharper.Dto; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbClientManager - { - private const string DefaultLanguage = "en"; - - private readonly IMemoryCache _cache; - private readonly TvDbClient _tvDbClient; - private DateTime _tokenCreatedAt; - - public TvdbClientManager(IMemoryCache memoryCache) - { - _cache = memoryCache; - _tvDbClient = new TvDbClient(); - } - - private TvDbClient TvDbClient - { - get - { - if (string.IsNullOrEmpty(_tvDbClient.Authentication.Token)) - { - _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey).GetAwaiter().GetResult(); - _tokenCreatedAt = DateTime.Now; - } - - // Refresh if necessary - if (_tokenCreatedAt < DateTime.Now.Subtract(TimeSpan.FromHours(20))) - { - try - { - _tvDbClient.Authentication.RefreshTokenAsync().GetAwaiter().GetResult(); - } - catch - { - _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey).GetAwaiter().GetResult(); - } - - _tokenCreatedAt = DateTime.Now; - } - - return _tvDbClient; - } - } - - public Task> GetSeriesByNameAsync(string name, string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("series", name, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByNameAsync(name, cancellationToken)); - } - - public Task> GetSeriesByIdAsync(int tvdbId, string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("series", tvdbId, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetAsync(tvdbId, cancellationToken)); - } - - public Task> GetEpisodesAsync(int episodeTvdbId, string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("episode", episodeTvdbId, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Episodes.GetAsync(episodeTvdbId, cancellationToken)); - } - - public Task> GetSeriesByImdbIdAsync( - string imdbId, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("series", imdbId, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByImdbIdAsync(imdbId, cancellationToken)); - } - - public Task> GetSeriesByZap2ItIdAsync( - string zap2ItId, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("series", zap2ItId, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByZap2ItIdAsync(zap2ItId, cancellationToken)); - } - - public Task> GetActorsAsync( - int tvdbId, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("actors", tvdbId, language); - return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetActorsAsync(tvdbId, cancellationToken)); - } - - public Task> GetImagesAsync( - int tvdbId, - ImagesQuery imageQuery, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("images", tvdbId, language, imageQuery); - return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesAsync(tvdbId, imageQuery, cancellationToken)); - } - - public Task> GetLanguagesAsync(CancellationToken cancellationToken) - { - return TryGetValue("languages", null, () => TvDbClient.Languages.GetAllAsync(cancellationToken)); - } - - public Task> GetSeriesEpisodeSummaryAsync( - int tvdbId, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey("seriesepisodesummary", tvdbId, language); - return TryGetValue(cacheKey, language, - () => TvDbClient.Series.GetEpisodesSummaryAsync(tvdbId, cancellationToken)); - } - - public Task> GetEpisodesPageAsync( - int tvdbId, - int page, - EpisodeQuery episodeQuery, - string language, - CancellationToken cancellationToken) - { - var cacheKey = GenerateKey(language, tvdbId, episodeQuery); - - return TryGetValue(cacheKey, language, - () => TvDbClient.Series.GetEpisodesAsync(tvdbId, page, episodeQuery, cancellationToken)); - } - - public Task GetEpisodeTvdbId( - EpisodeInfo searchInfo, - string language, - CancellationToken cancellationToken) - { - searchInfo.SeriesProviderIds.TryGetValue(nameof(MetadataProvider.Tvdb), - out var seriesTvdbId); - - var episodeQuery = new EpisodeQuery(); - - // Prefer SxE over premiere date as it is more robust - if (searchInfo.IndexNumber.HasValue && searchInfo.ParentIndexNumber.HasValue) - { - switch (searchInfo.SeriesDisplayOrder) - { - case "dvd": - episodeQuery.DvdEpisode = searchInfo.IndexNumber.Value; - episodeQuery.DvdSeason = searchInfo.ParentIndexNumber.Value; - break; - case "absolute": - episodeQuery.AbsoluteNumber = searchInfo.IndexNumber.Value; - break; - default: - // aired order - episodeQuery.AiredEpisode = searchInfo.IndexNumber.Value; - episodeQuery.AiredSeason = searchInfo.ParentIndexNumber.Value; - break; - } - } - else if (searchInfo.PremiereDate.HasValue) - { - // tvdb expects yyyy-mm-dd format - episodeQuery.FirstAired = searchInfo.PremiereDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); - } - - return GetEpisodeTvdbId(Convert.ToInt32(seriesTvdbId, CultureInfo.InvariantCulture), episodeQuery, language, cancellationToken); - } - - public async Task GetEpisodeTvdbId( - int seriesTvdbId, - EpisodeQuery episodeQuery, - string language, - CancellationToken cancellationToken) - { - var episodePage = - await GetEpisodesPageAsync(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken) - .ConfigureAwait(false); - return episodePage.Data.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture); - } - - public Task> GetEpisodesPageAsync( - int tvdbId, - EpisodeQuery episodeQuery, - string language, - CancellationToken cancellationToken) - { - return GetEpisodesPageAsync(tvdbId, 1, episodeQuery, language, cancellationToken); - } - - public async IAsyncEnumerable GetImageKeyTypesForSeriesAsync(int tvdbId, string language, [EnumeratorCancellation] CancellationToken cancellationToken) - { - var cacheKey = GenerateKey(nameof(TvDbClient.Series.GetImagesSummaryAsync), tvdbId); - var imagesSummary = await TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesSummaryAsync(tvdbId, cancellationToken)).ConfigureAwait(false); - - if (imagesSummary.Data.Fanart > 0) - { - yield return KeyType.Fanart; - } - - if (imagesSummary.Data.Series > 0) - { - yield return KeyType.Series; - } - - if (imagesSummary.Data.Poster > 0) - { - yield return KeyType.Poster; - } - } - - public async IAsyncEnumerable GetImageKeyTypesForSeasonAsync(int tvdbId, string language, [EnumeratorCancellation] CancellationToken cancellationToken) - { - var cacheKey = GenerateKey(nameof(TvDbClient.Series.GetImagesSummaryAsync), tvdbId); - var imagesSummary = await TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesSummaryAsync(tvdbId, cancellationToken)).ConfigureAwait(false); - - if (imagesSummary.Data.Season > 0) - { - yield return KeyType.Season; - } - - if (imagesSummary.Data.Fanart > 0) - { - yield return KeyType.Fanart; - } - - // TODO seasonwide is not supported in TvDbSharper - } - - private async Task TryGetValue(string key, string language, Func> resultFactory) - { - if (_cache.TryGetValue(key, out T cachedValue)) - { - return cachedValue; - } - - _tvDbClient.AcceptedLanguage = TvdbUtils.NormalizeLanguage(language) ?? DefaultLanguage; - var result = await resultFactory.Invoke().ConfigureAwait(false); - _cache.Set(key, result, TimeSpan.FromHours(1)); - return result; - } - - private static string GenerateKey(params object[] objects) - { - var key = string.Empty; - - foreach (var obj in objects) - { - var objType = obj.GetType(); - if (objType.IsPrimitive || objType == typeof(string)) - { - key += obj + ";"; - } - else - { - foreach (PropertyInfo propertyInfo in objType.GetProperties()) - { - var currentValue = propertyInfo.GetValue(obj, null); - if (currentValue == null) - { - continue; - } - - key += propertyInfo.Name + "=" + currentValue + ";"; - } - } - } - - return key; - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs deleted file mode 100644 index 50a876d6c5..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeImageProvider.cs +++ /dev/null @@ -1,130 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; -using TvDbSharper.Dto; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbEpisodeImageProvider : IRemoteImageProvider - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbEpisodeImageProvider(IHttpClientFactory httpClientFactory, ILogger logger, TvdbClientManager tvdbClientManager) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _tvdbClientManager = tvdbClientManager; - } - - public string Name => "TheTVDB"; - - public bool Supports(BaseItem item) - { - return item is Episode; - } - - public IEnumerable GetSupportedImages(BaseItem item) - { - return new List - { - ImageType.Primary - }; - } - - public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) - { - var episode = (Episode)item; - var series = episode.Series; - var imageResult = new List(); - var language = item.GetPreferredMetadataLanguage(); - if (series != null && TvdbSeriesProvider.IsValidSeries(series.ProviderIds)) - { - // Process images - try - { - string episodeTvdbId = null; - - if (episode.IndexNumber.HasValue && episode.ParentIndexNumber.HasValue) - { - var episodeInfo = new EpisodeInfo - { - IndexNumber = episode.IndexNumber.Value, - ParentIndexNumber = episode.ParentIndexNumber.Value, - SeriesProviderIds = series.ProviderIds, - SeriesDisplayOrder = series.DisplayOrder - }; - - episodeTvdbId = await _tvdbClientManager - .GetEpisodeTvdbId(episodeInfo, language, cancellationToken).ConfigureAwait(false); - } - - if (string.IsNullOrEmpty(episodeTvdbId)) - { - _logger.LogError( - "Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}", - episode.ParentIndexNumber, - episode.IndexNumber, - series.GetProviderId(MetadataProvider.Tvdb)); - return imageResult; - } - - var episodeResult = - await _tvdbClientManager - .GetEpisodesAsync(Convert.ToInt32(episodeTvdbId, CultureInfo.InvariantCulture), language, cancellationToken) - .ConfigureAwait(false); - - var image = GetImageInfo(episodeResult.Data); - if (image != null) - { - imageResult.Add(image); - } - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve episode images for series {TvDbId}", series.GetProviderId(MetadataProvider.Tvdb)); - } - } - - return imageResult; - } - - private RemoteImageInfo GetImageInfo(EpisodeRecord episode) - { - if (string.IsNullOrEmpty(episode.Filename)) - { - return null; - } - - return new RemoteImageInfo - { - Width = Convert.ToInt32(episode.ThumbWidth, CultureInfo.InvariantCulture), - Height = Convert.ToInt32(episode.ThumbHeight, CultureInfo.InvariantCulture), - ProviderName = Name, - Url = TvdbUtils.BannerUrl + episode.Filename, - Type = ImageType.Primary - }; - } - - public int Order => 0; - - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs deleted file mode 100644 index 5fa8a3e1ca..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbEpisodeProvider.cs +++ /dev/null @@ -1,261 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; -using TvDbSharper.Dto; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - /// - /// Class RemoteEpisodeProvider. - /// - public class TvdbEpisodeProvider : IRemoteMetadataProvider, IHasOrder - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbEpisodeProvider(IHttpClientFactory httpClientFactory, ILogger logger, TvdbClientManager tvdbClientManager) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _tvdbClientManager = tvdbClientManager; - } - - public async Task> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken) - { - var list = new List(); - - // Either an episode number or date must be provided; and the dictionary of provider ids must be valid - if ((searchInfo.IndexNumber == null && searchInfo.PremiereDate == null) - || !TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds)) - { - return list; - } - - var metadataResult = await GetEpisode(searchInfo, cancellationToken).ConfigureAwait(false); - - if (!metadataResult.HasMetadata) - { - return list; - } - - var item = metadataResult.Item; - - list.Add(new RemoteSearchResult - { - IndexNumber = item.IndexNumber, - Name = item.Name, - ParentIndexNumber = item.ParentIndexNumber, - PremiereDate = item.PremiereDate, - ProductionYear = item.ProductionYear, - ProviderIds = item.ProviderIds, - SearchProviderName = Name, - IndexNumberEnd = item.IndexNumberEnd - }); - - return list; - } - - public string Name => "TheTVDB"; - - public async Task> GetMetadata(EpisodeInfo searchInfo, CancellationToken cancellationToken) - { - var result = new MetadataResult - { - QueriedById = true - }; - - if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds) && - (searchInfo.IndexNumber.HasValue || searchInfo.PremiereDate.HasValue)) - { - result = await GetEpisode(searchInfo, cancellationToken).ConfigureAwait(false); - } - else - { - _logger.LogDebug("No series identity found for {EpisodeName}", searchInfo.Name); - } - - return result; - } - - private async Task> GetEpisode(EpisodeInfo searchInfo, CancellationToken cancellationToken) - { - var result = new MetadataResult - { - QueriedById = true - }; - - string seriesTvdbId = searchInfo.GetProviderId(MetadataProvider.Tvdb); - string episodeTvdbId = null; - try - { - episodeTvdbId = await _tvdbClientManager - .GetEpisodeTvdbId(searchInfo, searchInfo.MetadataLanguage, cancellationToken) - .ConfigureAwait(false); - if (string.IsNullOrEmpty(episodeTvdbId)) - { - _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}", - searchInfo.ParentIndexNumber, searchInfo.IndexNumber, seriesTvdbId); - return result; - } - - var episodeResult = await _tvdbClientManager.GetEpisodesAsync( - Convert.ToInt32(episodeTvdbId), searchInfo.MetadataLanguage, - cancellationToken).ConfigureAwait(false); - - result = MapEpisodeToResult(searchInfo, episodeResult.Data); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve episode with id {EpisodeTvDbId}, series id {SeriesTvdbId}", episodeTvdbId, seriesTvdbId); - } - - return result; - } - - private static MetadataResult MapEpisodeToResult(EpisodeInfo id, EpisodeRecord episode) - { - var result = new MetadataResult - { - HasMetadata = true, - Item = new Episode - { - IndexNumber = id.IndexNumber, - ParentIndexNumber = id.ParentIndexNumber, - IndexNumberEnd = id.IndexNumberEnd, - AirsBeforeEpisodeNumber = episode.AirsBeforeEpisode, - AirsAfterSeasonNumber = episode.AirsAfterSeason, - AirsBeforeSeasonNumber = episode.AirsBeforeSeason, - Name = episode.EpisodeName, - Overview = episode.Overview, - CommunityRating = (float?)episode.SiteRating, - OfficialRating = episode.ContentRating, - } - }; - result.ResetPeople(); - - var item = result.Item; - item.SetProviderId(MetadataProvider.Tvdb, episode.Id.ToString()); - item.SetProviderId(MetadataProvider.Imdb, episode.ImdbId); - - if (string.Equals(id.SeriesDisplayOrder, "dvd", StringComparison.OrdinalIgnoreCase)) - { - item.IndexNumber = Convert.ToInt32(episode.DvdEpisodeNumber ?? episode.AiredEpisodeNumber); - item.ParentIndexNumber = episode.DvdSeason ?? episode.AiredSeason; - } - else if (string.Equals(id.SeriesDisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase)) - { - if (episode.AbsoluteNumber.GetValueOrDefault() != 0) - { - item.IndexNumber = episode.AbsoluteNumber; - } - } - else if (episode.AiredEpisodeNumber.HasValue) - { - item.IndexNumber = episode.AiredEpisodeNumber; - } - else if (episode.AiredSeason.HasValue) - { - item.ParentIndexNumber = episode.AiredSeason; - } - - if (DateTime.TryParse(episode.FirstAired, out var date)) - { - // dates from tvdb are UTC but without offset or Z - item.PremiereDate = date; - item.ProductionYear = date.Year; - } - - foreach (var director in episode.Directors) - { - result.AddPerson(new PersonInfo - { - Name = director, - Type = PersonType.Director - }); - } - - // GuestStars is a weird list of names and roles - // Example: - // 1: Some Actor (Role1 - // 2: Role2 - // 3: Role3) - // 4: Another Actor (Role1 - // ... - for (var i = 0; i < episode.GuestStars.Length; ++i) - { - var currentActor = episode.GuestStars[i]; - var roleStartIndex = currentActor.IndexOf('(', StringComparison.Ordinal); - - if (roleStartIndex == -1) - { - result.AddPerson(new PersonInfo - { - Type = PersonType.GuestStar, - Name = currentActor, - Role = string.Empty - }); - continue; - } - - var roles = new List { currentActor.Substring(roleStartIndex + 1) }; - - // Fetch all roles - for (var j = i + 1; j < episode.GuestStars.Length; ++j) - { - var currentRole = episode.GuestStars[j]; - var roleEndIndex = currentRole.IndexOf(')', StringComparison.Ordinal); - - if (roleEndIndex == -1) - { - roles.Add(currentRole); - continue; - } - - roles.Add(currentRole.TrimEnd(')')); - // Update the outer index (keep in mind it adds 1 after the iteration) - i = j; - break; - } - - result.AddPerson(new PersonInfo - { - Type = PersonType.GuestStar, - Name = currentActor.Substring(0, roleStartIndex).Trim(), - Role = string.Join(", ", roles) - }); - } - - foreach (var writer in episode.Writers) - { - result.AddPerson(new PersonInfo - { - Name = writer, - Type = PersonType.Writer - }); - } - - result.ResultLanguage = episode.Language.EpisodeName; - return result; - } - - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - - public int Order => 0; - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs deleted file mode 100644 index dc3c60dee0..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbPersonImageProvider.cs +++ /dev/null @@ -1,113 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbPersonImageProvider : IRemoteImageProvider, IHasOrder - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly ILibraryManager _libraryManager; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbPersonImageProvider(ILibraryManager libraryManager, IHttpClientFactory httpClientFactory, ILogger logger, TvdbClientManager tvdbClientManager) - { - _libraryManager = libraryManager; - _httpClientFactory = httpClientFactory; - _logger = logger; - _tvdbClientManager = tvdbClientManager; - } - - /// - public string Name => "TheTVDB"; - - /// - public int Order => 1; - - /// - public bool Supports(BaseItem item) => item is Person; - - /// - public IEnumerable GetSupportedImages(BaseItem item) - { - yield return ImageType.Primary; - } - - /// - public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) - { - var seriesWithPerson = _libraryManager.GetItemList(new InternalItemsQuery - { - IncludeItemTypes = new[] { typeof(Series).Name }, - PersonIds = new[] { item.Id }, - DtoOptions = new DtoOptions(false) - { - EnableImages = false - } - }).Cast() - .Where(i => TvdbSeriesProvider.IsValidSeries(i.ProviderIds)) - .ToList(); - - var infos = (await Task.WhenAll(seriesWithPerson.Select(async i => - await GetImageFromSeriesData(i, item.Name, cancellationToken).ConfigureAwait(false))) - .ConfigureAwait(false)) - .Where(i => i != null) - .Take(1); - - return infos; - } - - private async Task GetImageFromSeriesData(Series series, string personName, CancellationToken cancellationToken) - { - var tvdbId = Convert.ToInt32(series.GetProviderId(MetadataProvider.Tvdb)); - - try - { - var actorsResult = await _tvdbClientManager - .GetActorsAsync(tvdbId, series.GetPreferredMetadataLanguage(), cancellationToken) - .ConfigureAwait(false); - var actor = actorsResult.Data.FirstOrDefault(a => - string.Equals(a.Name, personName, StringComparison.OrdinalIgnoreCase) && - !string.IsNullOrEmpty(a.Image)); - if (actor == null) - { - return null; - } - - return new RemoteImageInfo - { - Url = TvdbUtils.BannerUrl + actor.Image, - Type = ImageType.Primary, - ProviderName = Name - }; - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve actor {ActorName} from series {SeriesTvdbId}", personName, tvdbId); - return null; - } - } - - /// - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeasonImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeasonImageProvider.cs deleted file mode 100644 index 49576d488d..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeasonImageProvider.cs +++ /dev/null @@ -1,155 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; -using TvDbSharper.Dto; -using RatingType = MediaBrowser.Model.Dto.RatingType; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbSeasonImageProvider : IRemoteImageProvider, IHasOrder - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbSeasonImageProvider(IHttpClientFactory httpClientFactory, ILogger logger, TvdbClientManager tvdbClientManager) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _tvdbClientManager = tvdbClientManager; - } - - public string Name => ProviderName; - - public static string ProviderName => "TheTVDB"; - - public bool Supports(BaseItem item) - { - return item is Season; - } - - public IEnumerable GetSupportedImages(BaseItem item) - { - return new List - { - ImageType.Primary, - ImageType.Banner, - ImageType.Backdrop - }; - } - - public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) - { - var season = (Season)item; - var series = season.Series; - - if (series == null || !season.IndexNumber.HasValue || !TvdbSeriesProvider.IsValidSeries(series.ProviderIds)) - { - return Array.Empty(); - } - - var tvdbId = Convert.ToInt32(series.GetProviderId(MetadataProvider.Tvdb)); - var seasonNumber = season.IndexNumber.Value; - var language = item.GetPreferredMetadataLanguage(); - var remoteImages = new List(); - - var keyTypes = _tvdbClientManager.GetImageKeyTypesForSeasonAsync(tvdbId, language, cancellationToken).ConfigureAwait(false); - await foreach (var keyType in keyTypes) - { - var imageQuery = new ImagesQuery - { - KeyType = keyType, - SubKey = seasonNumber.ToString() - }; - try - { - var imageResults = await _tvdbClientManager - .GetImagesAsync(tvdbId, imageQuery, language, cancellationToken).ConfigureAwait(false); - remoteImages.AddRange(GetImages(imageResults.Data, language)); - } - catch (TvDbServerException) - { - _logger.LogDebug("No images of type {KeyType} found for series {TvdbId}", keyType, tvdbId); - } - } - - return remoteImages; - } - - private IEnumerable GetImages(Image[] images, string preferredLanguage) - { - var list = new List(); - // any languages with null ids are ignored - var languages = _tvdbClientManager.GetLanguagesAsync(CancellationToken.None).Result.Data.Where(x => x.Id.HasValue); - foreach (Image image in images) - { - var imageInfo = new RemoteImageInfo - { - RatingType = RatingType.Score, - CommunityRating = (double?)image.RatingsInfo.Average, - VoteCount = image.RatingsInfo.Count, - Url = TvdbUtils.BannerUrl + image.FileName, - ProviderName = ProviderName, - Language = languages.FirstOrDefault(lang => lang.Id == image.LanguageId)?.Abbreviation, - ThumbnailUrl = TvdbUtils.BannerUrl + image.Thumbnail - }; - - var resolution = image.Resolution.Split('x'); - if (resolution.Length == 2) - { - imageInfo.Width = Convert.ToInt32(resolution[0]); - imageInfo.Height = Convert.ToInt32(resolution[1]); - } - - imageInfo.Type = TvdbUtils.GetImageTypeFromKeyType(image.KeyType); - list.Add(imageInfo); - } - - var isLanguageEn = string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase); - return list.OrderByDescending(i => - { - if (string.Equals(preferredLanguage, i.Language, StringComparison.OrdinalIgnoreCase)) - { - return 3; - } - - if (!isLanguageEn) - { - if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase)) - { - return 2; - } - } - - if (string.IsNullOrEmpty(i.Language)) - { - return isLanguageEn ? 3 : 2; - } - - return 0; - }) - .ThenByDescending(i => i.CommunityRating ?? 0) - .ThenByDescending(i => i.VoteCount ?? 0); - } - - public int Order => 0; - - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesImageProvider.cs deleted file mode 100644 index d96840e51c..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesImageProvider.cs +++ /dev/null @@ -1,153 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; -using TvDbSharper.Dto; -using RatingType = MediaBrowser.Model.Dto.RatingType; -using Series = MediaBrowser.Controller.Entities.TV.Series; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbSeriesImageProvider : IRemoteImageProvider, IHasOrder - { - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbSeriesImageProvider(IHttpClientFactory httpClientFactory, ILogger logger, TvdbClientManager tvdbClientManager) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _tvdbClientManager = tvdbClientManager; - } - - public string Name => ProviderName; - - public static string ProviderName => "TheTVDB"; - - public bool Supports(BaseItem item) - { - return item is Series; - } - - public IEnumerable GetSupportedImages(BaseItem item) - { - return new List - { - ImageType.Primary, - ImageType.Banner, - ImageType.Backdrop - }; - } - - public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) - { - if (!TvdbSeriesProvider.IsValidSeries(item.ProviderIds)) - { - return Array.Empty(); - } - - var language = item.GetPreferredMetadataLanguage(); - var remoteImages = new List(); - var tvdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tvdb)); - var allowedKeyTypes = _tvdbClientManager.GetImageKeyTypesForSeriesAsync(tvdbId, language, cancellationToken) - .ConfigureAwait(false); - await foreach (KeyType keyType in allowedKeyTypes) - { - var imageQuery = new ImagesQuery - { - KeyType = keyType - }; - try - { - var imageResults = - await _tvdbClientManager.GetImagesAsync(tvdbId, imageQuery, language, cancellationToken) - .ConfigureAwait(false); - - remoteImages.AddRange(GetImages(imageResults.Data, language)); - } - catch (TvDbServerException) - { - _logger.LogDebug("No images of type {KeyType} exist for series {TvDbId}", keyType, - tvdbId); - } - } - - return remoteImages; - } - - private IEnumerable GetImages(Image[] images, string preferredLanguage) - { - var list = new List(); - var languages = _tvdbClientManager.GetLanguagesAsync(CancellationToken.None).Result.Data; - - foreach (Image image in images) - { - var imageInfo = new RemoteImageInfo - { - RatingType = RatingType.Score, - CommunityRating = (double?)image.RatingsInfo.Average, - VoteCount = image.RatingsInfo.Count, - Url = TvdbUtils.BannerUrl + image.FileName, - ProviderName = Name, - Language = languages.FirstOrDefault(lang => lang.Id == image.LanguageId)?.Abbreviation, - ThumbnailUrl = TvdbUtils.BannerUrl + image.Thumbnail - }; - - var resolution = image.Resolution.Split('x'); - if (resolution.Length == 2) - { - imageInfo.Width = Convert.ToInt32(resolution[0]); - imageInfo.Height = Convert.ToInt32(resolution[1]); - } - - imageInfo.Type = TvdbUtils.GetImageTypeFromKeyType(image.KeyType); - list.Add(imageInfo); - } - - var isLanguageEn = string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase); - return list.OrderByDescending(i => - { - if (string.Equals(preferredLanguage, i.Language, StringComparison.OrdinalIgnoreCase)) - { - return 3; - } - - if (!isLanguageEn) - { - if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase)) - { - return 2; - } - } - - if (string.IsNullOrEmpty(i.Language)) - { - return isLanguageEn ? 3 : 2; - } - - return 0; - }) - .ThenByDescending(i => i.CommunityRating ?? 0) - .ThenByDescending(i => i.VoteCount ?? 0); - } - - public int Order => 0; - - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs deleted file mode 100644 index ca9b1d738f..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs +++ /dev/null @@ -1,417 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Providers; -using Microsoft.Extensions.Logging; -using TvDbSharper; -using TvDbSharper.Dto; -using Series = MediaBrowser.Controller.Entities.TV.Series; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public class TvdbSeriesProvider : IRemoteMetadataProvider, IHasOrder - { - internal static TvdbSeriesProvider Current { get; private set; } - - private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; - private readonly ILibraryManager _libraryManager; - private readonly ILocalizationManager _localizationManager; - private readonly TvdbClientManager _tvdbClientManager; - - public TvdbSeriesProvider(IHttpClientFactory httpClientFactory, ILogger logger, ILibraryManager libraryManager, ILocalizationManager localizationManager, TvdbClientManager tvdbClientManager) - { - _httpClientFactory = httpClientFactory; - _logger = logger; - _libraryManager = libraryManager; - _localizationManager = localizationManager; - Current = this; - _tvdbClientManager = tvdbClientManager; - } - - public async Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken) - { - if (IsValidSeries(searchInfo.ProviderIds)) - { - var metadata = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false); - - if (metadata.HasMetadata) - { - return new List - { - new RemoteSearchResult - { - Name = metadata.Item.Name, - PremiereDate = metadata.Item.PremiereDate, - ProductionYear = metadata.Item.ProductionYear, - ProviderIds = metadata.Item.ProviderIds, - SearchProviderName = Name - } - }; - } - } - - return await FindSeries(searchInfo.Name, searchInfo.Year, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false); - } - - public async Task> GetMetadata(SeriesInfo itemId, CancellationToken cancellationToken) - { - var result = new MetadataResult - { - QueriedById = true - }; - - if (!IsValidSeries(itemId.ProviderIds)) - { - result.QueriedById = false; - await Identify(itemId).ConfigureAwait(false); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (IsValidSeries(itemId.ProviderIds)) - { - result.Item = new Series(); - result.HasMetadata = true; - - await FetchSeriesData(result, itemId.MetadataLanguage, itemId.ProviderIds, cancellationToken) - .ConfigureAwait(false); - } - - return result; - } - - private async Task FetchSeriesData(MetadataResult result, string metadataLanguage, Dictionary seriesProviderIds, CancellationToken cancellationToken) - { - var series = result.Item; - - if (seriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out var tvdbId) && !string.IsNullOrEmpty(tvdbId)) - { - series.SetProviderId(MetadataProvider.Tvdb, tvdbId); - } - - if (seriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out var imdbId) && !string.IsNullOrEmpty(imdbId)) - { - series.SetProviderId(MetadataProvider.Imdb, imdbId); - tvdbId = await GetSeriesByRemoteId(imdbId, MetadataProvider.Imdb.ToString(), metadataLanguage, - cancellationToken).ConfigureAwait(false); - } - - if (seriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out var zap2It) && !string.IsNullOrEmpty(zap2It)) - { - series.SetProviderId(MetadataProvider.Zap2It, zap2It); - tvdbId = await GetSeriesByRemoteId(zap2It, MetadataProvider.Zap2It.ToString(), metadataLanguage, - cancellationToken).ConfigureAwait(false); - } - - try - { - var seriesResult = - await _tvdbClientManager - .GetSeriesByIdAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken) - .ConfigureAwait(false); - MapSeriesToResult(result, seriesResult.Data, metadataLanguage); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve series with id {TvdbId}", tvdbId); - return; - } - - cancellationToken.ThrowIfCancellationRequested(); - - result.ResetPeople(); - - try - { - var actorsResult = await _tvdbClientManager - .GetActorsAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken).ConfigureAwait(false); - MapActorsToResult(result, actorsResult.Data); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve actors for series {TvdbId}", tvdbId); - } - } - - private async Task GetSeriesByRemoteId(string id, string idType, string language, CancellationToken cancellationToken) - { - TvDbResponse result = null; - - try - { - if (string.Equals(idType, MetadataProvider.Zap2It.ToString(), StringComparison.OrdinalIgnoreCase)) - { - result = await _tvdbClientManager.GetSeriesByZap2ItIdAsync(id, language, cancellationToken) - .ConfigureAwait(false); - } - else - { - result = await _tvdbClientManager.GetSeriesByImdbIdAsync(id, language, cancellationToken) - .ConfigureAwait(false); - } - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to retrieve series with remote id {RemoteId}", id); - } - - return result?.Data.First().Id.ToString(); - } - - /// - /// Check whether a dictionary of provider IDs includes an entry for a valid TV metadata provider. - /// - /// The dictionary to check. - /// True, if the dictionary contains a valid TV provider ID, otherwise false. - internal static bool IsValidSeries(Dictionary seriesProviderIds) - { - return seriesProviderIds.ContainsKey(MetadataProvider.Tvdb.ToString()) || - seriesProviderIds.ContainsKey(MetadataProvider.Imdb.ToString()) || - seriesProviderIds.ContainsKey(MetadataProvider.Zap2It.ToString()); - } - - /// - /// Finds the series. - /// - /// The name. - /// The year. - /// The language. - /// The cancellation token. - /// Task{System.String}. - private async Task> FindSeries(string name, int? year, string language, CancellationToken cancellationToken) - { - var results = await FindSeriesInternal(name, language, cancellationToken).ConfigureAwait(false); - - if (results.Count == 0) - { - var parsedName = _libraryManager.ParseName(name); - var nameWithoutYear = parsedName.Name; - - if (!string.IsNullOrWhiteSpace(nameWithoutYear) && !string.Equals(nameWithoutYear, name, StringComparison.OrdinalIgnoreCase)) - { - results = await FindSeriesInternal(nameWithoutYear, language, cancellationToken).ConfigureAwait(false); - } - } - - return results.Where(i => - { - if (year.HasValue && i.ProductionYear.HasValue) - { - // Allow one year tolerance - return Math.Abs(year.Value - i.ProductionYear.Value) <= 1; - } - - return true; - }); - } - - private async Task> FindSeriesInternal(string name, string language, CancellationToken cancellationToken) - { - var comparableName = GetComparableName(name); - var list = new List, RemoteSearchResult>>(); - TvDbResponse result; - try - { - result = await _tvdbClientManager.GetSeriesByNameAsync(comparableName, language, cancellationToken) - .ConfigureAwait(false); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "No series results found for {Name}", comparableName); - return new List(); - } - - foreach (var seriesSearchResult in result.Data) - { - var tvdbTitles = new List - { - GetComparableName(seriesSearchResult.SeriesName) - }; - tvdbTitles.AddRange(seriesSearchResult.Aliases.Select(GetComparableName)); - - DateTime.TryParse(seriesSearchResult.FirstAired, out var firstAired); - var remoteSearchResult = new RemoteSearchResult - { - Name = tvdbTitles.FirstOrDefault(), - ProductionYear = firstAired.Year, - SearchProviderName = Name - }; - - if (!string.IsNullOrEmpty(seriesSearchResult.Banner)) - { - // Results from their Search endpoints already include the /banners/ part in the url, because reasons... - remoteSearchResult.ImageUrl = TvdbUtils.TvdbImageBaseUrl + seriesSearchResult.Banner; - } - - try - { - var seriesSesult = - await _tvdbClientManager.GetSeriesByIdAsync(seriesSearchResult.Id, language, cancellationToken) - .ConfigureAwait(false); - remoteSearchResult.SetProviderId(MetadataProvider.Imdb, seriesSesult.Data.ImdbId); - remoteSearchResult.SetProviderId(MetadataProvider.Zap2It, seriesSesult.Data.Zap2itId); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Unable to retrieve series with id {TvdbId}", seriesSearchResult.Id); - } - - remoteSearchResult.SetProviderId(MetadataProvider.Tvdb, seriesSearchResult.Id.ToString()); - list.Add(new Tuple, RemoteSearchResult>(tvdbTitles, remoteSearchResult)); - } - - return list - .OrderBy(i => i.Item1.Contains(comparableName, StringComparer.OrdinalIgnoreCase) ? 0 : 1) - .ThenBy(i => list.IndexOf(i)) - .Select(i => i.Item2) - .ToList(); - } - - /// - /// Gets the name of the comparable. - /// - /// The name. - /// System.String. - private string GetComparableName(string name) - { - name = name.ToLowerInvariant(); - name = name.Normalize(NormalizationForm.FormKD); - name = name.Replace(", the", string.Empty).Replace("the ", " ").Replace(" the ", " "); - name = name.Replace("&", " and " ); - name = Regex.Replace(name, @"[\p{Lm}\p{Mn}]", string.Empty); // Remove diacritics, etc - name = Regex.Replace(name, @"[\W\p{Pc}]+", " "); // Replace sequences of non-word characters and _ with " " - return name.Trim(); - } - - private void MapSeriesToResult(MetadataResult result, TvDbSharper.Dto.Series tvdbSeries, string metadataLanguage) - { - Series series = result.Item; - series.SetProviderId(MetadataProvider.Tvdb, tvdbSeries.Id.ToString()); - series.Name = tvdbSeries.SeriesName; - series.Overview = (tvdbSeries.Overview ?? string.Empty).Trim(); - result.ResultLanguage = metadataLanguage; - series.AirDays = TVUtils.GetAirDays(tvdbSeries.AirsDayOfWeek); - series.AirTime = tvdbSeries.AirsTime; - series.CommunityRating = (float?)tvdbSeries.SiteRating; - series.SetProviderId(MetadataProvider.Imdb, tvdbSeries.ImdbId); - series.SetProviderId(MetadataProvider.Zap2It, tvdbSeries.Zap2itId); - if (Enum.TryParse(tvdbSeries.Status, true, out SeriesStatus seriesStatus)) - { - series.Status = seriesStatus; - } - - if (DateTime.TryParse(tvdbSeries.FirstAired, out var date)) - { - // dates from tvdb are UTC but without offset or Z - series.PremiereDate = date; - series.ProductionYear = date.Year; - } - - if (!string.IsNullOrEmpty(tvdbSeries.Runtime) && double.TryParse(tvdbSeries.Runtime, out double runtime)) - { - series.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks; - } - - foreach (var genre in tvdbSeries.Genre) - { - series.AddGenre(genre); - } - - if (!string.IsNullOrEmpty(tvdbSeries.Network)) - { - series.AddStudio(tvdbSeries.Network); - } - - if (result.Item.Status.HasValue && result.Item.Status.Value == SeriesStatus.Ended) - { - try - { - var episodeSummary = _tvdbClientManager - .GetSeriesEpisodeSummaryAsync(tvdbSeries.Id, metadataLanguage, CancellationToken.None).Result.Data; - var maxSeasonNumber = episodeSummary.AiredSeasons.Select(s => Convert.ToInt32(s)).Max(); - var episodeQuery = new EpisodeQuery - { - AiredSeason = maxSeasonNumber - }; - var episodesPage = - _tvdbClientManager.GetEpisodesPageAsync(tvdbSeries.Id, episodeQuery, metadataLanguage, CancellationToken.None).Result.Data; - result.Item.EndDate = episodesPage.Select(e => - { - DateTime.TryParse(e.FirstAired, out var firstAired); - return firstAired; - }).Max(); - } - catch (TvDbServerException e) - { - _logger.LogError(e, "Failed to find series end date for series {TvdbId}", tvdbSeries.Id); - } - } - } - - private static void MapActorsToResult(MetadataResult result, IEnumerable actors) - { - foreach (Actor actor in actors) - { - var personInfo = new PersonInfo - { - Type = PersonType.Actor, - Name = (actor.Name ?? string.Empty).Trim(), - Role = actor.Role, - SortOrder = actor.SortOrder - }; - - if (!string.IsNullOrEmpty(actor.Image)) - { - personInfo.ImageUrl = TvdbUtils.BannerUrl + actor.Image; - } - - if (!string.IsNullOrWhiteSpace(personInfo.Name)) - { - result.AddPerson(personInfo); - } - } - } - - public string Name => "TheTVDB"; - - public async Task Identify(SeriesInfo info) - { - if (!string.IsNullOrWhiteSpace(info.GetProviderId(MetadataProvider.Tvdb))) - { - return; - } - - var srch = await FindSeries(info.Name, info.Year, info.MetadataLanguage, CancellationToken.None) - .ConfigureAwait(false); - - var entry = srch.FirstOrDefault(); - - if (entry != null) - { - var id = entry.GetProviderId(MetadataProvider.Tvdb); - info.SetProviderId(MetadataProvider.Tvdb, id); - } - } - - public int Order => 0; - - public Task GetImageResponse(string url, CancellationToken cancellationToken) - { - return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbUtils.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbUtils.cs deleted file mode 100644 index 37a8d04a6f..0000000000 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbUtils.cs +++ /dev/null @@ -1,39 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using MediaBrowser.Model.Entities; - -namespace MediaBrowser.Providers.Plugins.TheTvdb -{ - public static class TvdbUtils - { - public const string TvdbApiKey = "OG4V3YJ3FAP7FP2K"; - public const string TvdbBaseUrl = "https://www.thetvdb.com/"; - public const string TvdbImageBaseUrl = "https://www.thetvdb.com"; - public const string BannerUrl = TvdbImageBaseUrl + "/banners/"; - - public static ImageType GetImageTypeFromKeyType(string keyType) - { - switch (keyType.ToLowerInvariant()) - { - case "poster": - case "season": return ImageType.Primary; - case "series": - case "seasonwide": return ImageType.Banner; - case "fanart": return ImageType.Backdrop; - default: throw new ArgumentException($"Invalid or unknown keytype: {keyType}", nameof(keyType)); - } - } - - public static string NormalizeLanguage(string language) - { - if (string.IsNullOrWhiteSpace(language)) - { - return null; - } - - // pt-br is just pt to tvdb - return language.Split('-')[0].ToLowerInvariant(); - } - } -} diff --git a/MediaBrowser.Providers/TV/TvdbEpisodeExternalId.cs b/MediaBrowser.Providers/TV/TvdbEpisodeExternalId.cs deleted file mode 100644 index 40c5f2d785..0000000000 --- a/MediaBrowser.Providers/TV/TvdbEpisodeExternalId.cs +++ /dev/null @@ -1,28 +0,0 @@ -#pragma warning disable CS1591 - -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using MediaBrowser.Providers.Plugins.TheTvdb; - -namespace MediaBrowser.Providers.TV -{ - public class TvdbEpisodeExternalId : IExternalId - { - /// - public string ProviderName => "TheTVDB"; - - /// - public string Key => MetadataProvider.Tvdb.ToString(); - - /// - public ExternalIdMediaType? Type => ExternalIdMediaType.Episode; - - /// - public string UrlFormatString => TvdbUtils.TvdbBaseUrl + "?tab=episode&id={0}"; - - /// - public bool Supports(IHasProviderIds item) => item is Episode; - } -} diff --git a/MediaBrowser.Providers/TV/TvdbExternalId.cs b/MediaBrowser.Providers/TV/TvdbExternalId.cs deleted file mode 100644 index 4c54de9f82..0000000000 --- a/MediaBrowser.Providers/TV/TvdbExternalId.cs +++ /dev/null @@ -1,28 +0,0 @@ -#pragma warning disable CS1591 - -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using MediaBrowser.Providers.Plugins.TheTvdb; - -namespace MediaBrowser.Providers.TV -{ - public class TvdbExternalId : IExternalId - { - /// - public string ProviderName => "TheTVDB"; - - /// - public string Key => MetadataProvider.Tvdb.ToString(); - - /// - public ExternalIdMediaType? Type => null; - - /// - public string UrlFormatString => TvdbUtils.TvdbBaseUrl + "?tab=series&id={0}"; - - /// - public bool Supports(IHasProviderIds item) => item is Series; - } -} diff --git a/MediaBrowser.Providers/TV/TvdbSeasonExternalId.cs b/MediaBrowser.Providers/TV/TvdbSeasonExternalId.cs deleted file mode 100644 index 807ebb3eee..0000000000 --- a/MediaBrowser.Providers/TV/TvdbSeasonExternalId.cs +++ /dev/null @@ -1,28 +0,0 @@ -#pragma warning disable CS1591 - -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Providers; -using MediaBrowser.Providers.Plugins.TheTvdb; - -namespace MediaBrowser.Providers.TV -{ - public class TvdbSeasonExternalId : IExternalId - { - /// - public string ProviderName => "TheTVDB"; - - /// - public string Key => MetadataProvider.Tvdb.ToString(); - - /// - public ExternalIdMediaType? Type => ExternalIdMediaType.Season; - - /// - public string UrlFormatString => null; - - /// - public bool Supports(IHasProviderIds item) => item is Season; - } -} diff --git a/MediaBrowser.Providers/TV/Zap2ItExternalId.cs b/MediaBrowser.Providers/TV/Zap2ItExternalId.cs index c9f314af94..3cb18e4248 100644 --- a/MediaBrowser.Providers/TV/Zap2ItExternalId.cs +++ b/MediaBrowser.Providers/TV/Zap2ItExternalId.cs @@ -4,7 +4,6 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; -using MediaBrowser.Providers.Plugins.TheTvdb; namespace MediaBrowser.Providers.TV { From 69360b749a53bd41087530f7fbe2e0c7798f704b Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 9 Oct 2020 17:35:08 -0600 Subject: [PATCH 0081/1930] Convert field string to enum. --- Jellyfin.Api/Controllers/ArtistsController.cs | 8 +++--- .../Controllers/ChannelsController.cs | 8 +++--- Jellyfin.Api/Controllers/GenresController.cs | 4 +-- .../Controllers/InstantMixController.cs | 28 +++++++++---------- Jellyfin.Api/Controllers/ItemsController.cs | 4 +-- Jellyfin.Api/Controllers/LibraryController.cs | 4 +-- Jellyfin.Api/Controllers/LiveTvController.cs | 25 +++++++++-------- Jellyfin.Api/Controllers/MoviesController.cs | 2 +- .../Controllers/MusicGenresController.cs | 4 +-- Jellyfin.Api/Controllers/PersonsController.cs | 4 +-- .../Controllers/PlaylistsController.cs | 4 +-- Jellyfin.Api/Controllers/StudiosController.cs | 4 +-- .../Controllers/TrailersController.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 14 +++++----- .../Controllers/UserLibraryController.cs | 4 +-- Jellyfin.Api/Controllers/YearsController.cs | 4 +-- Jellyfin.Api/Extensions/DtoExtensions.cs | 26 ++--------------- 17 files changed, 65 insertions(+), 84 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index d38214116c..e9e0160217 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -51,7 +51,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// Optional. Search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, @@ -260,7 +260,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// Optional. Search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -295,7 +295,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index 33a969f859..732e24799a 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -107,7 +107,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Sort Order - Ascending,Descending. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. /// Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Channel items returned. /// /// A representing the request to get the channel items. @@ -123,7 +123,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery] string? filters, [FromQuery] string? sortBy, - [FromQuery] string? fields) + [FromQuery] ItemFields[] fields) { var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -184,7 +184,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Specify one or more channel id's, comma delimited. /// Latest channel items returned. /// @@ -197,7 +197,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? filters, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? channelIds) { var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index de6aa86c94..aad652a404 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -52,7 +52,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// The search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -87,7 +87,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index 07fed97642..eae5ba843d 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -54,7 +54,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -67,7 +67,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -91,7 +91,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -104,7 +104,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -128,7 +128,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -141,7 +141,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -165,7 +165,7 @@ namespace Jellyfin.Api.Controllers /// The genre name. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -178,7 +178,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string name, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -201,7 +201,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -214,7 +214,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -238,7 +238,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -251,7 +251,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -275,7 +275,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// Optional. Filter by user id, and attach user data. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -288,7 +288,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 652c4689d0..5fd302db9e 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -179,7 +179,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, @@ -535,7 +535,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? mediaTypes, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 8a872ae133..865b0010d8 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -693,7 +693,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? excludeArtistIds, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] string? fields) + [FromQuery] ItemFields[] fields) { var item = itemId.Equals(Guid.Empty) ? (!userId.Equals(Guid.Empty) @@ -885,7 +885,7 @@ namespace Jellyfin.Api.Controllers string? excludeArtistIds, Guid? userId, int? limit, - string? fields, + ItemFields[] fields, string[] includeItemTypes, bool isMovie) { diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 3557e63047..8c316cfbaf 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -117,7 +117,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Include image information in output. /// Optional. The max number of images to return, per image type. /// "Optional. The image types to include in the output. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include user data. /// Optional. Key to sort by. /// Optional. Sort order. @@ -146,7 +146,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] string? enableImageTypes, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy, [FromQuery] SortOrder? sortOrder, @@ -238,7 +238,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Include image information in output. /// Optional. The max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include user data. /// Optional. Filter for movies. /// Optional. Filter for series. @@ -263,7 +263,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] string? enableImageTypes, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool? isMovie, [FromQuery] bool? isSeries, @@ -295,7 +295,7 @@ namespace Jellyfin.Api.Controllers IsKids = isKids, IsSports = isSports, IsLibraryItem = isLibraryItem, - Fields = RequestHelpers.GetItemFields(fields), + Fields = fields, ImageTypeLimit = imageTypeLimit, EnableImages = enableImages }, dtoOptions); @@ -315,7 +315,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Include image information in output. /// Optional. The max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include user data. /// Optional. Return total record count. /// Live tv recordings returned. @@ -350,7 +350,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] string? enableImageTypes, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { @@ -529,7 +529,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Include user data. /// Optional. Filter by series timer id. /// Optional. Filter by library series id. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Retrieve total record count. /// Live tv epgs returned. /// @@ -564,7 +564,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] string? seriesTimerId, [FromQuery] Guid? librarySeriesId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool enableTotalRecordCount = true) { var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -661,8 +661,9 @@ namespace Jellyfin.Api.Controllers } } + var fields = RequestHelpers.GetItemFields(body.Fields); var dtoOptions = new DtoOptions() - .AddItemFields(body.Fields) + .AddItemFields(fields) .AddClientFields(Request) .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); @@ -684,7 +685,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The max number of images to return, per image type. /// Optional. The image types to include in the output. /// The genres to return guide information for. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. include user data. /// Retrieve total record count. /// Recommended epgs returned. @@ -706,7 +707,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageTypeLimit, [FromQuery] string? enableImageTypes, [FromQuery] string? genreIds, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index 7fcfc749de..bf8279e0c7 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -65,7 +65,7 @@ namespace Jellyfin.Api.Controllers public ActionResult> GetMovieRecommendations( [FromQuery] Guid? userId, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] int categoryLimit = 5, [FromQuery] int itemLimit = 8) { diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 570ae8fdc7..bdcdf503eb 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -52,7 +52,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// The search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 8bd610dad9..4b0a84df23 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -51,7 +51,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// The search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 1e95bd2b38..31c66c3269 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -133,7 +133,7 @@ namespace Jellyfin.Api.Controllers /// User id. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Include image information in output. /// Optional. Include user data. /// Optional. The max number of images to return, per image type. @@ -147,7 +147,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] Guid userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index cdd5f958e9..886272c49a 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -50,7 +50,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// Optional. Search term. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. @@ -85,7 +85,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? filters, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 5157b08ae5..0662a39edc 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -144,7 +144,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? filters, [FromQuery] bool? isFavorite, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index d158f6c342..27e18eb38c 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -57,7 +57,7 @@ namespace Jellyfin.Api.Controllers /// The user id of the user to get the next up episodes for. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Filter by series id. /// Optional. Specify this to localize the search to a specific item or folder. Omit to use the root. /// Optional. Include image information in output. @@ -72,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? seriesId, [FromQuery] string? parentId, [FromQuery] bool? enableImges, @@ -82,7 +82,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool enableTotalRecordCount = true) { var options = new DtoOptions() - .AddItemFields(fields!) + .AddItemFields(fields) .AddClientFields(Request) .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!); @@ -117,7 +117,7 @@ namespace Jellyfin.Api.Controllers /// The user id of the user to get the upcoming episodes for. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls. + /// Optional. Specify additional fields of information to return in the output. /// Optional. Specify this to localize the search to a specific item or folder. Omit to use the root. /// Optional. Include image information in output. /// Optional. The max number of images to return, per image type. @@ -130,7 +130,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Controllers public ActionResult> GetEpisodes( [FromRoute, Required] string seriesId, [FromQuery] Guid? userId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] int? season, [FromQuery] string? seasonId, [FromQuery] bool? isMissing, @@ -319,7 +319,7 @@ namespace Jellyfin.Api.Controllers public ActionResult> GetSeasons( [FromRoute, Required] string seriesId, [FromQuery] Guid? userId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] bool? isSpecialSeason, [FromQuery] bool? isMissing, [FromQuery] string? adjacentTo, diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index 48262f0620..981c98b6aa 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -251,7 +251,7 @@ namespace Jellyfin.Api.Controllers /// /// User id. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted. /// Filter by items that are played, or not. /// Optional. include image information in output. @@ -267,7 +267,7 @@ namespace Jellyfin.Api.Controllers public ActionResult> GetLatestMedia( [FromRoute, Required] Guid userId, [FromQuery] Guid? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? includeItemTypes, [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 4ecf0407bf..707a31f757 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -50,7 +50,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of records to return. /// Sort Order - Ascending,Descending. /// Specify this to localize the search to a specific item or folder. Omit to use the root. - /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. + /// Optional. Specify additional fields of information to return in the output. /// Optional. If specified, results will be excluded based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be included based on item type. This allows multiple, comma delimited. /// Optional. Filter by MediaType. Allows multiple, comma delimited. @@ -70,7 +70,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] string? fields, + [FromQuery] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? mediaTypes, diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index e61e9c29d9..cbe748bcf4 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -21,31 +21,11 @@ namespace Jellyfin.Api.Extensions /// Legacy order: 1. /// /// DtoOptions object. - /// Comma delimited string of fields. + /// Array of item fields. /// Modified DtoOptions object. - internal static DtoOptions AddItemFields(this DtoOptions dtoOptions, string? fields) + internal static DtoOptions AddItemFields(this DtoOptions dtoOptions, ItemFields[] fields) { - if (string.IsNullOrEmpty(fields)) - { - dtoOptions.Fields = Array.Empty(); - } - else - { - dtoOptions.Fields = fields.Split(',') - .Select(v => - { - if (Enum.TryParse(v, true, out ItemFields value)) - { - return (ItemFields?)value; - } - - return null; - }) - .Where(i => i.HasValue) - .Select(i => i!.Value) - .ToArray(); - } - + dtoOptions.Fields = fields; return dtoOptions; } From 27e753ddb4f6eb43ef867bff2cdf757702bffa1c Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 9 Oct 2020 17:52:39 -0600 Subject: [PATCH 0082/1930] Convert image type string to enum. --- Jellyfin.Api/Controllers/ArtistsController.cs | 5 ++-- Jellyfin.Api/Controllers/GenresController.cs | 3 ++- .../Controllers/InstantMixController.cs | 15 ++++++----- Jellyfin.Api/Controllers/ItemsController.cs | 8 +++--- Jellyfin.Api/Controllers/LiveTvController.cs | 14 +++++----- .../Controllers/MusicGenresController.cs | 3 ++- Jellyfin.Api/Controllers/PersonsController.cs | 3 ++- .../Controllers/PlaylistsController.cs | 3 ++- Jellyfin.Api/Controllers/StudiosController.cs | 3 ++- .../Controllers/TrailersController.cs | 5 ++-- Jellyfin.Api/Controllers/TvShowsController.cs | 9 ++++--- .../Controllers/UserLibraryController.cs | 2 +- Jellyfin.Api/Controllers/YearsController.cs | 3 ++- Jellyfin.Api/Extensions/DtoExtensions.cs | 8 +++--- Jellyfin.Api/Helpers/RequestHelpers.cs | 27 +++++++++++++++++++ 15 files changed, 74 insertions(+), 37 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index d38214116c..9e98811877 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -9,6 +9,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -99,7 +100,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, @@ -308,7 +309,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index de6aa86c94..c065b9b576 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -100,7 +101,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index 07fed97642..e6e6b3e70e 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -71,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -108,7 +109,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var album = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -145,7 +146,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var playlist = (Playlist)_libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -182,7 +183,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -218,7 +219,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -255,7 +256,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -292,7 +293,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 652c4689d0..3411361af1 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -185,7 +185,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, - [FromQuery] string? imageTypes, + [FromQuery] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, [FromQuery] string? genres, @@ -194,7 +194,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, @@ -342,7 +342,7 @@ namespace Jellyfin.Api.Controllers PersonIds = RequestHelpers.GetGuids(personIds), PersonTypes = RequestHelpers.Split(personTypes, ',', true), Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(), - ImageTypes = RequestHelpers.Split(imageTypes, ',', true).Select(v => Enum.Parse(v, true)).ToArray(), + ImageTypes = imageTypes, VideoTypes = RequestHelpers.Split(videoTypes, ',', true).Select(v => Enum.Parse(v, true)).ToArray(), AdjacentTo = adjacentTo, ItemIds = RequestHelpers.GetGuids(ids), @@ -539,7 +539,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? mediaTypes, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] bool enableTotalRecordCount = true, diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 3557e63047..458c62355c 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -26,6 +26,7 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; @@ -145,7 +146,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isDisliked, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy, @@ -262,7 +263,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? seriesTimerId, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] bool? isMovie, @@ -349,7 +350,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? seriesTimerId, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) @@ -560,7 +561,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? genreIds, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] string? seriesTimerId, [FromQuery] Guid? librarySeriesId, @@ -661,10 +662,11 @@ namespace Jellyfin.Api.Controllers } } + var imageTypes = RequestHelpers.GetImageTypes(body.EnableImageTypes); var dtoOptions = new DtoOptions() .AddItemFields(body.Fields) .AddClientFields(Request) - .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); + .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, imageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); } @@ -704,7 +706,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isSports, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? genreIds, [FromQuery] string? fields, [FromQuery] bool? enableUserData, diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 570ae8fdc7..28337396b1 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -11,6 +11,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -99,7 +100,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 8bd610dad9..94161490aa 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -99,7 +100,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 1e95bd2b38..0419b2436b 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Playlists; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; @@ -151,7 +152,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes) + [FromQuery] ImageType[] enableImageTypes) { var playlist = (Playlist)_libraryManager.GetItemById(playlistId); if (playlist == null) diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index cdd5f958e9..401f516fe2 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -9,6 +9,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -98,7 +99,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 5157b08ae5..e230d34257 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -1,6 +1,7 @@ using System; using Jellyfin.Api.Constants; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -149,7 +150,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, - [FromQuery] string? imageTypes, + [FromQuery] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, [FromQuery] string? genres, @@ -158,7 +159,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index d158f6c342..49a6c386fe 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -13,6 +13,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.TV; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -77,7 +78,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { @@ -134,7 +135,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData) { var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -206,7 +207,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy) { @@ -325,7 +326,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? adjacentTo, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData) { var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index 48262f0620..a52af17815 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -272,7 +272,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] int limit = 20, [FromQuery] bool groupItems = true) diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 4ecf0407bf..2c685309a6 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -77,7 +78,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortBy, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] string? enableImageTypes, + [FromQuery] ImageType[] enableImageTypes, [FromQuery] Guid? userId, [FromQuery] bool recursive = true, [FromQuery] bool? enableImages = true) diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index e61e9c29d9..85f8d789e4 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -126,7 +126,7 @@ namespace Jellyfin.Api.Extensions bool? enableImages, bool? enableUserData, int? imageTypeLimit, - string? enableImageTypes) + ImageType[] enableImageTypes) { dtoOptions.EnableImages = enableImages ?? true; @@ -140,11 +140,9 @@ namespace Jellyfin.Api.Extensions dtoOptions.EnableUserData = enableUserData.Value; } - if (!string.IsNullOrWhiteSpace(enableImageTypes)) + if (enableImageTypes.Length != 0) { - dtoOptions.ImageTypes = enableImageTypes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) - .Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)) - .ToArray(); + dtoOptions.ImageTypes = enableImageTypes; } return dtoOptions; diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 8dcf08af56..18200de726 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -6,6 +6,7 @@ using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Http; @@ -173,5 +174,31 @@ namespace Jellyfin.Api.Helpers .Select(i => i!.Value) .ToArray(); } + + /// + /// Gets the item fields. + /// + /// The image types string. + /// IEnumerable{ItemFields}. + internal static ImageType[] GetImageTypes(string? imageTypes) + { + if (string.IsNullOrEmpty(imageTypes)) + { + return Array.Empty(); + } + + return Split(imageTypes, ',', true) + .Select(v => + { + if (Enum.TryParse(v, true, out ImageType value)) + { + return (ImageType?)value; + } + + return null; + }).Where(i => i.HasValue) + .Select(i => i!.Value) + .ToArray(); + } } } From 2eafbc03e44310c6abda435867129100d1587f11 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 9 Oct 2020 18:01:12 -0600 Subject: [PATCH 0083/1930] fix build --- Jellyfin.Api/Helpers/RequestHelpers.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 18200de726..fa48e7a8f1 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -174,7 +174,7 @@ namespace Jellyfin.Api.Helpers .Select(i => i!.Value) .ToArray(); } - + /// /// Gets the item fields. /// From 6dc81ec8e8e25ed73d6d8ad932de57774f3a4418 Mon Sep 17 00:00:00 2001 From: Greenback Date: Sat, 10 Oct 2020 14:05:19 +0100 Subject: [PATCH 0084/1930] Changes to support network config --- .../AppBase/BaseConfigurationManager.cs | 35 +++++++++++++++++-- .../ApplicationHost.cs | 11 +++--- .../Controllers/ConfigurationController.cs | 10 ------ Jellyfin.Networking/Manager/NetworkManager.cs | 13 ++++--- .../Configuration/IConfigurationManager.cs | 10 +++--- 5 files changed, 51 insertions(+), 28 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index fa4b3080c9..8503a358e4 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -134,6 +134,35 @@ namespace Emby.Server.Implementations.AppBase } } + /// + /// Manually pre-loads a factory so that it is available pre system initialisation. + /// + /// Class to register. + public virtual void RegisterConfiguration() + { + if (!typeof(IConfigurationFactory).IsAssignableFrom(typeof(T))) + { + throw new ArgumentException("Parameter does not implement IConfigurationFactory"); + } + + IConfigurationFactory factory = (IConfigurationFactory)Activator.CreateInstance(typeof(T)); + + if (_configurationFactories == null) + { + _configurationFactories = new IConfigurationFactory[] { factory }; + } + else + { + var list = _configurationFactories.ToList(); + list.Add(factory); + _configurationFactories = list.ToArray(); + } + + _configurationStores = _configurationFactories + .SelectMany(i => i.GetConfigurations()) + .ToArray(); + } + /// /// Adds parts. /// @@ -269,7 +298,7 @@ namespace Emby.Server.Implementations.AppBase } /// - public object GetConfiguration(string key, Type objectType = null) + public object GetConfiguration(string key) { return _configurations.GetOrAdd(key, k => { @@ -278,12 +307,12 @@ namespace Emby.Server.Implementations.AppBase var configurationInfo = _configurationStores .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase)); - if (configurationInfo == null && objectType == null) + if (configurationInfo == null) { throw new ResourceNotFoundException("Configuration with key " + key + " not found."); } - var configurationType = configurationInfo?.ConfigurationType ?? objectType; + var configurationType = configurationInfo.ConfigurationType; lock (_configurationSyncLock) { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ecd26c0d84..768f7a9c8d 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -276,9 +276,11 @@ namespace Emby.Server.Implementations _fileSystemManager = fileSystem; ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); + MigrateNetworkConfiguration(); + // Have to pre-register the NetworkConfigurationFactory. + ConfigurationManager.RegisterConfiguration(); NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); - NetManager.UpdateSettings(GetNetworkConfiguration()); Logger = LoggerFactory.CreateLogger(); @@ -304,7 +306,7 @@ namespace Emby.Server.Implementations ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; } - private NetworkConfiguration GetNetworkConfiguration() + private void MigrateNetworkConfiguration() { string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml"); if (!File.Exists(path)) @@ -312,11 +314,8 @@ namespace Emby.Server.Implementations var networkSettings = new NetworkConfiguration(); ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings); _xmlSerializer.SerializeToFile(networkSettings, path); - - return networkSettings; + Logger.LogDebug("Successfully migrated network settings."); } - - return (NetworkConfiguration)ConfigurationManager.GetConfiguration("network", typeof(NetworkConfiguration)); } public string ExpandVirtualPath(string path) diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index 09d72e8b10..53f94cf375 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -51,10 +51,6 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetConfiguration() { - // TODO: Temp workaround until the web can be changed. - var net = _configurationManager.GetNetworkConfiguration(); - ClassMigrationHelper.CopyProperties(net, _configurationManager.Configuration); - return _configurationManager.Configuration; } @@ -70,12 +66,6 @@ namespace Jellyfin.Api.Controllers public ActionResult UpdateConfiguration([FromBody, Required] ServerConfiguration configuration) { _configurationManager.ReplaceConfiguration(configuration); - - // TODO: Temp workaround until the web can be changed. - var network = _configurationManager.GetNetworkConfiguration(); - ClassMigrationHelper.CopyProperties(configuration, network); - _configurationManager.SaveConfiguration("Network", network); - return NoContent(); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 26614c85e0..6d6b7ebc4e 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -110,10 +110,12 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls = new Dictionary(); _eventFireLock = new object(); + UpdateSettings(_configurationManager.GetNetworkConfiguration()); + NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; - _configurationManager.ConfigurationUpdated += ConfigurationUpdated; + _configurationManager.NamedConfigurationUpdated += ConfigurationUpdated; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. @@ -600,7 +602,7 @@ namespace Jellyfin.Networking.Manager { if (disposing) { - _configurationManager.ConfigurationUpdated -= ConfigurationUpdated; + _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; } @@ -609,9 +611,12 @@ namespace Jellyfin.Networking.Manager } } - private void ConfigurationUpdated(object? sender, EventArgs args) + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) { - UpdateSettings(_configurationManager.GetNetworkConfiguration()); + if (evt.Key.Equals("network", StringComparison.Ordinal)) + { + UpdateSettings(evt.NewConfiguration); + } } /// diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 7bcd4d8ed3..17520f8a37 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -47,12 +47,12 @@ namespace MediaBrowser.Common.Configuration void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration); /// - /// Gets the configuration. + /// Manually pre-loads a factory so that it is available pre system initialisation. /// - /// The key. - /// Optional parameter containing the key object to create, if it hasn't been registered. - /// System.Object. - object GetConfiguration(string key, Type objectType = null); + /// Class to register. + void RegisterConfiguration(); + + object GetConfiguration(string key); /// /// Gets the type of the configuration. From b34d6fec3db8b00aee11a8ff0c165048abed0ec1 Mon Sep 17 00:00:00 2001 From: Greenback Date: Sat, 10 Oct 2020 14:08:26 +0100 Subject: [PATCH 0085/1930] fixed tests --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 768f7a9c8d..e9cac8fa47 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -314,7 +314,7 @@ namespace Emby.Server.Implementations var networkSettings = new NetworkConfiguration(); ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings); _xmlSerializer.SerializeToFile(networkSettings, path); - Logger.LogDebug("Successfully migrated network settings."); + Logger?.LogDebug("Successfully migrated network settings."); } } From 1ee1f9c8a7d6f7a32d77d14351df040d5f3349fc Mon Sep 17 00:00:00 2001 From: Greenback Date: Sat, 10 Oct 2020 15:27:02 +0100 Subject: [PATCH 0086/1930] Fixed web interface. --- Emby.Server.Implementations/ApplicationHost.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index e9cac8fa47..559a040a81 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1111,9 +1111,9 @@ namespace Emby.Server.Implementations } else { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. + // Un-versioned folder - Add it under the path name and version 0.0.0.1. versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + } } } catch @@ -1212,6 +1212,9 @@ namespace Emby.Server.Implementations // Xbmc yield return typeof(ArtistNfoProvider).Assembly; + // Network + yield return typeof(NetworkManager).Assembly; + foreach (var i in GetAssembliesWithPartsInternal()) { yield return i; From 163d6b0f1d1a252e85b8776b4b0c2ccaa611667e Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Sun, 11 Oct 2020 06:15:55 -0600 Subject: [PATCH 0087/1930] Update Jellyfin.Api/Helpers/RequestHelpers.cs Co-authored-by: Claus Vium --- Jellyfin.Api/Helpers/RequestHelpers.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index fa48e7a8f1..0f2967063e 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -196,7 +196,8 @@ namespace Jellyfin.Api.Helpers } return null; - }).Where(i => i.HasValue) + }) + .Where(i => i.HasValue) .Select(i => i!.Value) .ToArray(); } From 0b73a1d90f80456ab6ea8e53134eae193aa9d5da Mon Sep 17 00:00:00 2001 From: Greenback Date: Sun, 11 Oct 2020 13:19:14 +0100 Subject: [PATCH 0088/1930] Added extra functionality to support registrar. --- .../AppBase/BaseConfigurationManager.cs | 29 ++++++++ .../ApplicationHost.cs | 69 ++----------------- .../Configuration/IConfigurationManager.cs | 6 ++ MediaBrowser.Common/Plugins/BasePlugin.cs | 35 +++++++--- MediaBrowser.Common/Plugins/IPlugin.cs | 12 ---- .../Plugins/IPluginRegistrar.cs | 17 +++++ 6 files changed, 83 insertions(+), 85 deletions(-) create mode 100644 MediaBrowser.Common/Plugins/IPluginRegistrar.cs diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 4ab0a2a3f2..ea4c1ad08c 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -133,6 +133,35 @@ namespace Emby.Server.Implementations.AppBase } } + /// + /// Manually pre-loads a factory so that it is available pre system initialisation. + /// + /// Class to register. + public virtual void RegisterConfiguration() + { + if (!typeof(IConfigurationFactory).IsAssignableFrom(typeof(T))) + { + throw new ArgumentException("Parameter does not implement IConfigurationFactory"); + } + + IConfigurationFactory factory = (IConfigurationFactory)Activator.CreateInstance(typeof(T)); + + if (_configurationFactories == null) + { + _configurationFactories = new IConfigurationFactory[] { factory }; + } + else + { + var list = _configurationFactories.ToList(); + list.Add(factory); + _configurationFactories = list.ToArray(); + } + + _configurationStores = _configurationFactories + .SelectMany(i => i.GetConfigurations()) + .ToArray(); + } + /// /// Adds parts. /// diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d14e503b06..3f2307d80e 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -128,7 +128,6 @@ namespace Emby.Server.Implementations private ISessionManager _sessionManager; private IHttpClientFactory _httpClientFactory; private IWebSocketManager _webSocketManager; - private Dictionary _pluginRegistrations; private string[] _urlPrefixes; /// @@ -262,8 +261,6 @@ namespace Emby.Server.Implementations ServiceCollection = serviceCollection; - _pluginRegistrations = new Dictionary(); - _networkManager = networkManager; networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets; @@ -505,7 +502,7 @@ namespace Emby.Server.Implementations RegisterServices(); - RegisterPlugIns(); + RegisterPlugInServices(); } /// @@ -770,7 +767,6 @@ namespace Emby.Server.Implementations ConfigurationManager.AddParts(GetExports()); _plugins = GetExports() - .Select(LoadPlugin) .Where(i => i != null) .ToArray(); @@ -819,51 +815,6 @@ namespace Emby.Server.Implementations Resolve().AddParts(GetExports()); } - private IPlugin LoadPlugin(IPlugin plugin) - { - try - { - if (plugin is IPluginAssembly assemblyPlugin) - { - var assembly = plugin.GetType().Assembly; - var assemblyName = assembly.GetName(); - var assemblyFilePath = assembly.Location; - - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - - assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); - - try - { - var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); - if (idAttributes.Length > 0) - { - var attribute = (GuidAttribute)idAttributes[0]; - var assemblyId = new Guid(attribute.Value); - - assemblyPlugin.SetId(assemblyId); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName); - } - } - - if (plugin is IHasPluginConfiguration hasPluginConfiguration) - { - hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); - } - } - catch (Exception ex) - { - Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName); - return null; - } - - return plugin; - } - /// /// Discovers the types. /// @@ -874,22 +825,20 @@ namespace Emby.Server.Implementations _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray(); } - private void RegisterPlugIns() + private void RegisterPlugInServices() { - foreach ((var pluginType, var assembly) in _pluginRegistrations) + foreach (var pluginServiceRegistrar in GetExportTypes()) { try { - var pluginRegistration = Activator.CreateInstance(pluginType); - pluginType.InvokeMember("RegisterServices", BindingFlags.InvokeMethod, null, pluginRegistration, new object[] { ServiceCollection }, CultureInfo.InvariantCulture); + var instance = (IPluginRegistrar)Activator.CreateInstance(pluginServiceRegistrar); + instance.RegisterServices(ServiceCollection); } catch (Exception ex) { - Logger.LogError(ex, "Error registering {Assembly} with D.I.", assembly); + Logger.LogError(ex, "Error registering {Assembly} with D.I.", pluginServiceRegistrar.Assembly); } } - - _pluginRegistrations.Clear(); } private IEnumerable GetTypes(IEnumerable assemblies) @@ -900,12 +849,6 @@ namespace Emby.Server.Implementations try { exportedTypes = ass.GetExportedTypes(); - - Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - if (reg != null) - { - _pluginRegistrations.Add(reg, ass); - } } catch (FileNotFoundException ex) { diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index fe726090d6..8cbeaea866 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -46,6 +46,12 @@ namespace MediaBrowser.Common.Configuration /// The new configuration. void ReplaceConfiguration(BaseApplicationConfiguration newConfiguration); + /// + /// Manually pre-loads a factory so that it is available pre system initialisation. + /// + /// Class to register. + void RegisterConfiguration(); + /// /// Gets the configuration. /// diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 4b2918d085..b89bc7eba5 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -3,6 +3,7 @@ using System; using System.IO; using System.Reflection; +using System.Runtime.InteropServices; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; @@ -82,16 +83,6 @@ namespace MediaBrowser.Common.Plugins { } - /// - public virtual void RegisterServices(IServiceCollection serviceCollection) - { - } - - /// - public virtual void UnregisterServices(IServiceCollection serviceCollection) - { - } - /// public void SetAttributes(string assemblyFilePath, string dataFolderPath, Version assemblyVersion) { @@ -140,6 +131,30 @@ namespace MediaBrowser.Common.Plugins { ApplicationPaths = applicationPaths; XmlSerializer = xmlSerializer; + if (this is IPluginAssembly assemblyPlugin) + { + var assembly = GetType().Assembly; + var assemblyName = assembly.GetName(); + var assemblyFilePath = assembly.Location; + + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + + assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); + + var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); + if (idAttributes.Length > 0) + { + var attribute = (GuidAttribute)idAttributes[0]; + var assemblyId = new Guid(attribute.Value); + + assemblyPlugin.SetId(assemblyId); + } + } + + if (this is IHasPluginConfiguration hasPluginConfiguration) + { + hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); + } } /// diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs index 1844eb124f..d583a58878 100644 --- a/MediaBrowser.Common/Plugins/IPlugin.cs +++ b/MediaBrowser.Common/Plugins/IPlugin.cs @@ -62,18 +62,6 @@ namespace MediaBrowser.Common.Plugins /// Called when just before the plugin is uninstalled from the server. /// void OnUninstalling(); - - /// - /// Registers the plugin's services to the service collection. - /// - /// The service collection. - void RegisterServices(IServiceCollection serviceCollection); - - /// - /// Unregisters the plugin's services from the service collection. - /// - /// The service collection. - void UnregisterServices(IServiceCollection serviceCollection); } public interface IHasPluginConfiguration diff --git a/MediaBrowser.Common/Plugins/IPluginRegistrar.cs b/MediaBrowser.Common/Plugins/IPluginRegistrar.cs new file mode 100644 index 0000000000..79901c368e --- /dev/null +++ b/MediaBrowser.Common/Plugins/IPluginRegistrar.cs @@ -0,0 +1,17 @@ +namespace MediaBrowser.Common.Plugins +{ + using Microsoft.Extensions.DependencyInjection; + + /// + /// Defines the . + /// + public interface IPluginRegistrar + { + /// + /// Registers the plugin's services with the service collection. + /// This object is created prior to the plugin creation, so access to other classes is limited. + /// + /// The service collection. + void RegisterServices(IServiceCollection serviceCollection); + } +} From 8c0748b677eaac0eafefda774aef8abb5870aaf1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 16:41:30 +0100 Subject: [PATCH 0089/1930] Update BasePlugin.cs Added ConfigurationChanged event. --- MediaBrowser.Common/Plugins/BasePlugin.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index b89bc7eba5..55443e518e 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -175,6 +175,11 @@ namespace MediaBrowser.Common.Plugins /// The type of the configuration. public Type ConfigurationType => typeof(TConfigurationType); + /// + /// Gets or sets the event handler that is triggered when this configuration changes. + /// + public EventHandler ConfigurationChanged { get; set; } + /// /// Gets the name the assembly file. /// @@ -270,6 +275,8 @@ namespace MediaBrowser.Common.Plugins Configuration = (TConfigurationType)configuration; SaveConfiguration(); + + ConfigurationChanged.Invoke(this, configuration); } /// From 85d36a55a12c85af58fbfd2d3c087d21f6f3c387 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 18:26:59 +0100 Subject: [PATCH 0090/1930] Update BasePlugin.cs Removed trailing spaces --- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 55443e518e..e21d8c7d1b 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -275,7 +275,7 @@ namespace MediaBrowser.Common.Plugins Configuration = (TConfigurationType)configuration; SaveConfiguration(); - + ConfigurationChanged.Invoke(this, configuration); } From 7e939fa2cb16298d5c24db29a9115584e4a0679b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 19:56:05 +0100 Subject: [PATCH 0091/1930] Update BasePlugin.cs Plugins supporting di cannot be unloaded. --- MediaBrowser.Common/Plugins/BasePlugin.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index e21d8c7d1b..cfd9bbf1de 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -56,7 +56,8 @@ namespace MediaBrowser.Common.Plugins /// Gets a value indicating whether the plugin can be uninstalled. /// public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) - .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture); + .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) && + !typeof(IPluginRegistrar).IsAssignableFrom(typeof(this)); /// /// Gets the plugin info. From d31178ab4b60e2a71d57f64c6d96d3f0effc0bc7 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 20:00:46 +0100 Subject: [PATCH 0092/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index cfd9bbf1de..93e2867101 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.Common.Plugins /// public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) && - !typeof(IPluginRegistrar).IsAssignableFrom(typeof(this)); + !typeof(IPluginRegistrar).IsAssignableFrom(this.GetType()); /// /// Gets the plugin info. From ee976bb47abe2f16b7d27cd2f789264c5a9ec8d0 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Sun, 11 Oct 2020 15:27:11 -0600 Subject: [PATCH 0093/1930] Update MediaBrowser.Common/Plugins/LocalPlugin.cs Co-authored-by: BaronGreenback --- MediaBrowser.Common/Plugins/LocalPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index e26631615a..922fad23ae 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Common.Plugins /// Comparison result. public static bool operator !=(LocalPlugin left, LocalPlugin right) { - return !(left == right); + return !left.Equals(right); } /// From ae8a3bc02cffd01f4c64ec86fdcc9c807ec5b1a8 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:49:34 +0100 Subject: [PATCH 0094/1930] Update MediaBrowser.Common/Plugins/IPluginRegistrar.cs Co-authored-by: Claus Vium --- MediaBrowser.Common/Plugins/IPluginRegistrar.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/IPluginRegistrar.cs b/MediaBrowser.Common/Plugins/IPluginRegistrar.cs index 79901c368e..4e6265fe24 100644 --- a/MediaBrowser.Common/Plugins/IPluginRegistrar.cs +++ b/MediaBrowser.Common/Plugins/IPluginRegistrar.cs @@ -5,7 +5,7 @@ namespace MediaBrowser.Common.Plugins /// /// Defines the . /// - public interface IPluginRegistrar + public interface IPluginServiceRegistrator { /// /// Registers the plugin's services with the service collection. From ed05ae683e49bd9771f5817eb81a10fe40e49d94 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:49:51 +0100 Subject: [PATCH 0095/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Claus Vium --- Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index ea4c1ad08c..dd4c44e1af 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -137,7 +137,7 @@ namespace Emby.Server.Implementations.AppBase /// Manually pre-loads a factory so that it is available pre system initialisation. /// /// Class to register. - public virtual void RegisterConfiguration() + public virtual void RegisterConfiguration() where T : IConfigurationFactory { if (!typeof(IConfigurationFactory).IsAssignableFrom(typeof(T))) { From 387fdb0f1376f65b342c10e5222d7c0b56cdd8e5 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:50:36 +0100 Subject: [PATCH 0096/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Claus Vium --- .../AppBase/BaseConfigurationManager.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index dd4c44e1af..ca52b80cca 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -139,11 +139,6 @@ namespace Emby.Server.Implementations.AppBase /// Class to register. public virtual void RegisterConfiguration() where T : IConfigurationFactory { - if (!typeof(IConfigurationFactory).IsAssignableFrom(typeof(T))) - { - throw new ArgumentException("Parameter does not implement IConfigurationFactory"); - } - IConfigurationFactory factory = (IConfigurationFactory)Activator.CreateInstance(typeof(T)); if (_configurationFactories == null) From d49ba961230c438b25332a77ac345e22e3cb0ba6 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:50:48 +0100 Subject: [PATCH 0097/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 3f2307d80e..20cc9d76f6 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -825,7 +825,7 @@ namespace Emby.Server.Implementations _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray(); } - private void RegisterPlugInServices() + private void RegisterPluginServices() { foreach (var pluginServiceRegistrar in GetExportTypes()) { From 5c8015128f4e29cfa8fd15977d0984bb587b4f13 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:51:03 +0100 Subject: [PATCH 0098/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 20cc9d76f6..c1e6038acb 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -836,7 +836,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error registering {Assembly} with D.I.", pluginServiceRegistrar.Assembly); + Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrar.Assembly); } } } From 16a0357617f576c1fae9a996f36f92b903810087 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 11 Oct 2020 23:51:56 +0100 Subject: [PATCH 0099/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index c1e6038acb..11143128ac 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -502,7 +502,7 @@ namespace Emby.Server.Implementations RegisterServices(); - RegisterPlugInServices(); + RegisterPluginServices(); } /// From 37f38526995146c8731af6d3091113bd3e842017 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 11 Oct 2020 17:45:45 -0600 Subject: [PATCH 0100/1930] Add comma delimited string to array json converter --- .../JsonCommaDelimitedArrayConverter.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs new file mode 100644 index 0000000000..4f6a685314 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -0,0 +1,53 @@ +using System; +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// + /// Convert comma delimited string to array of type. + /// + /// Type to convert to. + public class JsonCommaDelimitedArrayConverter : JsonConverter + { + private readonly TypeConverter _typeConverter; + + /// + /// Initializes a new instance of the class. + /// + public JsonCommaDelimitedArrayConverter() + { + _typeConverter = TypeDescriptor.GetConverter(typeof(T)); + } + + /// + public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var stringEntries = reader.GetString()?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + if (stringEntries == null || stringEntries.Length == 0) + { + return Array.Empty(); + } + + var entries = new T[stringEntries.Length]; + for (var i = 0; i < stringEntries.Length; i++) + { + entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i]); + } + + return entries; + } + + return JsonSerializer.Deserialize(ref reader, options); + } + + /// + public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value, options); + } + } +} \ No newline at end of file From 7565ae22cb91c472928167ac89c39f67324c72e1 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 11 Oct 2020 21:09:15 -0600 Subject: [PATCH 0101/1930] Add tests and switch to factory --- ...JsonCommaDelimitedArrayConverterFactory.cs | 28 ++++++++ .../Json/JsonCommaDelimitedArrayTests.cs | 65 +++++++++++++++++++ .../Models/GenericBodyModel.cs | 20 ++++++ 3 files changed, 113 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs create mode 100644 tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs new file mode 100644 index 0000000000..b7b1daf76a --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// + /// Json comma delimited array converter factory. + /// + /// + /// This must be applied as an attribute, adding to the JsonConverter list causes stack overflow. + /// + public class JsonCommaDelimitedArrayConverterFactory : JsonConverterFactory + { + /// + public override bool CanConvert(Type typeToConvert) + { + return true; + } + + /// + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + var structType = typeToConvert.GetElementType(); + return (JsonConverter)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType)); + } + } +} \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs new file mode 100644 index 0000000000..c543cfee9f --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs @@ -0,0 +1,65 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Jellyfin.Common.Tests.Models; +using MediaBrowser.Model.Session; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public static class JsonCommaDelimitedArrayTests + { + [Fact] + public static void Deserialize_String_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a,b,c"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_String_Array_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""a"",""b"",""c""] }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Array_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + } +} \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs b/tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs new file mode 100644 index 0000000000..9a6c382fea --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs @@ -0,0 +1,20 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; + +namespace Jellyfin.Common.Tests.Models +{ + /// + /// The generic body model. + /// + /// The value type. + public class GenericBodyModel + { + /// + /// Gets or sets the value. + /// + [SuppressMessage("Microsoft.Performance", "CA1819:Properties should not return arrays", MessageId = "Value", Justification = "Imported from ServiceStack")] + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public T[] Value { get; set; } = default!; + } +} \ No newline at end of file From f7cc2f785c134d16c9ad7a5ed5d9a3e12455cbab Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 07:48:53 +0100 Subject: [PATCH 0102/1930] Rename IPluginRegistrar.cs to IPluginServiceRegistrator.cs --- .../Plugins/{IPluginRegistrar.cs => IPluginServiceRegistrator.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MediaBrowser.Common/Plugins/{IPluginRegistrar.cs => IPluginServiceRegistrator.cs} (100%) diff --git a/MediaBrowser.Common/Plugins/IPluginRegistrar.cs b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs similarity index 100% rename from MediaBrowser.Common/Plugins/IPluginRegistrar.cs rename to MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs From 53bea919d0fcc7812b30ac5c47668152f5c66689 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 07:51:09 +0100 Subject: [PATCH 0103/1930] Update IPluginServiceRegistrator.cs --- MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs index 4e6265fe24..cb6c27f862 100644 --- a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs +++ b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs @@ -3,7 +3,7 @@ namespace MediaBrowser.Common.Plugins using Microsoft.Extensions.DependencyInjection; /// - /// Defines the . + /// Defines the . /// public interface IPluginServiceRegistrator { From 257acbc2c94b4764d7654f29a63c8af299442b89 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 20:33:08 +0100 Subject: [PATCH 0104/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 93e2867101..11445d79d4 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.Common.Plugins /// public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) && - !typeof(IPluginRegistrar).IsAssignableFrom(this.GetType()); + !typeof(IPluginServiceRegistrator).IsAssignableFrom(this.GetType()); /// /// Gets the plugin info. From 63e514e6c438a07db5f20c7a8a79545c4029f915 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 20:34:18 +0100 Subject: [PATCH 0105/1930] Update ApplicationHost.cs --- Emby.Server.Implementations/ApplicationHost.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 11143128ac..62c70235d1 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -827,11 +827,11 @@ namespace Emby.Server.Implementations private void RegisterPluginServices() { - foreach (var pluginServiceRegistrar in GetExportTypes()) + foreach (var pluginServiceRegistrar in GetExportTypes()) { try { - var instance = (IPluginRegistrar)Activator.CreateInstance(pluginServiceRegistrar); + var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrar); instance.RegisterServices(ServiceCollection); } catch (Exception ex) From c7364be743004720a4ce1a45b07b3fa74f5fb8e0 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 20:53:10 +0100 Subject: [PATCH 0106/1930] Update IConfigurationManager.cs --- MediaBrowser.Common/Configuration/IConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 8cbeaea866..60faaa6172 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Common.Configuration /// Manually pre-loads a factory so that it is available pre system initialisation. /// /// Class to register. - void RegisterConfiguration(); + void RegisterConfiguration() where T : IConfigurationFactory; /// /// Gets the configuration. From 5e5f1cc9c57a2bca162f63b4c5ce559ae785344a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 20:56:37 +0100 Subject: [PATCH 0107/1930] Update IConfigurationManager.cs --- MediaBrowser.Common/Configuration/IConfigurationManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 60faaa6172..47c009ea9a 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -50,7 +50,8 @@ namespace MediaBrowser.Common.Configuration /// Manually pre-loads a factory so that it is available pre system initialisation. /// /// Class to register. - void RegisterConfiguration() where T : IConfigurationFactory; + void RegisterConfiguration() + where T : IConfigurationFactory; /// /// Gets the configuration. From 00b2539a7013abea12596333dbcce146bbd72745 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Oct 2020 21:00:54 +0100 Subject: [PATCH 0108/1930] Update IConfigurationManager.cs --- MediaBrowser.Common/Configuration/IConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 47c009ea9a..fc63d93503 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Common.Configuration /// Manually pre-loads a factory so that it is available pre system initialisation. /// /// Class to register. - void RegisterConfiguration() + void RegisterConfiguration() where T : IConfigurationFactory; /// From 15a7f88e083a78a4219cbd004e6041b49c490b05 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Oct 2020 11:44:11 -0600 Subject: [PATCH 0109/1930] Automatically clean activity log database --- .../Localization/Core/en-US.json | 2 + .../Tasks/CleanActivityLogTask.cs | 68 +++++++++++++++++++ .../Activity/ActivityManager.cs | 12 ++++ .../Activity/IActivityManager.cs | 7 ++ 4 files changed, 89 insertions(+) create mode 100644 Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs diff --git a/Emby.Server.Implementations/Localization/Core/en-US.json b/Emby.Server.Implementations/Localization/Core/en-US.json index 92c54fb0e6..bc973c9737 100644 --- a/Emby.Server.Implementations/Localization/Core/en-US.json +++ b/Emby.Server.Implementations/Localization/Core/en-US.json @@ -95,6 +95,8 @@ "TasksLibraryCategory": "Library", "TasksApplicationCategory": "Application", "TasksChannelsCategory": "Internet Channels", + "TaskCleanActivityLog": "Clean Activity Log", + "TaskCleanActivityLogDescription": "Deletes activity log entries older then the configured age.", "TaskCleanCache": "Clean Cache Directory", "TaskCleanCacheDescription": "Deletes cache files no longer needed by the system.", "TaskRefreshChapterImages": "Extract Chapter Images", diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs new file mode 100644 index 0000000000..50bc091c83 --- /dev/null +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Activity; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Tasks; + +namespace Emby.Server.Implementations.ScheduledTasks.Tasks +{ + /// + /// Deletes old activity log entries. + /// + public class CleanActivityLogTask : IScheduledTask, IConfigurableScheduledTask + { + private readonly ILocalizationManager _localization; + private readonly IActivityManager _activityManager; + + /// + /// Initializes a new instance of the class. + /// + /// Instance of the interface. + /// Instance of the interface. + public CleanActivityLogTask( + ILocalizationManager localization, + IActivityManager activityManager) + { + _localization = localization; + _activityManager = activityManager; + } + + /// + public string Name => _localization.GetLocalizedString("TaskCleanActivityLog"); + + /// + public string Key => "CleanActivityLog"; + + /// + public string Description => _localization.GetLocalizedString("TaskCleanActivityLogDescription"); + + /// + public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory"); + + /// + public bool IsHidden => false; + + /// + public bool IsEnabled => true; + + /// + public bool IsLogged => true; + + /// + public Task Execute(CancellationToken cancellationToken, IProgress progress) + { + // TODO allow configure + var startDate = DateTime.UtcNow.AddDays(-30); + return _activityManager.CleanAsync(startDate); + } + + /// + public IEnumerable GetDefaultTriggers() + { + return Enumerable.Empty(); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs index 5926abfe0d..7bde4f35be 100644 --- a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs +++ b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs @@ -72,6 +72,18 @@ namespace Jellyfin.Server.Implementations.Activity }; } + /// + public async Task CleanAsync(DateTime startDate) + { + await using var dbContext = _provider.CreateContext(); + var entries = dbContext.ActivityLogs + .AsQueryable() + .Where(entry => entry.DateCreated <= startDate); + + dbContext.RemoveRange(entries); + await dbContext.SaveChangesAsync().ConfigureAwait(false); + } + private static ActivityLogEntry ConvertToOldModel(ActivityLog entry) { return new ActivityLogEntry diff --git a/MediaBrowser.Model/Activity/IActivityManager.cs b/MediaBrowser.Model/Activity/IActivityManager.cs index 3e4ea208ed..28073fb8d7 100644 --- a/MediaBrowser.Model/Activity/IActivityManager.cs +++ b/MediaBrowser.Model/Activity/IActivityManager.cs @@ -16,5 +16,12 @@ namespace MediaBrowser.Model.Activity Task CreateAsync(ActivityLog entry); Task> GetPagedResultAsync(ActivityLogQuery query); + + /// + /// Remove all activity logs before the specified date. + /// + /// Activity log start date. + /// A representing the asynchronous operation. + Task CleanAsync(DateTime startDate); } } From 0e872ca65ccae174a0e4090f6a3197d6337356d6 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 14 Oct 2020 19:03:54 +0100 Subject: [PATCH 0110/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Cody Robibero --- .../AppBase/BaseConfigurationManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index ca52b80cca..bb22c31fe6 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -137,7 +137,8 @@ namespace Emby.Server.Implementations.AppBase /// Manually pre-loads a factory so that it is available pre system initialisation. /// /// Class to register. - public virtual void RegisterConfiguration() where T : IConfigurationFactory + public virtual void RegisterConfiguration() + where T : IConfigurationFactory { IConfigurationFactory factory = (IConfigurationFactory)Activator.CreateInstance(typeof(T)); From 002190f0a392a5f248f508cbd9ffd7a9fd4f3982 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 14 Oct 2020 19:04:09 +0100 Subject: [PATCH 0111/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Cody Robibero --- Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index bb22c31fe6..9e667a4975 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -144,7 +144,7 @@ namespace Emby.Server.Implementations.AppBase if (_configurationFactories == null) { - _configurationFactories = new IConfigurationFactory[] { factory }; + _configurationFactories = new[] { factory }; } else { From a8cee0bd36278035135bf871f25c126a12fde9ef Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 14 Oct 2020 19:04:17 +0100 Subject: [PATCH 0112/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Cody Robibero --- Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 9e667a4975..a5a361d24b 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -148,7 +148,7 @@ namespace Emby.Server.Implementations.AppBase } else { - var list = _configurationFactories.ToList(); + var list = _configurationFactories.ToList(); list.Add(factory); _configurationFactories = list.ToArray(); } From f2a86d9c80748b39c4bd798882dea79b7f345302 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Oct 2020 13:03:36 -0600 Subject: [PATCH 0113/1930] Remove CommaDelimitedArrayModelBinderProvider --- Jellyfin.Api/Controllers/ArtistsController.cs | 5 ++-- .../Controllers/ChannelsController.cs | 5 ++-- Jellyfin.Api/Controllers/GenresController.cs | 3 +- Jellyfin.Api/Controllers/ItemsController.cs | 5 ++-- .../Controllers/LibraryStructureController.cs | 3 +- .../Controllers/MusicGenresController.cs | 3 +- Jellyfin.Api/Controllers/PersonsController.cs | 3 +- Jellyfin.Api/Controllers/SessionController.cs | 2 +- Jellyfin.Api/Controllers/StudiosController.cs | 3 +- .../Controllers/TrailersController.cs | 5 ++-- .../CommaDelimitedArrayModelBinderProvider.cs | 29 ------------------- .../ApiServiceCollectionExtensions.cs | 3 -- 12 files changed, 23 insertions(+), 46 deletions(-) delete mode 100644 Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinderProvider.cs diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 784ecaeb32..37fc520b3a 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -89,7 +90,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, @@ -298,7 +299,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index fda00b8d46..20fc96ba83 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -121,7 +122,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? sortOrder, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] string? sortBy, [FromQuery] string? fields) { @@ -196,7 +197,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] string? fields, [FromQuery] string? channelIds) { diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index f4b69b312e..18ec0fe046 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -90,7 +91,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index b50b1e836b..c5f3a1aee1 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -159,7 +160,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isHd, [FromQuery] bool? is4K, [FromQuery] string? locationTypes, - [FromQuery] LocationType[] excludeLocationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, [FromQuery] double? minCommunityRating, @@ -182,7 +183,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? imageTypes, diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs index d290e3c5bd..94995650cb 100644 --- a/Jellyfin.Api/Controllers/LibraryStructureController.cs +++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Constants; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LibraryStructureDto; using MediaBrowser.Common.Progress; using MediaBrowser.Controller; @@ -75,7 +76,7 @@ namespace Jellyfin.Api.Controllers public async Task AddVirtualFolder( [FromQuery] string? name, [FromQuery] string? collectionType, - [FromQuery] string[] paths, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths, [FromBody] AddVirtualFolderDto? libraryOptionsDto, [FromQuery] bool refreshLibrary = false) { diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index d216b7f728..44616304f7 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -89,7 +90,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index bbef1ff9a1..5221595d86 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -89,7 +90,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 5656709629..e506ac7bf1 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -379,7 +379,7 @@ namespace Jellyfin.Api.Controllers public ActionResult PostCapabilities( [FromQuery] string? id, [FromQuery] string? playableMediaTypes, - [FromQuery] GeneralCommandType[] supportedCommands, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands, [FromQuery] bool supportsMediaControl = false, [FromQuery] bool supportsSync = false, [FromQuery] bool supportsPersistentIdentifier = true) diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 3a8ac1b243..da161f13e3 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -88,7 +89,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? genres, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index dec4498575..37b9687cd2 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -1,5 +1,6 @@ using System; using Jellyfin.Api.Constants; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -125,7 +126,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isHd, [FromQuery] bool? is4K, [FromQuery] string? locationTypes, - [FromQuery] LocationType[] excludeLocationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, [FromQuery] double? minCommunityRating, @@ -147,7 +148,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? parentId, [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, - [FromQuery] ItemFilter[] filters, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, [FromQuery] string? imageTypes, diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinderProvider.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinderProvider.cs deleted file mode 100644 index b9785a73b8..0000000000 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinderProvider.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Microsoft.AspNetCore.Mvc.ModelBinding; - -namespace Jellyfin.Api.ModelBinders -{ - /// - /// Comma delimited array model binder provider. - /// - public class CommaDelimitedArrayModelBinderProvider : IModelBinderProvider - { - private readonly IModelBinder _binder; - - /// - /// Initializes a new instance of the class. - /// - public CommaDelimitedArrayModelBinderProvider() - { - _binder = new CommaDelimitedArrayModelBinder(); - } - - /// - public IModelBinder? GetBinder(ModelBinderProviderContext context) - { - return context.Metadata.ModelType.IsArray ? _binder : null; - } - } -} diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index d7b9da5c2f..e180d0cd7a 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -16,7 +16,6 @@ using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Auth.RequiresElevationPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; -using Jellyfin.Api.ModelBinders; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -167,8 +166,6 @@ namespace Jellyfin.Server.Extensions opts.OutputFormatters.Add(new CssOutputFormatter()); opts.OutputFormatters.Add(new XmlOutputFormatter()); - - opts.ModelBinderProviders.Insert(0, new CommaDelimitedArrayModelBinderProvider()); }) // Clear app parts to avoid other assemblies being picked up From 39924f99927ae85b85095cfe9c2d7fb4ece7e75a Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Oct 2020 17:58:33 -0600 Subject: [PATCH 0114/1930] Allow apikey to authenticate as admin --- .../HttpServer/Security/AuthService.cs | 7 +- .../Security/AuthorizationContext.cs | 120 +++++++++--------- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 9 +- .../Auth/CustomAuthenticationHandler.cs | 14 +- 4 files changed, 77 insertions(+), 73 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 68d981ad1f..50c5b5b79e 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -19,12 +19,7 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo Authenticate(HttpRequest request) { var auth = _authorizationContext.GetAuthorizationInfo(request); - if (auth?.User == null) - { - return null; - } - - if (auth.User.HasPermission(PermissionKind.IsDisabled)) + if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false) { throw new SecurityException("User account has been disabled."); } diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 4b407dd9d2..c7666452c2 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -111,81 +111,83 @@ namespace Emby.Server.Implementations.HttpServer.Security Token = token }; - AuthenticationInfo originalAuthenticationInfo = null; - if (!string.IsNullOrWhiteSpace(token)) + if (string.IsNullOrWhiteSpace(token)) { - var result = _authRepo.Get(new AuthenticationInfoQuery + // Request doesn't contain a token. + throw new SecurityException("Unauthorized."); + } + + var result = _authRepo.Get(new AuthenticationInfoQuery + { + AccessToken = token + }); + + var originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null; + + if (originalAuthenticationInfo != null) + { + var updateToken = false; + + // TODO: Remove these checks for IsNullOrWhiteSpace + if (string.IsNullOrWhiteSpace(authInfo.Client)) { - AccessToken = token - }); + authInfo.Client = originalAuthenticationInfo.AppName; + } - originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null; - - if (originalAuthenticationInfo != null) + if (string.IsNullOrWhiteSpace(authInfo.DeviceId)) { - var updateToken = false; + authInfo.DeviceId = originalAuthenticationInfo.DeviceId; + } - // TODO: Remove these checks for IsNullOrWhiteSpace - if (string.IsNullOrWhiteSpace(authInfo.Client)) - { - authInfo.Client = originalAuthenticationInfo.AppName; - } + // Temporary. TODO - allow clients to specify that the token has been shared with a casting device + var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1; - if (string.IsNullOrWhiteSpace(authInfo.DeviceId)) + if (string.IsNullOrWhiteSpace(authInfo.Device)) + { + authInfo.Device = originalAuthenticationInfo.DeviceName; + } + else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase)) + { + if (allowTokenInfoUpdate) { - authInfo.DeviceId = originalAuthenticationInfo.DeviceId; + updateToken = true; + originalAuthenticationInfo.DeviceName = authInfo.Device; } + } - // Temporary. TODO - allow clients to specify that the token has been shared with a casting device - var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1; + if (string.IsNullOrWhiteSpace(authInfo.Version)) + { + authInfo.Version = originalAuthenticationInfo.AppVersion; + } + else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase)) + { + if (allowTokenInfoUpdate) + { + updateToken = true; + originalAuthenticationInfo.AppVersion = authInfo.Version; + } + } - if (string.IsNullOrWhiteSpace(authInfo.Device)) - { - authInfo.Device = originalAuthenticationInfo.DeviceName; - } - else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase)) - { - if (allowTokenInfoUpdate) - { - updateToken = true; - originalAuthenticationInfo.DeviceName = authInfo.Device; - } - } + if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3) + { + originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow; + updateToken = true; + } - if (string.IsNullOrWhiteSpace(authInfo.Version)) - { - authInfo.Version = originalAuthenticationInfo.AppVersion; - } - else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase)) - { - if (allowTokenInfoUpdate) - { - updateToken = true; - originalAuthenticationInfo.AppVersion = authInfo.Version; - } - } + if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty)) + { + authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId); - if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3) + if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase)) { - originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow; + originalAuthenticationInfo.UserName = authInfo.User.Username; updateToken = true; } + } - if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty)) - { - authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId); - - if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase)) - { - originalAuthenticationInfo.UserName = authInfo.User.Username; - updateToken = true; - } - } - - if (updateToken) - { - _authRepo.Update(originalAuthenticationInfo); - } + if (updateToken) + { + _authRepo.Update(originalAuthenticationInfo); } } diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index d732b6bc6a..c4567d058c 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,4 +1,5 @@ -using System.Security.Claims; +using System; +using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; @@ -57,6 +58,12 @@ namespace Jellyfin.Api.Auth return false; } + // UserId of Guid.Empty means token is an apikey. + if (userId.Equals(Guid.Empty)) + { + return true; + } + // Ensure userId links to a valid user. var user = _userManager.GetUserById(userId.Value); if (user == null) diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index 733c6959eb..ec5d172a21 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -1,3 +1,4 @@ +using System; using System.Globalization; using System.Security.Authentication; using System.Security.Claims; @@ -43,18 +44,17 @@ namespace Jellyfin.Api.Auth try { var authorizationInfo = _authService.Authenticate(Request); - if (authorizationInfo == null) + var role = UserRoles.User; + // UserId of Guid.Empty means token is an apikey. + if (authorizationInfo.UserId.Equals(Guid.Empty) || authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator)) { - return Task.FromResult(AuthenticateResult.NoResult()); - // TODO return when legacy API is removed. - // Don't spam the log with "Invalid User" - // return Task.FromResult(AuthenticateResult.Fail("Invalid user")); + role = UserRoles.Administrator; } var claims = new[] { - new Claim(ClaimTypes.Name, authorizationInfo.User.Username), - new Claim(ClaimTypes.Role, authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User), + new Claim(ClaimTypes.Name, authorizationInfo.User?.Username ?? string.Empty), + new Claim(ClaimTypes.Role, role), new Claim(InternalClaimTypes.UserId, authorizationInfo.UserId.ToString("N", CultureInfo.InvariantCulture)), new Claim(InternalClaimTypes.DeviceId, authorizationInfo.DeviceId), new Claim(InternalClaimTypes.Device, authorizationInfo.Device), From c037d3536d44b32de81a43425fb276ec4af5d103 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Oct 2020 17:58:46 -0600 Subject: [PATCH 0115/1930] clean up authorization handlers --- .../DefaultAuthorizationHandler.cs | 8 +++++--- .../IgnoreParentalControlHandler.cs | 8 +++++--- Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs | 6 +++--- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index b5913daab9..be77b7a4e4 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -29,13 +29,15 @@ namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DefaultAuthorizationRequirement requirement) { var validated = ValidateClaims(context.User); - if (!validated) + if (validated) + { + context.Succeed(requirement); + } + else { context.Fail(); - return Task.CompletedTask; } - context.Succeed(requirement); return Task.CompletedTask; } } diff --git a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs index 5213bc4cb7..a7623556a9 100644 --- a/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs +++ b/Jellyfin.Api/Auth/IgnoreParentalControlPolicy/IgnoreParentalControlHandler.cs @@ -29,13 +29,15 @@ namespace Jellyfin.Api.Auth.IgnoreParentalControlPolicy protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IgnoreParentalControlRequirement requirement) { var validated = ValidateClaims(context.User, ignoreSchedule: true); - if (!validated) + if (validated) + { + context.Succeed(requirement); + } + else { context.Fail(); - return Task.CompletedTask; } - context.Succeed(requirement); return Task.CompletedTask; } } diff --git a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs index af73352bcc..d772ec5542 100644 --- a/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessPolicy/LocalAccessHandler.cs @@ -29,13 +29,13 @@ namespace Jellyfin.Api.Auth.LocalAccessPolicy protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessRequirement requirement) { var validated = ValidateClaims(context.User, localAccessOnly: true); - if (!validated) + if (validated) { - context.Fail(); + context.Succeed(requirement); } else { - context.Succeed(requirement); + context.Fail(); } return Task.CompletedTask; From 4b6889615b877448b0a895b36c835e8d332584c6 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Oct 2020 18:21:15 -0600 Subject: [PATCH 0116/1930] Fix tests --- tests/Jellyfin.Api.Tests/TestHelpers.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/TestHelpers.cs b/tests/Jellyfin.Api.Tests/TestHelpers.cs index a4dd4e4092..c4ce398859 100644 --- a/tests/Jellyfin.Api.Tests/TestHelpers.cs +++ b/tests/Jellyfin.Api.Tests/TestHelpers.cs @@ -45,7 +45,7 @@ namespace Jellyfin.Api.Tests { new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Name, "jellyfin"), - new Claim(InternalClaimTypes.UserId, Guid.Empty.ToString("N", CultureInfo.InvariantCulture)), + new Claim(InternalClaimTypes.UserId, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture)), new Claim(InternalClaimTypes.DeviceId, Guid.Empty.ToString("N", CultureInfo.InvariantCulture)), new Claim(InternalClaimTypes.Device, "test"), new Claim(InternalClaimTypes.Client, "test"), From d5c226b1c3b04fa824adbcdc3eb0cbe09815f643 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 15 Oct 2020 08:02:59 -0600 Subject: [PATCH 0117/1930] Move SecurityException --- .../HttpServer/Security/AuthService.cs | 5 +++++ .../HttpServer/Security/AuthorizationContext.cs | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 50c5b5b79e..7d53e886f7 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -19,6 +19,11 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo Authenticate(HttpRequest request) { var auth = _authorizationContext.GetAuthorizationInfo(request); + if (auth == null) + { + throw new SecurityException("Unauthenticated request."); + } + if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false) { throw new SecurityException("User account has been disabled."); diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index c7666452c2..1f647b78bc 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.HttpServer.Security if (string.IsNullOrWhiteSpace(token)) { // Request doesn't contain a token. - throw new SecurityException("Unauthorized."); + return (null, null); } var result = _authRepo.Get(new AuthenticationInfoQuery From 5487dfc145096faeaa9ee82d92ffa224ef69fc11 Mon Sep 17 00:00:00 2001 From: gion Date: Tue, 12 May 2020 09:08:35 +0200 Subject: [PATCH 0118/1930] Rename GroupInfoView to GroupInfoDto --- .../SyncPlay/SyncPlayController.cs | 4 +- .../SyncPlay/SyncPlayManager.cs | 4 +- MediaBrowser.Api/SyncPlay/SyncPlayService.cs | 262 ++++++++++++++++++ .../SyncPlay/ISyncPlayController.cs | 2 +- .../SyncPlay/ISyncPlayManager.cs | 2 +- .../{GroupInfoView.cs => GroupInfoDto.cs} | 2 +- 6 files changed, 269 insertions(+), 7 deletions(-) create mode 100644 MediaBrowser.Api/SyncPlay/SyncPlayService.cs rename MediaBrowser.Model/SyncPlay/{GroupInfoView.cs => GroupInfoDto.cs} (97%) diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs index 5384795122..c98fd6d4af 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs @@ -499,9 +499,9 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public GroupInfoView GetInfo() + public GroupInfoDto GetInfo() { - return new GroupInfoView() + return new GroupInfoDto() { GroupId = GetGroupId().ToString(), PlayingItemName = _group.PlayingItem.Name, diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 966ed5024e..550939d701 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -286,13 +286,13 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public List ListGroups(SessionInfo session, Guid filterItemId) + public List ListGroups(SessionInfo session, Guid filterItemId) { var user = _userManager.GetUserById(session.UserId); if (user.SyncPlayAccess == SyncPlayAccess.None) { - return new List(); + return new List(); } // Filter by item if requested diff --git a/MediaBrowser.Api/SyncPlay/SyncPlayService.cs b/MediaBrowser.Api/SyncPlay/SyncPlayService.cs new file mode 100644 index 0000000000..6035f84e4a --- /dev/null +++ b/MediaBrowser.Api/SyncPlay/SyncPlayService.cs @@ -0,0 +1,262 @@ +using System.Threading; +using System; +using System.Collections.Generic; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay; +using MediaBrowser.Model.Services; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Api.SyncPlay +{ + [Route("/SyncPlay/New", "POST", Summary = "Create a new SyncPlay group")] + [Authenticated] + public class SyncPlayNew : IReturnVoid + { + } + + [Route("/SyncPlay/Join", "POST", Summary = "Join an existing SyncPlay group")] + [Authenticated] + public class SyncPlayJoin : IReturnVoid + { + /// + /// Gets or sets the Group id. + /// + /// The Group id to join. + [ApiMember(Name = "GroupId", Description = "Group Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] + public string GroupId { get; set; } + } + + [Route("/SyncPlay/Leave", "POST", Summary = "Leave joined SyncPlay group")] + [Authenticated] + public class SyncPlayLeave : IReturnVoid + { + } + + [Route("/SyncPlay/List", "GET", Summary = "List SyncPlay groups")] + [Authenticated] + public class SyncPlayList : IReturnVoid + { + /// + /// Gets or sets the filter item id. + /// + /// The filter item id. + [ApiMember(Name = "FilterItemId", Description = "Filter by item id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] + public string FilterItemId { get; set; } + } + + [Route("/SyncPlay/Play", "POST", Summary = "Request play in SyncPlay group")] + [Authenticated] + public class SyncPlayPlay : IReturnVoid + { + } + + [Route("/SyncPlay/Pause", "POST", Summary = "Request pause in SyncPlay group")] + [Authenticated] + public class SyncPlayPause : IReturnVoid + { + } + + [Route("/SyncPlay/Seek", "POST", Summary = "Request seek in SyncPlay group")] + [Authenticated] + public class SyncPlaySeek : IReturnVoid + { + [ApiMember(Name = "PositionTicks", IsRequired = true, DataType = "long", ParameterType = "query", Verb = "POST")] + public long PositionTicks { get; set; } + } + + [Route("/SyncPlay/Buffering", "POST", Summary = "Request group wait in SyncPlay group while buffering")] + [Authenticated] + public class SyncPlayBuffering : IReturnVoid + { + /// + /// Gets or sets the date used to pin PositionTicks in time. + /// + /// The date related to PositionTicks. + [ApiMember(Name = "When", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] + public string When { get; set; } + + [ApiMember(Name = "PositionTicks", IsRequired = true, DataType = "long", ParameterType = "query", Verb = "POST")] + public long PositionTicks { get; set; } + + /// + /// Gets or sets whether this is a buffering or a ready request. + /// + /// true if buffering is complete; false otherwise. + [ApiMember(Name = "BufferingDone", IsRequired = true, DataType = "bool", ParameterType = "query", Verb = "POST")] + public bool BufferingDone { get; set; } + } + + [Route("/SyncPlay/Ping", "POST", Summary = "Update session ping")] + [Authenticated] + public class SyncPlayPing : IReturnVoid + { + [ApiMember(Name = "Ping", IsRequired = true, DataType = "double", ParameterType = "query", Verb = "POST")] + public double Ping { get; set; } + } + + /// + /// Class SyncPlayService. + /// + public class SyncPlayService : BaseApiService + { + /// + /// The session context. + /// + private readonly ISessionContext _sessionContext; + + /// + /// The SyncPlay manager. + /// + private readonly ISyncPlayManager _syncPlayManager; + + public SyncPlayService( + ILogger logger, + IServerConfigurationManager serverConfigurationManager, + IHttpResultFactory httpResultFactory, + ISessionContext sessionContext, + ISyncPlayManager syncPlayManager) + : base(logger, serverConfigurationManager, httpResultFactory) + { + _sessionContext = sessionContext; + _syncPlayManager = syncPlayManager; + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayNew request) + { + var currentSession = GetSession(_sessionContext); + _syncPlayManager.NewGroup(currentSession, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayJoin request) + { + var currentSession = GetSession(_sessionContext); + + Guid groupId; + if (!Guid.TryParse(request.GroupId, out groupId)) + { + Logger.LogError("JoinGroup: {0} is not a valid format for GroupId. Ignoring request.", request.GroupId); + return; + } + + var joinRequest = new JoinGroupRequest() + { + GroupId = groupId + }; + + _syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayLeave request) + { + var currentSession = GetSession(_sessionContext); + _syncPlayManager.LeaveGroup(currentSession, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + /// The requested list of groups. + public List Get(SyncPlayListGroups request) + { + var currentSession = GetSession(_sessionContext); + var filterItemId = Guid.Empty; + + if (!string.IsNullOrEmpty(request.FilterItemId) && !Guid.TryParse(request.FilterItemId, out filterItemId)) + { + Logger.LogWarning("ListGroups: {0} is not a valid format for FilterItemId. Ignoring filter.", request.FilterItemId); + } + + return _syncPlayManager.ListGroups(currentSession, filterItemId); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayPlay request) + { + var currentSession = GetSession(_sessionContext); + var syncPlayRequest = new PlaybackRequest() + { + Type = PlaybackRequestType.Play + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayPause request) + { + var currentSession = GetSession(_sessionContext); + var syncPlayRequest = new PlaybackRequest() + { + Type = PlaybackRequestType.Pause + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlaySeek request) + { + var currentSession = GetSession(_sessionContext); + var syncPlayRequest = new PlaybackRequest() + { + Type = PlaybackRequestType.Seek, + PositionTicks = request.PositionTicks + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayBuffering request) + { + var currentSession = GetSession(_sessionContext); + var syncPlayRequest = new PlaybackRequest() + { + Type = request.BufferingDone ? PlaybackRequestType.Ready : PlaybackRequestType.Buffer, + When = DateTime.Parse(request.When), + PositionTicks = request.PositionTicks + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + } + + /// + /// Handles the specified request. + /// + /// The request. + public void Post(SyncPlayPing request) + { + var currentSession = GetSession(_sessionContext); + var syncPlayRequest = new PlaybackRequest() + { + Type = PlaybackRequestType.Ping, + Ping = Convert.ToInt64(request.Ping) + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs index 60d17fe367..d869c05bd1 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs @@ -62,6 +62,6 @@ namespace MediaBrowser.Controller.SyncPlay /// Gets the info about the group for the clients. /// /// The group info for the clients. - GroupInfoView GetInfo(); + GroupInfoDto GetInfo(); } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 006fb687b8..65770021dc 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -40,7 +40,7 @@ namespace MediaBrowser.Controller.SyncPlay /// The session. /// The item id to filter by. /// The list of available groups. - List ListGroups(SessionInfo session, Guid filterItemId); + List ListGroups(SessionInfo session, Guid filterItemId); /// /// Handle a request by a session in a group. diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoView.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs similarity index 97% rename from MediaBrowser.Model/SyncPlay/GroupInfoView.cs rename to MediaBrowser.Model/SyncPlay/GroupInfoDto.cs index f4c6859988..ac84a26dc3 100644 --- a/MediaBrowser.Model/SyncPlay/GroupInfoView.cs +++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Model.SyncPlay /// /// Class GroupInfoView. /// - public class GroupInfoView + public class GroupInfoDto { /// /// Gets or sets the group identifier. From e10799e0e8d7afcdf07585ac4b27dd060c973d8f Mon Sep 17 00:00:00 2001 From: gion Date: Tue, 12 May 2020 19:05:05 +0200 Subject: [PATCH 0119/1930] Rewrite syncplay using a state design pattern --- .../SyncPlay/GroupStates/PausedGroupState.cs | 171 ++++++ .../SyncPlay/GroupStates/PlayingGroupState.cs | 94 ++++ .../SyncPlay/SyncPlayController.cs | 502 +++++------------- .../SyncPlay/SyncPlayManager.cs | 4 +- MediaBrowser.Api/SyncPlay/SyncPlayService.cs | 41 +- MediaBrowser.Controller/SyncPlay/GroupInfo.cs | 6 - .../SyncPlay/IPlaybackGroupRequest.cs | 24 + .../SyncPlay/ISyncPlayController.cs | 2 +- .../SyncPlay/ISyncPlayManager.cs | 2 +- .../SyncPlay/ISyncPlayState.cs | 95 ++++ .../SyncPlay/ISyncPlayStateContext.cs | 75 +++ .../PlaybackRequest/BufferGroupRequest.cs | 43 ++ .../PlaybackRequest/PauseGroupRequest.cs | 24 + .../PlaybackRequest/PingGroupRequest.cs | 31 ++ .../PlaybackRequest/PlayGroupRequest.cs | 24 + .../PlaybackRequest/ReadyGroupRequest.cs | 43 ++ .../PlaybackRequest/SeekGroupRequest.cs | 30 ++ .../SyncPlay/SyncPlayAbstractState.cs | 65 +++ MediaBrowser.Model/SyncPlay/GroupState.cs | 25 + .../SyncPlay/PlaybackRequest.cs | 34 -- .../SyncPlay/SyncPlayBroadcastType.cs | 28 + 21 files changed, 934 insertions(+), 429 deletions(-) create mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs create mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs create mode 100644 MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs create mode 100644 MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs create mode 100644 MediaBrowser.Model/SyncPlay/GroupState.cs delete mode 100644 MediaBrowser.Model/SyncPlay/PlaybackRequest.cs create mode 100644 MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs new file mode 100644 index 0000000000..d3bf24f747 --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs @@ -0,0 +1,171 @@ +using System.Linq; +using System; +using System.Threading; +using System.Collections.Generic; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class PausedGroupState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public class PausedGroupState : SyncPlayAbstractState + { + /// + public override GroupState GetGroupState() + { + return GroupState.Paused; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var playingState = new PlayingGroupState(); + context.SetState(playingState); + return playingState.HandleRequest(context, true, request, session, cancellationToken); + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + if (newState) + { + GroupInfo group = context.GetGroup(); + + // Pause group and compute the media playback position + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - group.LastActivity; + group.LastActivity = currentTime; + // Seek only if playback actually started + // Pause request may be issued during the delay added to account for latency + group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + } + else + { + // Client got lost, sending current state + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + + return true; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + GroupInfo group = context.GetGroup(); + + // Sanitize PositionTicks + var ticks = context.SanitizePositionTicks(request.PositionTicks); + + // Seek + group.PositionTicks = ticks; + group.LastActivity = DateTime.UtcNow; + + var command = context.NewSyncPlayCommand(SendCommandType.Seek); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + + return true; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + GroupInfo group = context.GetGroup(); + + if (newState) + { + // Pause group and compute the media playback position + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - group.LastActivity; + group.LastActivity = currentTime; + group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + + group.SetBuffering(session, true); + + // Send pause command to all non-buffering sessions + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); + + var updateOthers = context.NewSyncPlayGroupUpdate(GroupUpdateType.GroupWait, session.UserName); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + } + else + { + // TODO: no idea? + // group.SetBuffering(session, true); + + // Client got lost, sending current state + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + + return true; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + GroupInfo group = context.GetGroup(); + + group.SetBuffering(session, false); + + var requestTicks = context.SanitizePositionTicks(request.PositionTicks); + + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - request.When; + var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime; + var delay = group.PositionTicks - clientPosition.Ticks; + + if (group.IsBuffering()) + { + // Others are still buffering, tell this client to pause when ready + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + var pauseAtTime = currentTime.AddMilliseconds(delay); + command.When = context.DateToUTCString(pauseAtTime); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + else + { + // Let other clients resume as soon as the buffering client catches up + if (delay > group.GetHighestPing() * 2) + { + // Client that was buffering is recovering, notifying others to resume + group.LastActivity = currentTime.AddMilliseconds( + delay + ); + var command = context.NewSyncPlayCommand(SendCommandType.Play); + context.SendCommand(session, SyncPlayBroadcastType.AllExceptCurrentSession, command, cancellationToken); + } + else + { + // Client, that was buffering, resumed playback but did not update others in time + delay = Math.Max(group.GetHighestPing() * 2, group.DefaultPing); + + group.LastActivity = currentTime.AddMilliseconds( + delay + ); + + var command = context.NewSyncPlayCommand(SendCommandType.Play); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + } + + // Change state + var playingState = new PlayingGroupState(); + context.SetState(playingState); + } + + return true; + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs new file mode 100644 index 0000000000..42c7779c19 --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs @@ -0,0 +1,94 @@ +using System.Linq; +using System; +using System.Threading; +using System.Collections.Generic; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class PlayingGroupState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public class PlayingGroupState : SyncPlayAbstractState + { + /// + public override GroupState GetGroupState() + { + return GroupState.Playing; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + GroupInfo group = context.GetGroup(); + + if (newState) + { + // Pick a suitable time that accounts for latency + var delay = Math.Max(group.GetHighestPing() * 2, group.DefaultPing); + + // Unpause group and set starting point in future + // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position) + // The added delay does not guarantee, of course, that the command will be received in time + // Playback synchronization will mainly happen client side + group.LastActivity = DateTime.UtcNow.AddMilliseconds( + delay + ); + + var command = context.NewSyncPlayCommand(SendCommandType.Play); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + } + else + { + // Client got lost, sending current state + var command = context.NewSyncPlayCommand(SendCommandType.Play); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + + return true; + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var pausedState = new PausedGroupState(); + context.SetState(pausedState); + return pausedState.HandleRequest(context, true, request, session, cancellationToken); + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var pausedState = new PausedGroupState(); + context.SetState(pausedState); + return pausedState.HandleRequest(context, true, request, session, cancellationToken); + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var pausedState = new PausedGroupState(); + context.SetState(pausedState); + return pausedState.HandleRequest(context, true, request, session, cancellationToken); + } + + /// + public override bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Group was not waiting, make sure client has latest state + var command = context.NewSyncPlayCommand(SendCommandType.Play); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + + return true; + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs index c98fd6d4af..225be7430d 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs @@ -8,6 +8,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Model.Session; using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay { @@ -17,34 +18,8 @@ namespace Emby.Server.Implementations.SyncPlay /// /// Class is not thread-safe, external locking is required when accessing methods. /// - public class SyncPlayController : ISyncPlayController + public class SyncPlayController : ISyncPlayController, ISyncPlayStateContext { - /// - /// Used to filter the sessions of a group. - /// - private enum BroadcastType - { - /// - /// All sessions will receive the message. - /// - AllGroup = 0, - - /// - /// Only the specified session will receive the message. - /// - CurrentSession = 1, - - /// - /// All sessions, except the current one, will receive the message. - /// - AllExceptCurrentSession = 2, - - /// - /// Only sessions that are not buffering will receive the message. - /// - AllReady = 3 - } - /// /// The session manager. /// @@ -55,22 +30,33 @@ namespace Emby.Server.Implementations.SyncPlay /// private readonly ISyncPlayManager _syncPlayManager; + /// + /// The logger. + /// + private readonly ILogger _logger; + /// /// The group to manage. /// private readonly GroupInfo _group = new GroupInfo(); /// - /// Initializes a new instance of the class. + /// Internal group state. /// - /// The session manager. - /// The SyncPlay manager. - public SyncPlayController( - ISessionManager sessionManager, - ISyncPlayManager syncPlayManager) + /// The group's state. + private ISyncPlayState State = new PausedGroupState(); + + /// + public GroupInfo GetGroup() { - _sessionManager = sessionManager; - _syncPlayManager = syncPlayManager; + return _group; + } + + /// + public void SetState(ISyncPlayState state) + { + _logger.LogInformation("SetState: {0} -> {1}.", State.GetGroupState(), state.GetGroupState()); + this.State = state; } /// @@ -83,13 +69,18 @@ namespace Emby.Server.Implementations.SyncPlay public bool IsGroupEmpty() => _group.IsEmpty(); /// - /// Converts DateTime to UTC string. + /// Initializes a new instance of the class. /// - /// The date to convert. - /// The UTC string. - private string DateToUTCString(DateTime date) + /// The session manager. + /// The SyncPlay manager. + public SyncPlayController( + ISessionManager sessionManager, + ISyncPlayManager syncPlayManager, + ILogger logger) { - return date.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture); + _sessionManager = sessionManager; + _syncPlayManager = syncPlayManager; + _logger = logger; } /// @@ -98,37 +89,30 @@ namespace Emby.Server.Implementations.SyncPlay /// The current session. /// The filtering type. /// The array of sessions matching the filter. - private IEnumerable FilterSessions(SessionInfo from, BroadcastType type) + private SessionInfo[] FilterSessions(SessionInfo from, SyncPlayBroadcastType type) { switch (type) { - case BroadcastType.CurrentSession: + case SyncPlayBroadcastType.CurrentSession: return new SessionInfo[] { from }; - case BroadcastType.AllGroup: - return _group.Participants.Values - .Select(session => session.Session); - case BroadcastType.AllExceptCurrentSession: - return _group.Participants.Values - .Select(session => session.Session) - .Where(session => !session.Id.Equals(from.Id, StringComparison.Ordinal)); - case BroadcastType.AllReady: - return _group.Participants.Values - .Where(session => !session.IsBuffering) - .Select(session => session.Session); + case SyncPlayBroadcastType.AllGroup: + return _group.Participants.Values.Select( + session => session.Session).ToArray(); + case SyncPlayBroadcastType.AllExceptCurrentSession: + return _group.Participants.Values.Select( + session => session.Session).Where( + session => !session.Id.Equals(from.Id)).ToArray(); + case SyncPlayBroadcastType.AllReady: + return _group.Participants.Values.Where( + session => !session.IsBuffering).Select( + session => session.Session).ToArray(); default: return Array.Empty(); } } - /// - /// Sends a GroupUpdate message to the interested sessions. - /// - /// The current session. - /// The filtering type. - /// The message to send. - /// The cancellation token. - /// The task. - private Task SendGroupUpdate(SessionInfo from, BroadcastType type, GroupUpdate message, CancellationToken cancellationToken) + /// + public Task SendGroupUpdate(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate message, CancellationToken cancellationToken) { IEnumerable GetTasks() { @@ -141,15 +125,8 @@ namespace Emby.Server.Implementations.SyncPlay return Task.WhenAll(GetTasks()); } - /// - /// Sends a playback command to the interested sessions. - /// - /// The current session. - /// The filtering type. - /// The message to send. - /// The cancellation token. - /// The task. - private Task SendCommand(SessionInfo from, BroadcastType type, SendCommand message, CancellationToken cancellationToken) + /// + public Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken) { IEnumerable GetTasks() { @@ -162,12 +139,8 @@ namespace Emby.Server.Implementations.SyncPlay return Task.WhenAll(GetTasks()); } - /// - /// Builds a new playback command with some default values. - /// - /// The command type. - /// The SendCommand. - private SendCommand NewSyncPlayCommand(SendCommandType type) + /// + public SendCommand NewSyncPlayCommand(SendCommandType type) { return new SendCommand() { @@ -179,13 +152,8 @@ namespace Emby.Server.Implementations.SyncPlay }; } - /// - /// Builds a new group update message. - /// - /// The update type. - /// The data to send. - /// The GroupUpdate. - private GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data) + /// + public GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data) { return new GroupUpdate() { @@ -196,285 +164,13 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public void CreateGroup(SessionInfo session, CancellationToken cancellationToken) + public string DateToUTCString(DateTime _date) { - _group.AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); - - _group.PlayingItem = session.FullNowPlayingItem; - _group.IsPaused = session.PlayState.IsPaused; - _group.PositionTicks = session.PlayState.PositionTicks ?? 0; - _group.LastActivity = DateTime.UtcNow; - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); - SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken); + return _date.ToUniversalTime().ToString("o"); } /// - public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) - { - if (session.NowPlayingItem?.Id == _group.PlayingItem.Id) - { - _group.AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); - SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); - SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - - // Syncing will happen client-side - if (!_group.IsPaused) - { - var playCommand = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.CurrentSession, playCommand, cancellationToken); - } - else - { - var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, BroadcastType.CurrentSession, pauseCommand, cancellationToken); - } - } - else - { - var playRequest = new PlayRequest - { - ItemIds = new Guid[] { _group.PlayingItem.Id }, - StartPositionTicks = _group.PositionTicks - }; - var update = NewSyncPlayGroupUpdate(GroupUpdateType.PrepareSession, playRequest); - SendGroupUpdate(session, BroadcastType.CurrentSession, update, cancellationToken); - } - } - - /// - public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) - { - _group.RemoveSession(session); - _syncPlayManager.RemoveSessionFromGroup(session, this); - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks); - SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); - SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - } - - /// - public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - // The server's job is to maintain a consistent state for clients to reference - // and notify clients of state changes. The actual syncing of media playback - // happens client side. Clients are aware of the server's time and use it to sync. - switch (request.Type) - { - case PlaybackRequestType.Play: - HandlePlayRequest(session, request, cancellationToken); - break; - case PlaybackRequestType.Pause: - HandlePauseRequest(session, request, cancellationToken); - break; - case PlaybackRequestType.Seek: - HandleSeekRequest(session, request, cancellationToken); - break; - case PlaybackRequestType.Buffer: - HandleBufferingRequest(session, request, cancellationToken); - break; - case PlaybackRequestType.Ready: - HandleBufferingDoneRequest(session, request, cancellationToken); - break; - case PlaybackRequestType.Ping: - HandlePingUpdateRequest(session, request); - break; - } - } - - /// - /// Handles a play action requested by a session. - /// - /// The session. - /// The play action. - /// The cancellation token. - private void HandlePlayRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - if (_group.IsPaused) - { - // Pick a suitable time that accounts for latency - var delay = Math.Max(_group.GetHighestPing() * 2, GroupInfo.DefaultPing); - - // Unpause group and set starting point in future - // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position) - // The added delay does not guarantee, of course, that the command will be received in time - // Playback synchronization will mainly happen client side - _group.IsPaused = false; - _group.LastActivity = DateTime.UtcNow.AddMilliseconds( - delay); - - var command = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.AllGroup, command, cancellationToken); - } - else - { - // Client got lost, sending current state - var command = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken); - } - } - - /// - /// Handles a pause action requested by a session. - /// - /// The session. - /// The pause action. - /// The cancellation token. - private void HandlePauseRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - if (!_group.IsPaused) - { - // Pause group and compute the media playback position - _group.IsPaused = true; - var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - _group.LastActivity; - _group.LastActivity = currentTime; - - // Seek only if playback actually started - // Pause request may be issued during the delay added to account for latency - _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; - - var command = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, BroadcastType.AllGroup, command, cancellationToken); - } - else - { - // Client got lost, sending current state - var command = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken); - } - } - - /// - /// Handles a seek action requested by a session. - /// - /// The session. - /// The seek action. - /// The cancellation token. - private void HandleSeekRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - // Sanitize PositionTicks - var ticks = SanitizePositionTicks(request.PositionTicks); - - // Pause and seek - _group.IsPaused = true; - _group.PositionTicks = ticks; - _group.LastActivity = DateTime.UtcNow; - - var command = NewSyncPlayCommand(SendCommandType.Seek); - SendCommand(session, BroadcastType.AllGroup, command, cancellationToken); - } - - /// - /// Handles a buffering action requested by a session. - /// - /// The session. - /// The buffering action. - /// The cancellation token. - private void HandleBufferingRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - if (!_group.IsPaused) - { - // Pause group and compute the media playback position - _group.IsPaused = true; - var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - _group.LastActivity; - _group.LastActivity = currentTime; - _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; - - _group.SetBuffering(session, true); - - // Send pause command to all non-buffering sessions - var command = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, BroadcastType.AllReady, command, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.GroupWait, session.UserName); - SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - } - else - { - // Client got lost, sending current state - var command = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken); - } - } - - /// - /// Handles a buffering-done action requested by a session. - /// - /// The session. - /// The buffering-done action. - /// The cancellation token. - private void HandleBufferingDoneRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) - { - if (_group.IsPaused) - { - _group.SetBuffering(session, false); - - var requestTicks = SanitizePositionTicks(request.PositionTicks); - - var when = request.When ?? DateTime.UtcNow; - var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - when; - var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime; - var delay = _group.PositionTicks - clientPosition.Ticks; - - if (_group.IsBuffering()) - { - // Others are still buffering, tell this client to pause when ready - var command = NewSyncPlayCommand(SendCommandType.Pause); - var pauseAtTime = currentTime.AddMilliseconds(delay); - command.When = DateToUTCString(pauseAtTime); - SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken); - } - else - { - // Let other clients resume as soon as the buffering client catches up - _group.IsPaused = false; - - if (delay > _group.GetHighestPing() * 2) - { - // Client that was buffering is recovering, notifying others to resume - _group.LastActivity = currentTime.AddMilliseconds( - delay); - var command = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.AllExceptCurrentSession, command, cancellationToken); - } - else - { - // Client, that was buffering, resumed playback but did not update others in time - delay = Math.Max(_group.GetHighestPing() * 2, GroupInfo.DefaultPing); - - _group.LastActivity = currentTime.AddMilliseconds( - delay); - - var command = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.AllGroup, command, cancellationToken); - } - } - } - else - { - // Group was not waiting, make sure client has latest state - var command = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken); - } - } - - /// - /// Sanitizes the PositionTicks, considers the current playing item when available. - /// - /// The PositionTicks. - /// The sanitized PositionTicks. - private long SanitizePositionTicks(long? positionTicks) + public long SanitizePositionTicks(long? positionTicks) { var ticks = positionTicks ?? 0; ticks = ticks >= 0 ? ticks : 0; @@ -487,15 +183,87 @@ namespace Emby.Server.Implementations.SyncPlay return ticks; } - /// - /// Updates ping of a session. - /// - /// The session. - /// The update. - private void HandlePingUpdateRequest(SessionInfo session, PlaybackRequest request) + /// + public void CreateGroup(SessionInfo session, CancellationToken cancellationToken) { - // Collected pings are used to account for network latency when unpausing playback - _group.UpdatePing(session, request.Ping ?? GroupInfo.DefaultPing); + _group.AddSession(session); + _syncPlayManager.AddSessionToGroup(session, this); + + State = new PausedGroupState(); + + _group.PlayingItem = session.FullNowPlayingItem; + // TODO: looks like new groups should mantain playstate (and not force to pause) + // _group.IsPaused = session.PlayState.IsPaused; + _group.PositionTicks = session.PlayState.PositionTicks ?? 0; + _group.LastActivity = DateTime.UtcNow; + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + // TODO: looks like new groups should mantain playstate (and not force to pause) + var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause); + SendCommand(session, SyncPlayBroadcastType.CurrentSession, pauseCommand, cancellationToken); + } + + /// + public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) + { + if (session.NowPlayingItem?.Id == _group.PlayingItem.Id) + { + _group.AddSession(session); + _syncPlayManager.AddSessionToGroup(session, this); + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); + SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + + // Syncing will happen client-side + if (State.GetGroupState().Equals(GroupState.Playing)) + { + var playCommand = NewSyncPlayCommand(SendCommandType.Play); + SendCommand(session, SyncPlayBroadcastType.CurrentSession, playCommand, cancellationToken); + } + else + { + var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause); + SendCommand(session, SyncPlayBroadcastType.CurrentSession, pauseCommand, cancellationToken); + } + } + else + { + var playRequest = new PlayRequest + { + ItemIds = new Guid[] { _group.PlayingItem.Id }, + StartPositionTicks = _group.PositionTicks + }; + var update = NewSyncPlayGroupUpdate(GroupUpdateType.PrepareSession, playRequest); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken); + } + } + + /// + public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) + { + _group.RemoveSession(session); + _syncPlayManager.RemoveSessionFromGroup(session, this); + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); + SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + } + + /// + public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) + { + // The server's job is to maintain a consistent state for clients to reference + // and notify clients of state changes. The actual syncing of media playback + // happens client side. Clients are aware of the server's time and use it to sync. + _logger.LogInformation("HandleRequest: {0}:{1}.", request.GetType(), State.GetGroupState()); + _ = request.Apply(this, State, session, cancellationToken); + // TODO: do something with returned value } /// diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 550939d701..b85f3c1496 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -186,7 +186,7 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } - var group = new SyncPlayController(_sessionManager, this); + var group = new SyncPlayController(_sessionManager, this, _logger); _groups[group.GetGroupId()] = group; group.CreateGroup(session, cancellationToken); @@ -312,7 +312,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) + public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) { var user = _userManager.GetUserById(session.UserId); diff --git a/MediaBrowser.Api/SyncPlay/SyncPlayService.cs b/MediaBrowser.Api/SyncPlay/SyncPlayService.cs index 6035f84e4a..bd9670f07a 100644 --- a/MediaBrowser.Api/SyncPlay/SyncPlayService.cs +++ b/MediaBrowser.Api/SyncPlay/SyncPlayService.cs @@ -172,7 +172,7 @@ namespace MediaBrowser.Api.SyncPlay /// /// The request. /// The requested list of groups. - public List Get(SyncPlayListGroups request) + public List Get(SyncPlayList request) { var currentSession = GetSession(_sessionContext); var filterItemId = Guid.Empty; @@ -192,10 +192,7 @@ namespace MediaBrowser.Api.SyncPlay public void Post(SyncPlayPlay request) { var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlaybackRequest() - { - Type = PlaybackRequestType.Play - }; + var syncPlayRequest = new PlayGroupRequest(); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); } @@ -206,10 +203,7 @@ namespace MediaBrowser.Api.SyncPlay public void Post(SyncPlayPause request) { var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlaybackRequest() - { - Type = PlaybackRequestType.Pause - }; + var syncPlayRequest = new PauseGroupRequest(); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); } @@ -220,9 +214,8 @@ namespace MediaBrowser.Api.SyncPlay public void Post(SyncPlaySeek request) { var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlaybackRequest() + var syncPlayRequest = new SeekGroupRequest() { - Type = PlaybackRequestType.Seek, PositionTicks = request.PositionTicks }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); @@ -235,12 +228,25 @@ namespace MediaBrowser.Api.SyncPlay public void Post(SyncPlayBuffering request) { var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlaybackRequest() + + IPlaybackGroupRequest syncPlayRequest; + if (!request.BufferingDone) { - Type = request.BufferingDone ? PlaybackRequestType.Ready : PlaybackRequestType.Buffer, - When = DateTime.Parse(request.When), - PositionTicks = request.PositionTicks - }; + syncPlayRequest = new BufferGroupRequest() + { + When = DateTime.Parse(request.When), + PositionTicks = request.PositionTicks + }; + } + else + { + syncPlayRequest = new ReadyGroupRequest() + { + When = DateTime.Parse(request.When), + PositionTicks = request.PositionTicks + }; + } + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); } @@ -251,9 +257,8 @@ namespace MediaBrowser.Api.SyncPlay public void Post(SyncPlayPing request) { var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlaybackRequest() + var syncPlayRequest = new PingGroupRequest() { - Type = PlaybackRequestType.Ping, Ping = Convert.ToInt64(request.Ping) }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); diff --git a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs b/MediaBrowser.Controller/SyncPlay/GroupInfo.cs index a1cada25cc..cdd24d0b59 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupInfo.cs @@ -30,12 +30,6 @@ namespace MediaBrowser.Controller.SyncPlay /// The playing item. public BaseItem PlayingItem { get; set; } - /// - /// Gets or sets a value indicating whether playback is paused. - /// - /// Playback is paused. - public bool IsPaused { get; set; } - /// /// Gets or sets a value indicating whether there are position ticks. /// diff --git a/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs new file mode 100644 index 0000000000..a6e87a007f --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs @@ -0,0 +1,24 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Interface IPlaybackGroupRequest. + /// + public interface IPlaybackGroupRequest + { + /// + /// Gets the playback request type. + /// + /// The playback request type. + PlaybackRequestType Type(); + + /// + /// Applies the request to a group. + /// + /// The operation completion status. + bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs index d869c05bd1..5ac2aeb247 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs @@ -56,7 +56,7 @@ namespace MediaBrowser.Controller.SyncPlay /// The session. /// The requested action. /// The cancellation token. - void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken); + void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken); /// /// Gets the info about the group for the clients. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 65770021dc..6fa94e2ce4 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller.SyncPlay /// The session. /// The request. /// The cancellation token. - void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken); + void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken); /// /// Maps a session to a group. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs new file mode 100644 index 0000000000..55c9ee938f --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs @@ -0,0 +1,95 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Interface ISyncPlayState. + /// + public interface ISyncPlayState + { + /// + /// Gets the group state. + /// + /// The group state. + GroupState GetGroupState(); + + /// + /// Generic handle. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The play action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a play action requested by a session. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The play action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a pause action requested by a session. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The pause action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a seek action requested by a session. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The seek action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a buffering action requested by a session. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The buffering action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a buffering-done action requested by a session. Context's state can change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The buffering-done action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Updates ping of a session. Context's state should not change. + /// + /// The context of the state. + /// Whether the state has been just set. + /// The buffering-done action. + /// The session. + /// The cancellation token. + /// The operation completion status. + bool HandleRequest(ISyncPlayStateContext context, bool newState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs new file mode 100644 index 0000000000..9bdb1ace6c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Interface ISyncPlayStateContext. + /// + public interface ISyncPlayStateContext + { + /// + /// Gets the context's group. + /// + /// The group. + GroupInfo GetGroup(); + + /// + /// Sets a new state. + /// + /// The new state. + void SetState(ISyncPlayState state); + + /// + /// Sends a GroupUpdate message to the interested sessions. + /// + /// The current session. + /// The filtering type. + /// The message to send. + /// The cancellation token. + /// The task. + Task SendGroupUpdate(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate message, CancellationToken cancellationToken); + + /// + /// Sends a playback command to the interested sessions. + /// + /// The current session. + /// The filtering type. + /// The message to send. + /// The cancellation token. + /// The task. + Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken); + + /// + /// Builds a new playback command with some default values. + /// + /// The command type. + /// The SendCommand. + SendCommand NewSyncPlayCommand(SendCommandType type); + + /// + /// Builds a new group update message. + /// + /// The update type. + /// The data to send. + /// The GroupUpdate. + GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data); + + /// + /// Converts DateTime to UTC string. + /// + /// The date to convert. + /// The UTC string. + string DateToUTCString(DateTime date); + + /// + /// Sanitizes the PositionTicks, considers the current playing item when available. + /// + /// The PositionTicks. + /// The sanitized PositionTicks. + long SanitizePositionTicks(long? positionTicks); + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs new file mode 100644 index 0000000000..21dae8e4e6 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class BufferingGroupRequest. + /// + public class BufferGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets when the request has been made by the client. + /// + /// The date of the request. + public DateTime When { get; set; } + + /// + /// Gets or sets the position ticks. + /// + /// The position ticks. + public long PositionTicks { get; set; } + + /// + /// Gets or sets the playing item id. + /// + /// The playing item id. + public Guid PlayingItemId { get; set; } + + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Buffer; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs new file mode 100644 index 0000000000..21a46add8c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs @@ -0,0 +1,24 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class PauseGroupRequest. + /// + public class PauseGroupRequest : IPlaybackGroupRequest + { + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Pause; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs new file mode 100644 index 0000000000..2f78edfc56 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs @@ -0,0 +1,31 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +// FIXME: not really group related, can be moved up to SyncPlayController maybe? +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class UpdatePingGroupRequest. + /// + public class PingGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the ping time. + /// + /// The ping time. + public long Ping { get; set; } + + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Ping; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs new file mode 100644 index 0000000000..942229a775 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs @@ -0,0 +1,24 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class PlayGroupRequest. + /// + public class PlayGroupRequest : IPlaybackGroupRequest + { + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Play; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs new file mode 100644 index 0000000000..ee88ddddbb --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs @@ -0,0 +1,43 @@ +using System; +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class BufferingDoneGroupRequest. + /// + public class ReadyGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets when the request has been made by the client. + /// + /// The date of the request. + public DateTime When { get; set; } + + /// + /// Gets or sets the position ticks. + /// + /// The position ticks. + public long PositionTicks { get; set; } + + /// + /// Gets or sets the playing item id. + /// + /// The playing item id. + public Guid PlayingItemId { get; set; } + + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Ready; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs new file mode 100644 index 0000000000..bb5e7a343e --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class SeekGroupRequest. + /// + public class SeekGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the position ticks. + /// + /// The position ticks. + public long PositionTicks { get; set; } + + /// + public PlaybackRequestType Type() + { + return PlaybackRequestType.Seek; + } + + /// + public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + return state.HandleRequest(context, false, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs b/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs new file mode 100644 index 0000000000..0b72d16686 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs @@ -0,0 +1,65 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class SyncPlayAbstractState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public abstract class SyncPlayAbstractState : ISyncPlayState + { + /// + public abstract GroupState GetGroupState(); + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + return true; + } + + /// + public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + GroupInfo group = context.GetGroup(); + + // Collected pings are used to account for network latency when unpausing playback + group.UpdatePing(session, request.Ping); + + return true; + } + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupState.cs b/MediaBrowser.Model/SyncPlay/GroupState.cs new file mode 100644 index 0000000000..871634d558 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupState.cs @@ -0,0 +1,25 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Enum GroupState. + /// + public enum GroupState + { + /// + /// The group is in idle state. No media is playing. + /// + Idle, + /// + /// The group is in wating state. Playback is paused. Will start playing when users are ready. + /// + Waiting, + /// + /// The group is in paused state. Playback is paused. Will resume on play command. + /// + Paused, + /// + /// The group is in playing state. Playback is advancing. + /// + Playing + } +} diff --git a/MediaBrowser.Model/SyncPlay/PlaybackRequest.cs b/MediaBrowser.Model/SyncPlay/PlaybackRequest.cs deleted file mode 100644 index 9de23194e3..0000000000 --- a/MediaBrowser.Model/SyncPlay/PlaybackRequest.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; - -namespace MediaBrowser.Model.SyncPlay -{ - /// - /// Class PlaybackRequest. - /// - public class PlaybackRequest - { - /// - /// Gets or sets the request type. - /// - /// The request type. - public PlaybackRequestType Type { get; set; } - - /// - /// Gets or sets when the request has been made by the client. - /// - /// The date of the request. - public DateTime? When { get; set; } - - /// - /// Gets or sets the position ticks. - /// - /// The position ticks. - public long? PositionTicks { get; set; } - - /// - /// Gets or sets the ping time. - /// - /// The ping time. - public long? Ping { get; set; } - } -} diff --git a/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs b/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs new file mode 100644 index 0000000000..29dbb11b38 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/SyncPlayBroadcastType.cs @@ -0,0 +1,28 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Used to filter the sessions of a group. + /// + public enum SyncPlayBroadcastType + { + /// + /// All sessions will receive the message. + /// + AllGroup = 0, + + /// + /// Only the specified session will receive the message. + /// + CurrentSession = 1, + + /// + /// All sessions, except the current one, will receive the message. + /// + AllExceptCurrentSession = 2, + + /// + /// Only sessions that are not buffering will receive the message. + /// + AllReady = 3 + } +} From ed2eabec16aafdf795f5ea4f8834ffdc74bc149f Mon Sep 17 00:00:00 2001 From: gion Date: Sat, 30 May 2020 10:17:54 +0200 Subject: [PATCH 0120/1930] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7b4772730a..218542dbaa 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -78,6 +78,7 @@ - [Nickbert7](https://github.com/Nickbert7) - [nvllsvm](https://github.com/nvllsvm) - [nyanmisaka](https://github.com/nyanmisaka) + - [OancaAndrei](https://github.com/OancaAndrei) - [oddstr13](https://github.com/oddstr13) - [orryverducci](https://github.com/orryverducci) - [petermcneil](https://github.com/petermcneil) From 8819a9d478e6fc11dbfdcff80d9a2dc175953373 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca Date: Thu, 24 Sep 2020 23:04:21 +0200 Subject: [PATCH 0121/1930] Add playlist-sync and group-wait to SyncPlay --- .../Session/SessionManager.cs | 6 +- .../SyncPlay/GroupController.cs | 681 ++++++++++++++++++ .../GroupStates/AbstractGroupState.cs | 218 ++++++ .../SyncPlay/GroupStates/IdleGroupState.cs | 121 ++++ .../SyncPlay/GroupStates/PausedGroupState.cs | 199 +++-- .../SyncPlay/GroupStates/PlayingGroupState.cs | 133 +++- .../SyncPlay/GroupStates/WaitingGroupState.cs | 653 +++++++++++++++++ .../SyncPlay/SyncPlayController.cs | 282 -------- .../SyncPlay/SyncPlayManager.cs | 131 ++-- .../Controllers/SyncPlayController.cs | 300 +++++++- MediaBrowser.Api/SyncPlay/SyncPlayService.cs | 267 ------- .../Session/ISessionManager.cs | 12 +- MediaBrowser.Controller/SyncPlay/GroupInfo.cs | 154 ---- .../SyncPlay/GroupMember.cs | 20 +- .../SyncPlay/IPlaybackGroupRequest.cs | 7 +- .../SyncPlay/ISyncPlayController.cs | 40 +- .../SyncPlay/ISyncPlayManager.cs | 12 +- .../SyncPlay/ISyncPlayState.cs | 165 ++++- .../SyncPlay/ISyncPlayStateContext.cs | 160 +++- .../PlaybackRequest/BufferGroupRequest.cs | 18 +- .../PlaybackRequest/IgnoreWaitGroupRequest.cs | 30 + .../MovePlaylistItemGroupRequest.cs | 36 + .../PlaybackRequest/NextTrackGroupRequest.cs | 30 + .../PlaybackRequest/PauseGroupRequest.cs | 6 +- .../PlaybackRequest/PingGroupRequest.cs | 7 +- .../PlaybackRequest/PlayGroupRequest.cs | 25 +- .../PreviousTrackGroupRequest.cs | 30 + .../PlaybackRequest/QueueGroupRequest.cs | 37 + .../PlaybackRequest/ReadyGroupRequest.cs | 18 +- .../RemoveFromPlaylistGroupRequest.cs | 30 + .../PlaybackRequest/SeekGroupRequest.cs | 6 +- .../SetCurrentItemGroupRequest.cs | 30 + .../SetRepeatModeGroupRequest.cs | 30 + .../SetShuffleModeGroupRequest.cs | 30 + .../PlaybackRequest/StopGroupRequest.cs | 24 + .../PlaybackRequest/UnpauseGroupRequest.cs | 24 + .../SyncPlay/Queue/PlayQueueManager.cs | 596 +++++++++++++++ .../SyncPlay/SyncPlayAbstractState.cs | 65 -- MediaBrowser.Model/SyncPlay/GroupInfoDto.cs | 26 +- .../SyncPlay/GroupRepeatMode.cs | 23 + .../SyncPlay/GroupShuffleMode.cs | 18 + .../SyncPlay/GroupStateUpdate.cs | 22 + .../SyncPlay/GroupUpdateType.cs | 8 +- .../SyncPlay/JoinGroupRequest.cs | 4 +- .../SyncPlay/NewGroupRequest.cs | 16 + .../SyncPlay/PlayQueueUpdate.cs | 52 ++ .../SyncPlay/PlayQueueUpdateReason.cs | 58 ++ .../SyncPlay/PlaybackRequestType.cs | 70 +- MediaBrowser.Model/SyncPlay/QueueItem.cs | 24 + MediaBrowser.Model/SyncPlay/SendCommand.cs | 6 + .../SyncPlay/SendCommandType.cs | 11 +- 51 files changed, 3846 insertions(+), 1125 deletions(-) create mode 100644 Emby.Server.Implementations/SyncPlay/GroupController.cs create mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs create mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs create mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs delete mode 100644 Emby.Server.Implementations/SyncPlay/SyncPlayController.cs delete mode 100644 MediaBrowser.Api/SyncPlay/SyncPlayService.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/GroupInfo.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs create mode 100644 MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs create mode 100644 MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs create mode 100644 MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs create mode 100644 MediaBrowser.Model/SyncPlay/NewGroupRequest.cs create mode 100644 MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs create mode 100644 MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs create mode 100644 MediaBrowser.Model/SyncPlay/QueueItem.cs diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 607b322f2e..9a94d05eb0 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1182,18 +1182,16 @@ namespace Emby.Server.Implementations.Session } /// - public async Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken) + public async Task SendSyncPlayCommand(SessionInfo session, SendCommand command, CancellationToken cancellationToken) { CheckDisposed(); - var session = GetSessionToRemoteControl(sessionId); await SendMessageToSession(session, SessionMessageType.SyncPlayCommand, command, cancellationToken).ConfigureAwait(false); } /// - public async Task SendSyncPlayGroupUpdate(string sessionId, GroupUpdate command, CancellationToken cancellationToken) + public async Task SendSyncPlayGroupUpdate(SessionInfo session, GroupUpdate command, CancellationToken cancellationToken) { CheckDisposed(); - var session = GetSessionToRemoteControl(sessionId); await SendMessageToSession(session, SessionMessageType.SyncPlayGroupUpdate, command, cancellationToken).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs new file mode 100644 index 0000000000..ee2e9eb8f1 --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -0,0 +1,681 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace Emby.Server.Implementations.SyncPlay +{ + /// + /// Class SyncPlayGroupController. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public class SyncPlayGroupController : ISyncPlayGroupController, ISyncPlayStateContext + { + /// + /// Gets the default ping value used for sessions. + /// + public long DefaultPing { get; } = 500; + + /// + /// The logger. + /// + private readonly ILogger _logger; + + /// + /// The user manager. + /// + private readonly IUserManager _userManager; + + /// + /// The session manager. + /// + private readonly ISessionManager _sessionManager; + + /// + /// The library manager. + /// + private readonly ILibraryManager _libraryManager; + + /// + /// The SyncPlay manager. + /// + private readonly ISyncPlayManager _syncPlayManager; + + /// + /// Internal group state. + /// + /// The group's state. + private ISyncPlayState State; + + /// + /// Gets the group identifier. + /// + /// The group identifier. + public Guid GroupId { get; } = Guid.NewGuid(); + + /// + /// Gets the group name. + /// + /// The group name. + public string GroupName { get; private set; } + + /// + /// Gets the group identifier. + /// + /// The group identifier. + public PlayQueueManager PlayQueue { get; } = new PlayQueueManager(); + + /// + /// Gets or sets the runtime ticks of current playing item. + /// + /// The runtime ticks of current playing item. + public long RunTimeTicks { get; private set; } + + /// + /// Gets or sets the position ticks. + /// + /// The position ticks. + public long PositionTicks { get; set; } + + /// + /// Gets or sets the last activity. + /// + /// The last activity. + public DateTime LastActivity { get; set; } + + /// + /// Gets the participants. + /// + /// The participants, or members of the group. + public Dictionary Participants { get; } = + new Dictionary(StringComparer.OrdinalIgnoreCase); + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + /// The user manager. + /// The session manager. + /// The library manager. + /// The SyncPlay manager. + public SyncPlayGroupController( + ILogger logger, + IUserManager userManager, + ISessionManager sessionManager, + ILibraryManager libraryManager, + ISyncPlayManager syncPlayManager) + { + _logger = logger; + _userManager = userManager; + _sessionManager = sessionManager; + _libraryManager = libraryManager; + _syncPlayManager = syncPlayManager; + + State = new IdleGroupState(_logger); + } + + /// + /// Checks if a session is in this group. + /// + /// The session id to check. + /// true if the session is in this group; false otherwise. + private bool ContainsSession(string sessionId) + { + return Participants.ContainsKey(sessionId); + } + + /// + /// Adds the session to the group. + /// + /// The session. + private void AddSession(SessionInfo session) + { + Participants.TryAdd( + session.Id, + new GroupMember + { + Session = session, + Ping = DefaultPing, + IsBuffering = false + }); + } + + /// + /// Removes the session from the group. + /// + /// The session. + private void RemoveSession(SessionInfo session) + { + Participants.Remove(session.Id); + } + + /// + /// Filters sessions of this group. + /// + /// The current session. + /// The filtering type. + /// The array of sessions matching the filter. + private SessionInfo[] FilterSessions(SessionInfo from, SyncPlayBroadcastType type) + { + switch (type) + { + case SyncPlayBroadcastType.CurrentSession: + return new SessionInfo[] { from }; + case SyncPlayBroadcastType.AllGroup: + return Participants.Values.Select( + session => session.Session).ToArray(); + case SyncPlayBroadcastType.AllExceptCurrentSession: + return Participants.Values.Select( + session => session.Session).Where( + session => !session.Id.Equals(from.Id)).ToArray(); + case SyncPlayBroadcastType.AllReady: + return Participants.Values.Where( + session => !session.IsBuffering).Select( + session => session.Session).ToArray(); + default: + return Array.Empty(); + } + } + + private bool HasAccessToItem(User user, BaseItem item) + { + var collections = _libraryManager.GetCollectionFolders(item) + .Select(folder => folder.Id.ToString("N", CultureInfo.InvariantCulture)); + return collections.Intersect(user.GetPreference(PreferenceKind.EnabledFolders)).Any(); + } + + private bool HasAccessToQueue(User user, Guid[] queue) + { + if (queue == null || queue.Length == 0) + { + return true; + } + + var items = queue.ToList() + .Select(item => _libraryManager.GetItemById(item)); + + // Find the highest rating value, which becomes the required minimum for the user + var MinParentalRatingAccessRequired = items + .Select(item => item.InheritedParentalRatingValue) + .Min(); + + // Check ParentalRating access, user must have the minimum required access level + var hasParentalRatingAccess = !user.MaxParentalAgeRating.HasValue + || MinParentalRatingAccessRequired <= user.MaxParentalAgeRating; + + // Check that user has access to all required folders + if (!user.HasPermission(PermissionKind.EnableAllFolders) && hasParentalRatingAccess) + { + // Get list of items that are not accessible + var blockedItems = items.Where(item => !HasAccessToItem(user, item)); + + // We need the user to be able to access all items + return !blockedItems.Any(); + } + + return hasParentalRatingAccess; + } + + private bool AllUsersHaveAccessToQueue(Guid[] queue) + { + if (queue == null || queue.Length == 0) + { + return true; + } + + // Get list of users + var users = Participants.Values + .Select(participant => _userManager.GetUserById(participant.Session.UserId)); + + // Find problematic users + var usersWithNoAccess = users.Where(user => !HasAccessToQueue(user, queue)); + + // All users must be able to access the queue + return !usersWithNoAccess.Any(); + } + + /// + public bool IsGroupEmpty() => Participants.Count == 0; + + /// + public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) + { + GroupName = request.GroupName; + AddSession(session); + _syncPlayManager.AddSessionToGroup(session, this); + + var sessionIsPlayingAnItem = session.FullNowPlayingItem != null; + + RestartCurrentItem(); + + if (sessionIsPlayingAnItem) + { + var playlist = session.NowPlayingQueue.Select(item => item.Id).ToArray(); + PlayQueue.SetPlaylist(playlist); + PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id); + RunTimeTicks = session.FullNowPlayingItem.RunTimeTicks ?? 0; + PositionTicks = session.PlayState.PositionTicks ?? 0; + + // Mantain playstate + var waitingState = new WaitingGroupState(_logger); + waitingState.ResumePlaying = !session.PlayState.IsPaused; + SetState(waitingState); + } + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + + _logger.LogInformation("InitGroup: {0} created group {1}.", session.Id.ToString(), GroupId.ToString()); + } + + /// + public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) + { + AddSession(session); + _syncPlayManager.AddSessionToGroup(session, this); + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); + SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + + State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + + _logger.LogInformation("SessionJoin: {0} joined group {1}.", session.Id.ToString(), GroupId.ToString()); + } + + /// + public void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) + { + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); + SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + + State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + + _logger.LogInformation("SessionRestore: {0} re-joined group {1}.", session.Id.ToString(), GroupId.ToString()); + } + + /// + public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) + { + State.SessionLeaving(this, State.GetGroupState(), session, cancellationToken); + + RemoveSession(session); + _syncPlayManager.RemoveSessionFromGroup(session, this); + + var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, GroupId.ToString()); + SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + + var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); + SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); + + _logger.LogInformation("SessionLeave: {0} left group {1}.", session.Id.ToString(), GroupId.ToString()); + } + + /// + public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) + { + // The server's job is to maintain a consistent state for clients to reference + // and notify clients of state changes. The actual syncing of media playback + // happens client side. Clients are aware of the server's time and use it to sync. + _logger.LogInformation("HandleRequest: {0} requested {1}, group {2} in {3} state.", + session.Id.ToString(), request.GetRequestType(), GroupId.ToString(), State.GetGroupState()); + request.Apply(this, State, session, cancellationToken); + } + + /// + public GroupInfoDto GetInfo() + { + return new GroupInfoDto() + { + GroupId = GroupId.ToString(), + GroupName = GroupName, + State = State.GetGroupState(), + Participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(), + LastUpdatedAt = DateToUTCString(DateTime.UtcNow) + }; + } + + /// + public bool HasAccessToPlayQueue(User user) + { + var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToArray(); + return HasAccessToQueue(user, items); + } + + /// + public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait) + { + if (!ContainsSession(session.Id)) + { + return; + } + + Participants[session.Id].IgnoreGroupWait = ignoreGroupWait; + } + + /// + public void SetState(ISyncPlayState state) + { + _logger.LogInformation("SetState: {0} switching from {1} to {2}.", GroupId.ToString(), State.GetGroupState(), state.GetGroupState()); + this.State = state; + } + + /// + public Task SendGroupUpdate(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate message, CancellationToken cancellationToken) + { + IEnumerable GetTasks() + { + foreach (var session in FilterSessions(from, type)) + { + yield return _sessionManager.SendSyncPlayGroupUpdate(session, message, cancellationToken); + } + } + + return Task.WhenAll(GetTasks()); + } + + /// + public Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken) + { + IEnumerable GetTasks() + { + foreach (var session in FilterSessions(from, type)) + { + yield return _sessionManager.SendSyncPlayCommand(session, message, cancellationToken); + } + } + + return Task.WhenAll(GetTasks()); + } + + /// + public SendCommand NewSyncPlayCommand(SendCommandType type) + { + return new SendCommand() + { + GroupId = GroupId.ToString(), + PlaylistItemId = PlayQueue.GetPlayingItemPlaylistId(), + PositionTicks = PositionTicks, + Command = type, + When = DateToUTCString(LastActivity), + EmittedAt = DateToUTCString(DateTime.UtcNow) + }; + } + + /// + public GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data) + { + return new GroupUpdate() + { + GroupId = GroupId.ToString(), + Type = type, + Data = data + }; + } + + /// + public string DateToUTCString(DateTime dateTime) + { + return dateTime.ToUniversalTime().ToString("o"); + } + + /// + public long SanitizePositionTicks(long? positionTicks) + { + var ticks = positionTicks ?? 0; + ticks = ticks >= 0 ? ticks : 0; + ticks = ticks > RunTimeTicks ? RunTimeTicks : ticks; + return ticks; + } + + /// + public void UpdatePing(SessionInfo session, long ping) + { + if (Participants.TryGetValue(session.Id, out GroupMember value)) + { + value.Ping = ping; + } + } + + /// + public long GetHighestPing() + { + long max = long.MinValue; + foreach (var session in Participants.Values) + { + max = Math.Max(max, session.Ping); + } + + return max; + } + + /// + public void SetBuffering(SessionInfo session, bool isBuffering) + { + if (Participants.TryGetValue(session.Id, out GroupMember value)) + { + value.IsBuffering = isBuffering; + } + } + + /// + public void SetAllBuffering(bool isBuffering) + { + foreach (var session in Participants.Values) + { + session.IsBuffering = isBuffering; + } + } + + /// + public bool IsBuffering() + { + foreach (var session in Participants.Values) + { + if (session.IsBuffering && !session.IgnoreGroupWait) + { + return true; + } + } + + return false; + } + + /// + public bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks) + { + // Ignore on empty queue or invalid item position + if (playQueue.Length < 1 || playingItemPosition >= playQueue.Length || playingItemPosition < 0) + { + return false; + } + + // Check is participants can access the new playing queue + if (!AllUsersHaveAccessToQueue(playQueue)) + { + return false; + } + + PlayQueue.SetPlaylist(playQueue); + PlayQueue.SetPlayingItemByIndex(playingItemPosition); + var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId()); + RunTimeTicks = item.RunTimeTicks ?? 0; + PositionTicks = startPositionTicks; + LastActivity = DateTime.UtcNow; + + return true; + } + + /// + public bool SetPlayingItem(string playlistItemId) + { + var itemFound = PlayQueue.SetPlayingItemByPlaylistId(playlistItemId); + + if (itemFound) + { + var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId()); + RunTimeTicks = item.RunTimeTicks ?? 0; + } + else + { + RunTimeTicks = 0; + } + + RestartCurrentItem(); + + return itemFound; + } + + /// + public bool RemoveFromPlayQueue(string[] playlistItemIds) + { + var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds); + if (playingItemRemoved) + { + var itemId = PlayQueue.GetPlayingItemId(); + if (!itemId.Equals(Guid.Empty)) + { + var item = _libraryManager.GetItemById(itemId); + RunTimeTicks = item.RunTimeTicks ?? 0; + } + else + { + RunTimeTicks = 0; + } + + RestartCurrentItem(); + } + + return playingItemRemoved; + } + + /// + public bool MoveItemInPlayQueue(string playlistItemId, int newIndex) + { + return PlayQueue.MovePlaylistItem(playlistItemId, newIndex); + } + + /// + public bool AddToPlayQueue(Guid[] newItems, string mode) + { + // Ignore on empty list + if (newItems.Length < 1) + { + return false; + } + + // Check is participants can access the new playing queue + if (!AllUsersHaveAccessToQueue(newItems)) + { + return false; + } + + if (mode.Equals("next")) + { + PlayQueue.QueueNext(newItems); + } + else + { + PlayQueue.Queue(newItems); + } + + return true; + } + + /// + public void RestartCurrentItem() + { + PositionTicks = 0; + LastActivity = DateTime.UtcNow; + } + + /// + public bool NextItemInQueue() + { + var update = PlayQueue.Next(); + if (update) + { + var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId()); + RunTimeTicks = item.RunTimeTicks ?? 0; + RestartCurrentItem(); + return true; + } + else + { + return false; + } + } + + /// + public bool PreviousItemInQueue() + { + var update = PlayQueue.Previous(); + if (update) + { + var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId()); + RunTimeTicks = item.RunTimeTicks ?? 0; + RestartCurrentItem(); + return true; + } + else + { + return false; + } + } + + /// + public void SetRepeatMode(string mode) { + PlayQueue.SetRepeatMode(mode); + } + + /// + public void SetShuffleMode(string mode) { + PlayQueue.SetShuffleMode(mode); + } + + /// + public PlayQueueUpdate GetPlayQueueUpdate(PlayQueueUpdateReason reason) + { + var startPositionTicks = PositionTicks; + + if (State.GetGroupState().Equals(GroupState.Playing)) + { + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - LastActivity; + // Event may happen during the delay added to account for latency + startPositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + } + + return new PlayQueueUpdate() + { + Reason = reason, + LastUpdate = DateToUTCString(PlayQueue.LastChange), + Playlist = PlayQueue.GetPlaylist(), + PlayingItemIndex = PlayQueue.PlayingItemIndex, + StartPositionTicks = startPositionTicks, + ShuffleMode = PlayQueue.ShuffleMode, + RepeatMode = PlayQueue.RepeatMode + }; + } + + } +} diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs new file mode 100644 index 0000000000..1f0cb42870 --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs @@ -0,0 +1,218 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class AbstractGroupState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public abstract class AbstractGroupState : ISyncPlayState + { + /// + /// The logger. + /// + protected readonly ILogger _logger; + + /// + /// Default constructor. + /// + public AbstractGroupState(ILogger logger) + { + _logger = logger; + } + + /// + /// Sends a group state update to all group. + /// + /// The context of the state. + /// The reason of the state change. + /// The session. + /// The cancellation token. + protected void SendGroupStateUpdate(ISyncPlayStateContext context, IPlaybackGroupRequest reason, SessionInfo session, CancellationToken cancellationToken) + { + // Notify relevant state change event + var stateUpdate = new GroupStateUpdate() + { + State = GetGroupState(), + Reason = reason.GetRequestType() + }; + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + /// + public abstract GroupState GetGroupState(); + + /// + public abstract void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + + /// + public abstract void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + var playingItemRemoved = context.RemoveFromPlayQueue(request.PlaylistItemIds); + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RemoveItems); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + if (playingItemRemoved) + { + var PlayingItemIndex = context.PlayQueue.PlayingItemIndex; + if (context.PlayQueue.PlayingItemIndex == -1) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, play queue is empty.", request.GetRequestType(), context.GroupId.ToString()); + + ISyncPlayState idleState = new IdleGroupState(_logger); + context.SetState(idleState); + var stopRequest = new StopGroupRequest(); + idleState.HandleRequest(context, GetGroupState(), stopRequest, session, cancellationToken); + } + } + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + var result = context.MoveItemInPlayQueue(request.PlaylistItemId, request.NewIndex); + + if (!result) + { + _logger.LogError("HandleRequest: {0} in group {1}, unable to move item in play queue.", request.GetRequestType(), context.GroupId.ToString()); + return; + } + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.MoveItem); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + var result = context.AddToPlayQueue(request.ItemIds, request.Mode); + + if (!result) + { + _logger.LogError("HandleRequest: {0} in group {1}, unable to add items to play queue.", request.GetRequestType(), context.GroupId.ToString()); + return; + } + + var reason = request.Mode.Equals("next") ? PlayQueueUpdateReason.QueueNext : PlayQueueUpdateReason.Queue; + var playQueueUpdate = context.GetPlayQueueUpdate(reason); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + UnhandledRequest(request); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + context.SetRepeatMode(request.Mode); + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RepeatMode); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + context.SetShuffleMode(request.Mode); + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.ShuffleMode); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Collected pings are used to account for network latency when unpausing playback + context.UpdatePing(session, request.Ping); + } + + /// + public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + context.SetIgnoreGroupWait(session, request.IgnoreWait); + } + + private void UnhandledRequest(IPlaybackGroupRequest request) + { + _logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.GetRequestType(), this.GetGroupState()); + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs new file mode 100644 index 0000000000..d6b981c584 --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs @@ -0,0 +1,121 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class IdleGroupState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public class IdleGroupState : AbstractGroupState + { + /// + /// Default constructor. + /// + public IdleGroupState(ILogger logger) : base(logger) + { + // Do nothing + } + + /// + public override GroupState GetGroupState() + { + return GroupState.Idle; + } + + /// + public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, GetGroupState(), session, cancellationToken); + } + + /// + public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + // Do nothing + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + private void SendStopCommand(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + var command = context.NewSyncPlayCommand(SendCommandType.Stop); + if (!prevState.Equals(GetGroupState())) + { + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + } + else + { + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs index d3bf24f747..39c0511d9f 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs @@ -1,11 +1,8 @@ -using System.Linq; using System; using System.Threading; -using System.Collections.Generic; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Session; using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.SyncPlay { @@ -15,8 +12,16 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Class is not thread-safe, external locking is required when accessing methods. /// - public class PausedGroupState : SyncPlayAbstractState + public class PausedGroupState : AbstractGroupState { + /// + /// Default constructor. + /// + public PausedGroupState(ILogger logger) : base(logger) + { + // Do nothing + } + /// public override GroupState GetGroupState() { @@ -24,31 +29,56 @@ namespace MediaBrowser.Controller.SyncPlay } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Change state - var playingState = new PlayingGroupState(); - context.SetState(playingState); - return playingState.HandleRequest(context, true, request, session, cancellationToken); + // Wait for session to be ready + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - if (newState) - { - GroupInfo group = context.GetGroup(); + // Do nothing + } + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var playingState = new PlayingGroupState(_logger); + context.SetState(playingState); + playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + if (!prevState.Equals(GetGroupState())) + { // Pause group and compute the media playback position var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - group.LastActivity; - group.LastActivity = currentTime; + var elapsedTime = currentTime - context.LastActivity; + context.LastActivity = currentTime; // Seek only if playback actually started // Pause request may be issued during the delay added to account for latency - group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); } else { @@ -56,116 +86,71 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } - - return true; } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - GroupInfo group = context.GetGroup(); - - // Sanitize PositionTicks - var ticks = context.SanitizePositionTicks(request.PositionTicks); - - // Seek - group.PositionTicks = ticks; - group.LastActivity = DateTime.UtcNow; - - var command = context.NewSyncPlayCommand(SendCommandType.Seek); - context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - - return true; + // Change state + var idleState = new IdleGroupState(_logger); + context.SetState(idleState); + idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - GroupInfo group = context.GetGroup(); + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } - if (newState) + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + if (prevState.Equals(GetGroupState())) { - // Pause group and compute the media playback position - var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - group.LastActivity; - group.LastActivity = currentTime; - group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; - - group.SetBuffering(session, true); - - // Send pause command to all non-buffering sessions - var command = context.NewSyncPlayCommand(SendCommandType.Pause); - context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); - - var updateOthers = context.NewSyncPlayGroupUpdate(GroupUpdateType.GroupWait, session.UserName); - context.SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - } - else - { - // TODO: no idea? - // group.SetBuffering(session, true); - // Client got lost, sending current state var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } + else if (prevState.Equals(GroupState.Waiting)) + { + // Sending current state to all clients + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - return true; + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - GroupInfo group = context.GetGroup(); + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } - group.SetBuffering(session, false); - - var requestTicks = context.SanitizePositionTicks(request.PositionTicks); - - var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - request.When; - var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime; - var delay = group.PositionTicks - clientPosition.Ticks; - - if (group.IsBuffering()) - { - // Others are still buffering, tell this client to pause when ready - var command = context.NewSyncPlayCommand(SendCommandType.Pause); - var pauseAtTime = currentTime.AddMilliseconds(delay); - command.When = context.DateToUTCString(pauseAtTime); - context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - } - else - { - // Let other clients resume as soon as the buffering client catches up - if (delay > group.GetHighestPing() * 2) - { - // Client that was buffering is recovering, notifying others to resume - group.LastActivity = currentTime.AddMilliseconds( - delay - ); - var command = context.NewSyncPlayCommand(SendCommandType.Play); - context.SendCommand(session, SyncPlayBroadcastType.AllExceptCurrentSession, command, cancellationToken); - } - else - { - // Client, that was buffering, resumed playback but did not update others in time - delay = Math.Max(group.GetHighestPing() * 2, group.DefaultPing); - - group.LastActivity = currentTime.AddMilliseconds( - delay - ); - - var command = context.NewSyncPlayCommand(SendCommandType.Play); - context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - } - - // Change state - var playingState = new PlayingGroupState(); - context.SetState(playingState); - } - - return true; + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs index 42c7779c19..e2909ff91c 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs @@ -1,11 +1,8 @@ -using System.Linq; using System; using System.Threading; -using System.Collections.Generic; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Session; using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; namespace MediaBrowser.Controller.SyncPlay { @@ -15,8 +12,21 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Class is not thread-safe, external locking is required when accessing methods. /// - public class PlayingGroupState : SyncPlayAbstractState + public class PlayingGroupState : AbstractGroupState { + /// + /// Ignore requests for buffering. + /// + public bool IgnoreBuffering { get; set; } + + /// + /// Default constructor. + /// + public PlayingGroupState(ILogger logger) : base(logger) + { + // Do nothing + } + /// public override GroupState GetGroupState() { @@ -24,71 +34,132 @@ namespace MediaBrowser.Controller.SyncPlay } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - GroupInfo group = context.GetGroup(); + // Wait for session to be ready + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); + } - if (newState) + /// + public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + // Do nothing + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + if (!prevState.Equals(GetGroupState())) { // Pick a suitable time that accounts for latency - var delay = Math.Max(group.GetHighestPing() * 2, group.DefaultPing); + var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing); // Unpause group and set starting point in future // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position) // The added delay does not guarantee, of course, that the command will be received in time // Playback synchronization will mainly happen client side - group.LastActivity = DateTime.UtcNow.AddMilliseconds( - delay + context.LastActivity = DateTime.UtcNow.AddMilliseconds( + delayMillis ); - var command = context.NewSyncPlayCommand(SendCommandType.Play); + var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); } else { // Client got lost, sending current state - var command = context.NewSyncPlayCommand(SendCommandType.Play); + var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } - - return true; } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state - var pausedState = new PausedGroupState(); + var pausedState = new PausedGroupState(_logger); context.SetState(pausedState); - return pausedState.HandleRequest(context, true, request, session, cancellationToken); + pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state - var pausedState = new PausedGroupState(); - context.SetState(pausedState); - return pausedState.HandleRequest(context, true, request, session, cancellationToken); + var idleState = new IdleGroupState(_logger); + context.SetState(idleState); + idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state - var pausedState = new PausedGroupState(); - context.SetState(pausedState); - return pausedState.HandleRequest(context, true, request, session, cancellationToken); + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } /// - public override bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Group was not waiting, make sure client has latest state - var command = context.NewSyncPlayCommand(SendCommandType.Play); - context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + if (IgnoreBuffering) + { + return; + } - return true; + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + if (prevState.Equals(GetGroupState())) + { + // Group was not waiting, make sure client has latest state + var command = context.NewSyncPlayCommand(SendCommandType.Unpause); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + else if (prevState.Equals(GroupState.Waiting)) + { + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state + var waitingState = new WaitingGroupState(_logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs new file mode 100644 index 0000000000..9d839b268b --- /dev/null +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs @@ -0,0 +1,653 @@ +using System; +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class WaitingGroupState. + /// + /// + /// Class is not thread-safe, external locking is required when accessing methods. + /// + public class WaitingGroupState : AbstractGroupState + { + /// + /// Tells the state to switch to after buffering is done. + /// + public bool ResumePlaying { get; set; } = false; + + /// + /// Whether the initial state has been set. + /// + private bool InitialStateSet { get; set; } = false; + + /// + /// The group state before the first ever event. + /// + private GroupState InitialState { get; set; } + + /// + /// Default constructor. + /// + public WaitingGroupState(ILogger logger) : base(logger) + { + // Do nothing + } + + /// + public override GroupState GetGroupState() + { + return GroupState.Waiting; + } + + /// + public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + if (prevState.Equals(GroupState.Playing)) { + ResumePlaying = true; + // Pause group and compute the media playback position + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - context.LastActivity; + context.LastActivity = currentTime; + // Seek only if playback actually started + // Event may happen during the delay added to account for latency + context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + } + + // Prepare new session + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken); + + context.SetBuffering(session, true); + + // Send pause command to all non-buffering sessions + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); + } + + /// + public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + context.SetBuffering(session, false); + + if (!context.IsBuffering()) + { + if (ResumePlaying) + { + // Client, that was buffering, left the group + var playingState = new PlayingGroupState(_logger); + context.SetState(playingState); + var unpauseRequest = new UnpauseGroupRequest(); + playingState.HandleRequest(context, GetGroupState(), unpauseRequest, session, cancellationToken); + + _logger.LogDebug("SessionLeaving: {0} left the group {1}, notifying others to resume.", session.Id.ToString(), context.GroupId.ToString()); + } + else + { + // Group is ready, returning to previous state + var pausedState = new PausedGroupState(_logger); + context.SetState(pausedState); + + _logger.LogDebug("SessionLeaving: {0} left the group {1}, returning to previous state.", session.Id.ToString(), context.GroupId.ToString()); + } + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + ResumePlaying = true; + + var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks); + if (!setQueueStatus) + { + _logger.LogError("HandleRequest: {0} in group {1}, unable to set playing queue.", request.GetRequestType(), context.GroupId.ToString()); + + // Ignore request and return to previous state + ISyncPlayState newState; + switch (prevState) + { + case GroupState.Playing: + newState = new PlayingGroupState(_logger); + break; + case GroupState.Paused: + newState = new PausedGroupState(_logger); + break; + default: + newState = new IdleGroupState(_logger); + break; + } + + context.SetState(newState); + return; + } + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + ResumePlaying = true; + + var result = context.SetPlayingItem(request.PlaylistItemId); + if (result) + { + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + } + else + { + // Return to old state + ISyncPlayState newState; + switch (prevState) + { + case GroupState.Playing: + newState = new PlayingGroupState(_logger); + break; + case GroupState.Paused: + newState = new PausedGroupState(_logger); + break; + default: + newState = new IdleGroupState(_logger); + break; + } + + context.SetState(newState); + + _logger.LogDebug("HandleRequest: {0} in group {1}, unable to change current playing item.", request.GetRequestType(), context.GroupId.ToString()); + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + if (prevState.Equals(GroupState.Idle)) + { + ResumePlaying = true; + context.RestartCurrentItem(); + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + + _logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.GetRequestType(), context.GroupId.ToString()); + } + else + { + if (ResumePlaying) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, ignoring sessions that are not ready and forcing the playback to start.", request.GetRequestType(), context.GroupId.ToString()); + + // An Unpause request is forcing the playback to start, ignoring sessions that are not ready + context.SetAllBuffering(false); + + // Change state + var playingState = new PlayingGroupState(_logger); + playingState.IgnoreBuffering = true; + context.SetState(playingState); + playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + else + { + // Group would have gone to paused state, now will go to playing state when ready + ResumePlaying = true; + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + // Wait for sessions to be ready, then switch to paused state + ResumePlaying = false; + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + // Change state + var idleState = new IdleGroupState(_logger); + context.SetState(idleState); + idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + if (prevState.Equals(GroupState.Playing)) + { + ResumePlaying = true; + } + else if(prevState.Equals(GroupState.Paused)) + { + ResumePlaying = false; + } + + // Sanitize PositionTicks + var ticks = context.SanitizePositionTicks(request.PositionTicks); + + // Seek + context.PositionTicks = ticks; + context.LastActivity = DateTime.UtcNow; + + var command = context.NewSyncPlayCommand(SendCommandType.Seek); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + // Make sure the client is playing the correct item + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); + var updateSession = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); + context.SetBuffering(session, true); + + return; + } + + if (prevState.Equals(GroupState.Playing)) + { + // Resume playback when all ready + ResumePlaying = true; + + context.SetBuffering(session, true); + + // Pause group and compute the media playback position + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - context.LastActivity; + context.LastActivity = currentTime; + context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + + // Send pause command to all non-buffering sessions + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); + } + else if (prevState.Equals(GroupState.Paused)) + { + // Don't resume playback when all ready + ResumePlaying = false; + + context.SetBuffering(session, true); + + // Send pause command to buffering session + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + else if (prevState.Equals(GroupState.Waiting)) + { + // Another session is now buffering + context.SetBuffering(session, true); + + if (!ResumePlaying) + { + // Force update for this session that should be paused + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + } + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + // Make sure the client is playing the correct item + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken); + context.SetBuffering(session, true); + + return; + } + + var requestTicks = context.SanitizePositionTicks(request.PositionTicks); + var currentTime = DateTime.UtcNow; + var elapsedTime = currentTime - request.When; + if (!request.IsPlaying) + { + elapsedTime = TimeSpan.Zero; + } + + var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime; + var delayTicks = context.PositionTicks - clientPosition.Ticks; + + if (delayTicks > TimeSpan.FromSeconds(5).Ticks) + { + // The client is really behind, other participants will have to wait a lot of time... + _logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + + if (ResumePlaying) + { + // Handle case where session reported as ready but in reality + // it has no clue of the real position nor the playback state + if (!request.IsPlaying && Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) { + // Session not ready at all + context.SetBuffering(session, true); + + // Correcting session's position + var command = context.NewSyncPlayCommand(SendCommandType.Seek); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + return; + } + + // Session is ready + context.SetBuffering(session, false); + + if (context.IsBuffering()) + { + // Others are still buffering, tell this client to pause when ready + var command = context.NewSyncPlayCommand(SendCommandType.Pause); + var pauseAtTime = currentTime.AddTicks(delayTicks); + command.When = context.DateToUTCString(pauseAtTime); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + + _logger.LogDebug("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + else + { + // If all ready, then start playback + // Let other clients resume as soon as the buffering client catches up + if (delayTicks > context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond) + { + // Client that was buffering is recovering, notifying others to resume + context.LastActivity = currentTime.AddTicks(delayTicks); + var command = context.NewSyncPlayCommand(SendCommandType.Unpause); + var filter = SyncPlayBroadcastType.AllExceptCurrentSession; + if (!request.IsPlaying) + { + filter = SyncPlayBroadcastType.AllGroup; + } + + context.SendCommand(session, filter, command, cancellationToken); + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + else + { + // Client, that was buffering, resumed playback but did not update others in time + delayTicks = context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond; + delayTicks = delayTicks < context.DefaultPing ? context.DefaultPing : delayTicks; + + context.LastActivity = currentTime.AddTicks(delayTicks); + + var command = context.NewSyncPlayCommand(SendCommandType.Unpause); + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + + // Change state + var playingState = new PlayingGroupState(_logger); + context.SetState(playingState); + playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + } + else + { + // Check that session is really ready, tollerate half second difference to account for player imperfections + if (Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) + { + // Session still not ready + context.SetBuffering(session, true); + + // Session is seeking to wrong position, correcting + var command = context.NewSyncPlayCommand(SendCommandType.Seek); + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + + // Notify relevant state change event + SendGroupStateUpdate(context, request, session, cancellationToken); + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + return; + } else { + // Session is ready + context.SetBuffering(session, false); + } + + if (!context.IsBuffering()) + { + // Group is ready, returning to previous state + var pausedState = new PausedGroupState(_logger); + context.SetState(pausedState); + + if (InitialState.Equals(GroupState.Playing)) + { + // Group went from playing to waiting state and a pause request occured while waiting + var pauserequest = new PauseGroupRequest(); + pausedState.HandleRequest(context, GetGroupState(), pauserequest, session, cancellationToken); + } + else if (InitialState.Equals(GroupState.Paused)) + { + pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + } + + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + } + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + ResumePlaying = true; + + // Make sure the client knows the playing item, to avoid duplicate requests + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); + return; + } + + var newItem = context.NextItemInQueue(); + if (newItem) + { + // Send playing-queue update + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextTrack); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + } + else + { + // Return to old state + ISyncPlayState newState; + switch (prevState) + { + case GroupState.Playing: + newState = new PlayingGroupState(_logger); + break; + case GroupState.Paused: + newState = new PausedGroupState(_logger); + break; + default: + newState = new IdleGroupState(_logger); + break; + } + + context.SetState(newState); + + _logger.LogDebug("HandleRequest: {0} in group {1}, no next track available.", request.GetRequestType(), context.GroupId.ToString()); + } + } + + /// + public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Save state if first event + if (!InitialStateSet) + { + InitialState = prevState; + InitialStateSet = true; + } + + ResumePlaying = true; + + // Make sure the client knows the playing item, to avoid duplicate requests + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + { + _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); + return; + } + + var newItem = context.PreviousItemInQueue(); + if (newItem) + { + // Send playing-queue update + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousTrack); + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + + // Reset status of sessions and await for all Ready events before sending Play command + context.SetAllBuffering(true); + } + else + { + // Return to old state + ISyncPlayState newState; + switch (prevState) + { + case GroupState.Playing: + newState = new PlayingGroupState(_logger); + break; + case GroupState.Paused: + newState = new PausedGroupState(_logger); + break; + default: + newState = new IdleGroupState(_logger); + break; + } + + context.SetState(newState); + + _logger.LogDebug("HandleRequest: {0} in group {1}, no previous track available.", request.GetRequestType(), context.GroupId.ToString()); + } + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs deleted file mode 100644 index 225be7430d..0000000000 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayController.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Controller.Session; -using MediaBrowser.Controller.SyncPlay; -using MediaBrowser.Model.Session; -using MediaBrowser.Model.SyncPlay; -using Microsoft.Extensions.Logging; - -namespace Emby.Server.Implementations.SyncPlay -{ - /// - /// Class SyncPlayController. - /// - /// - /// Class is not thread-safe, external locking is required when accessing methods. - /// - public class SyncPlayController : ISyncPlayController, ISyncPlayStateContext - { - /// - /// The session manager. - /// - private readonly ISessionManager _sessionManager; - - /// - /// The SyncPlay manager. - /// - private readonly ISyncPlayManager _syncPlayManager; - - /// - /// The logger. - /// - private readonly ILogger _logger; - - /// - /// The group to manage. - /// - private readonly GroupInfo _group = new GroupInfo(); - - /// - /// Internal group state. - /// - /// The group's state. - private ISyncPlayState State = new PausedGroupState(); - - /// - public GroupInfo GetGroup() - { - return _group; - } - - /// - public void SetState(ISyncPlayState state) - { - _logger.LogInformation("SetState: {0} -> {1}.", State.GetGroupState(), state.GetGroupState()); - this.State = state; - } - - /// - public Guid GetGroupId() => _group.GroupId; - - /// - public Guid GetPlayingItemId() => _group.PlayingItem.Id; - - /// - public bool IsGroupEmpty() => _group.IsEmpty(); - - /// - /// Initializes a new instance of the class. - /// - /// The session manager. - /// The SyncPlay manager. - public SyncPlayController( - ISessionManager sessionManager, - ISyncPlayManager syncPlayManager, - ILogger logger) - { - _sessionManager = sessionManager; - _syncPlayManager = syncPlayManager; - _logger = logger; - } - - /// - /// Filters sessions of this group. - /// - /// The current session. - /// The filtering type. - /// The array of sessions matching the filter. - private SessionInfo[] FilterSessions(SessionInfo from, SyncPlayBroadcastType type) - { - switch (type) - { - case SyncPlayBroadcastType.CurrentSession: - return new SessionInfo[] { from }; - case SyncPlayBroadcastType.AllGroup: - return _group.Participants.Values.Select( - session => session.Session).ToArray(); - case SyncPlayBroadcastType.AllExceptCurrentSession: - return _group.Participants.Values.Select( - session => session.Session).Where( - session => !session.Id.Equals(from.Id)).ToArray(); - case SyncPlayBroadcastType.AllReady: - return _group.Participants.Values.Where( - session => !session.IsBuffering).Select( - session => session.Session).ToArray(); - default: - return Array.Empty(); - } - } - - /// - public Task SendGroupUpdate(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate message, CancellationToken cancellationToken) - { - IEnumerable GetTasks() - { - foreach (var session in FilterSessions(from, type)) - { - yield return _sessionManager.SendSyncPlayGroupUpdate(session.Id, message, cancellationToken); - } - } - - return Task.WhenAll(GetTasks()); - } - - /// - public Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken) - { - IEnumerable GetTasks() - { - foreach (var session in FilterSessions(from, type)) - { - yield return _sessionManager.SendSyncPlayCommand(session.Id, message, cancellationToken); - } - } - - return Task.WhenAll(GetTasks()); - } - - /// - public SendCommand NewSyncPlayCommand(SendCommandType type) - { - return new SendCommand() - { - GroupId = _group.GroupId.ToString(), - Command = type, - PositionTicks = _group.PositionTicks, - When = DateToUTCString(_group.LastActivity), - EmittedAt = DateToUTCString(DateTime.UtcNow) - }; - } - - /// - public GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data) - { - return new GroupUpdate() - { - GroupId = _group.GroupId.ToString(), - Type = type, - Data = data - }; - } - - /// - public string DateToUTCString(DateTime _date) - { - return _date.ToUniversalTime().ToString("o"); - } - - /// - public long SanitizePositionTicks(long? positionTicks) - { - var ticks = positionTicks ?? 0; - ticks = ticks >= 0 ? ticks : 0; - if (_group.PlayingItem != null) - { - var runTimeTicks = _group.PlayingItem.RunTimeTicks ?? 0; - ticks = ticks > runTimeTicks ? runTimeTicks : ticks; - } - - return ticks; - } - - /// - public void CreateGroup(SessionInfo session, CancellationToken cancellationToken) - { - _group.AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); - - State = new PausedGroupState(); - - _group.PlayingItem = session.FullNowPlayingItem; - // TODO: looks like new groups should mantain playstate (and not force to pause) - // _group.IsPaused = session.PlayState.IsPaused; - _group.PositionTicks = session.PlayState.PositionTicks ?? 0; - _group.LastActivity = DateTime.UtcNow; - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); - SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); - // TODO: looks like new groups should mantain playstate (and not force to pause) - var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, SyncPlayBroadcastType.CurrentSession, pauseCommand, cancellationToken); - } - - /// - public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) - { - if (session.NowPlayingItem?.Id == _group.PlayingItem.Id) - { - _group.AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow)); - SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); - SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - - // Syncing will happen client-side - if (State.GetGroupState().Equals(GroupState.Playing)) - { - var playCommand = NewSyncPlayCommand(SendCommandType.Play); - SendCommand(session, SyncPlayBroadcastType.CurrentSession, playCommand, cancellationToken); - } - else - { - var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause); - SendCommand(session, SyncPlayBroadcastType.CurrentSession, pauseCommand, cancellationToken); - } - } - else - { - var playRequest = new PlayRequest - { - ItemIds = new Guid[] { _group.PlayingItem.Id }, - StartPositionTicks = _group.PositionTicks - }; - var update = NewSyncPlayGroupUpdate(GroupUpdateType.PrepareSession, playRequest); - SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken); - } - } - - /// - public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) - { - _group.RemoveSession(session); - _syncPlayManager.RemoveSessionFromGroup(session, this); - - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks); - SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); - SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - } - - /// - public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) - { - // The server's job is to maintain a consistent state for clients to reference - // and notify clients of state changes. The actual syncing of media playback - // happens client side. Clients are aware of the server's time and use it to sync. - _logger.LogInformation("HandleRequest: {0}:{1}.", request.GetType(), State.GetGroupState()); - _ = request.Apply(this, State, session, cancellationToken); - // TODO: do something with returned value - } - - /// - public GroupInfoDto GetInfo() - { - return new GroupInfoDto() - { - GroupId = GetGroupId().ToString(), - PlayingItemName = _group.PlayingItem.Name, - PlayingItemId = _group.PlayingItem.Id.ToString(), - PositionTicks = _group.PositionTicks, - Participants = _group.Participants.Values.Select(session => session.Session.UserName).Distinct().ToList() - }; - } - } -} diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index b85f3c1496..a8e30a9eca 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; -using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; @@ -41,14 +39,14 @@ namespace Emby.Server.Implementations.SyncPlay /// /// The map between sessions and groups. /// - private readonly Dictionary _sessionToGroupMap = - new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _sessionToGroupMap = + new Dictionary(StringComparer.OrdinalIgnoreCase); /// /// The groups. /// - private readonly Dictionary _groups = - new Dictionary(); + private readonly Dictionary _groups = + new Dictionary(); /// /// Lock used for accesing any group. @@ -75,7 +73,9 @@ namespace Emby.Server.Implementations.SyncPlay _sessionManager = sessionManager; _libraryManager = libraryManager; + _sessionManager.SessionStarted += OnSessionManagerSessionStarted; _sessionManager.SessionEnded += OnSessionManagerSessionEnded; + _sessionManager.PlaybackStart += OnSessionManagerPlaybackStart; _sessionManager.PlaybackStopped += OnSessionManagerPlaybackStopped; } @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.SyncPlay /// Gets all groups. /// /// All groups. - public IEnumerable Groups => _groups.Values; + public IEnumerable Groups => _groups.Values; /// public void Dispose() @@ -103,12 +103,30 @@ namespace Emby.Server.Implementations.SyncPlay return; } + _sessionManager.SessionStarted -= OnSessionManagerSessionStarted; _sessionManager.SessionEnded -= OnSessionManagerSessionEnded; + _sessionManager.PlaybackStart -= OnSessionManagerPlaybackStart; _sessionManager.PlaybackStopped -= OnSessionManagerPlaybackStopped; _disposed = true; } + private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) + { + var session = e.SessionInfo; + if (!IsSessionInGroup(session)) + { + return; + } + + var groupId = GetSessionGroup(session) ?? Guid.Empty; + var request = new JoinGroupRequest() + { + GroupId = groupId + }; + JoinGroup(session, groupId, request, CancellationToken.None); + } + private void OnSessionManagerSessionEnded(object sender, SessionEventArgs e) { var session = e.SessionInfo; @@ -117,7 +135,18 @@ namespace Emby.Server.Implementations.SyncPlay return; } - LeaveGroup(session, CancellationToken.None); + // TODO: probably remove this event, not used at the moment + } + + private void OnSessionManagerPlaybackStart(object sender, PlaybackProgressEventArgs e) + { + var session = e.Session; + if (!IsSessionInGroup(session)) + { + return; + } + + // TODO: probably remove this event, not used at the moment } private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e) @@ -128,7 +157,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } - LeaveGroup(session, CancellationToken.None); + // TODO: probably remove this event, not used at the moment } private bool IsSessionInGroup(SessionInfo session) @@ -136,33 +165,14 @@ namespace Emby.Server.Implementations.SyncPlay return _sessionToGroupMap.ContainsKey(session.Id); } - private bool HasAccessToItem(User user, Guid itemId) - { - var item = _libraryManager.GetItemById(itemId); - - // Check ParentalRating access - var hasParentalRatingAccess = !user.MaxParentalAgeRating.HasValue - || item.InheritedParentalRatingValue <= user.MaxParentalAgeRating; - - if (!user.HasPermission(PermissionKind.EnableAllFolders) && hasParentalRatingAccess) - { - var collections = _libraryManager.GetCollectionFolders(item).Select( - folder => folder.Id.ToString("N", CultureInfo.InvariantCulture)); - - return collections.Intersect(user.GetPreference(PreferenceKind.EnabledFolders)).Any(); - } - - return hasParentalRatingAccess; - } - private Guid? GetSessionGroup(SessionInfo session) { _sessionToGroupMap.TryGetValue(session.Id, out var group); - return group?.GetGroupId(); + return group?.GroupId; } /// - public void NewGroup(SessionInfo session, CancellationToken cancellationToken) + public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { var user = _userManager.GetUserById(session.UserId); @@ -174,8 +184,7 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.CreateGroupDenied }; - - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -186,10 +195,10 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } - var group = new SyncPlayController(_sessionManager, this, _logger); - _groups[group.GetGroupId()] = group; + var group = new SyncPlayGroupController(_logger, _userManager, _sessionManager, _libraryManager, this); + _groups[group.GroupId] = group; - group.CreateGroup(session, cancellationToken); + group.CreateGroup(session, request, cancellationToken); } } @@ -206,14 +215,13 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.JoinGroupDenied }; - - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } lock (_groupsLock) { - ISyncPlayController group; + ISyncPlayGroupController group; _groups.TryGetValue(groupId, out group); if (group == null) @@ -224,20 +232,20 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.GroupDoesNotExist }; - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } - if (!HasAccessToItem(user, group.GetPlayingItemId())) + if (!group.HasAccessToPlayQueue(user)) { - _logger.LogWarning("JoinGroup: {0} does not have access to {1}.", session.Id, group.GetPlayingItemId()); + _logger.LogWarning("JoinGroup: {0} does not have access to some content from the playing queue of group {1}.", session.Id, group.GroupId.ToString()); var error = new GroupUpdate() { - GroupId = group.GetGroupId().ToString(), + GroupId = group.GroupId.ToString(), Type = GroupUpdateType.LibraryAccessDenied }; - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -245,6 +253,7 @@ namespace Emby.Server.Implementations.SyncPlay { if (GetSessionGroup(session).Equals(groupId)) { + group.SessionRestore(session, request, cancellationToken); return; } @@ -271,7 +280,7 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.NotInGroup }; - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -279,14 +288,14 @@ namespace Emby.Server.Implementations.SyncPlay if (group.IsGroupEmpty()) { - _logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GetGroupId()); - _groups.Remove(group.GetGroupId(), out _); + _logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GroupId); + _groups.Remove(group.GroupId, out _); } } } /// - public List ListGroups(SessionInfo session, Guid filterItemId) + public List ListGroups(SessionInfo session) { var user = _userManager.GetUserById(session.UserId); @@ -295,20 +304,9 @@ namespace Emby.Server.Implementations.SyncPlay return new List(); } - // Filter by item if requested - if (!filterItemId.Equals(Guid.Empty)) - { - return _groups.Values.Where( - group => group.GetPlayingItemId().Equals(filterItemId) && HasAccessToItem(user, group.GetPlayingItemId())).Select( - group => group.GetInfo()).ToList(); - } - else - { - // Otherwise show all available groups - return _groups.Values.Where( - group => HasAccessToItem(user, group.GetPlayingItemId())).Select( - group => group.GetInfo()).ToList(); - } + return _groups.Values.Where( + group => group.HasAccessToPlayQueue(user)).Select( + group => group.GetInfo()).ToList(); } /// @@ -324,8 +322,7 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.JoinGroupDenied }; - - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -341,7 +338,7 @@ namespace Emby.Server.Implementations.SyncPlay { Type = GroupUpdateType.NotInGroup }; - _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -350,7 +347,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public void AddSessionToGroup(SessionInfo session, ISyncPlayController group) + public void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group) { if (IsSessionInGroup(session)) { @@ -361,7 +358,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// - public void RemoveSessionFromGroup(SessionInfo session, ISyncPlayController group) + public void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group) { if (!IsSessionInGroup(session)) { @@ -369,7 +366,7 @@ namespace Emby.Server.Implementations.SyncPlay } _sessionToGroupMap.Remove(session.Id, out var tempGroup); - if (!tempGroup.GetGroupId().Equals(group.GetGroupId())) + if (!tempGroup.GroupId.Equals(group.GroupId)) { throw new InvalidOperationException("Session was in wrong group!"); } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index e16a10ba4d..847c3ab117 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -43,14 +43,20 @@ namespace Jellyfin.Api.Controllers /// /// Create a new SyncPlay group. /// + /// The name of the new group. /// New group created. /// A indicating success. [HttpPost("New")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayCreateGroup() + public ActionResult SyncPlayCreateGroup( + [FromQuery, Required] string groupName) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - _syncPlayManager.NewGroup(currentSession, CancellationToken.None); + var newGroupRequest = new NewGroupRequest() + { + GroupName = groupName + }; + _syncPlayManager.NewGroup(currentSession, newGroupRequest, CancellationToken.None); return NoContent(); } @@ -62,15 +68,14 @@ namespace Jellyfin.Api.Controllers /// A indicating success. [HttpPost("Join")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayJoinGroup([FromQuery, Required] Guid groupId) + public ActionResult SyncPlayJoinGroup( + [FromQuery, Required] Guid groupId) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var joinRequest = new JoinGroupRequest() { GroupId = groupId }; - _syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None); return NoContent(); } @@ -92,35 +97,143 @@ namespace Jellyfin.Api.Controllers /// /// Gets all SyncPlay groups. /// - /// Optional. Filter by item id. /// Groups returned. /// An containing the available SyncPlay groups. [HttpGet("List")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> SyncPlayGetGroups([FromQuery] Guid? filterItemId) + public ActionResult> SyncPlayGetGroups() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - return Ok(_syncPlayManager.ListGroups(currentSession, filterItemId.HasValue ? filterItemId.Value : Guid.Empty)); + return Ok(_syncPlayManager.ListGroups(currentSession)); } /// /// Request play in SyncPlay group. /// + /// The playing queue. Item ids in the playing queue, comma delimited. + /// The playing item position from the queue. + /// The start position ticks. /// Play request sent to all group members. /// A indicating success. [HttpPost("Play")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayPlay() + public ActionResult SyncPlayPlay( + [FromQuery, Required] string playingQueue, + [FromQuery, Required] int playingItemPosition, + [FromQuery, Required] long startPositionTicks) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlaybackRequest() + var syncPlayRequest = new PlayGroupRequest() { - Type = PlaybackRequestType.Play + PlayingQueue = RequestHelpers.GetGuids(playingQueue), + PlayingItemPosition = playingItemPosition, + StartPositionTicks = startPositionTicks }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } + /// + /// Request to change playlist item in SyncPlay group. + /// + /// The playlist id of the item. + /// Queue update request sent to all group members. + /// A indicating success. + [HttpPost("SetPlaylistItem")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlaySetPlaylistItem( + [FromQuery, Required] string playlistItemId) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new SetPlaylistItemGroupRequest() + { + PlaylistItemId = playlistItemId + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request to remove items from the playlist in SyncPlay group. + /// + /// The playlist ids of the items to remove. + /// Queue update request sent to all group members. + /// A indicating success. + [HttpPost("RemoveFromPlaylist")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayRemoveFromPlaylist( + [FromQuery, Required] string[] playlistItemIds) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new RemoveFromPlaylistGroupRequest() + { + PlaylistItemIds = playlistItemIds + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request to move an item in the playlist in SyncPlay group. + /// + /// The playlist id of the item to move. + /// The new position. + /// Queue update request sent to all group members. + /// A indicating success. + [HttpPost("MovePlaylistItem")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayMovePlaylistItem( + [FromQuery, Required] string playlistItemId, + [FromQuery, Required] int newIndex) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new MovePlaylistItemGroupRequest() + { + PlaylistItemId = playlistItemId, + NewIndex = newIndex + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request to queue items to the playlist of a SyncPlay group. + /// + /// The items to add. Item ids, comma delimited. + /// The mode in which to queue items. + /// Queue update request sent to all group members. + /// A indicating success. + [HttpPost("Queue")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayQueue( + [FromQuery, Required] string itemIds, + [FromQuery, Required] string mode) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new QueueGroupRequest() + { + ItemIds = RequestHelpers.GetGuids(itemIds), + Mode = mode + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request unpause in SyncPlay group. + /// + /// Unpause request sent to all group members. + /// A indicating success. + [HttpPost("Unpause")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayUnpause() + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new UnpauseGroupRequest(); + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + /// /// Request pause in SyncPlay group. /// @@ -131,10 +244,22 @@ namespace Jellyfin.Api.Controllers public ActionResult SyncPlayPause() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlaybackRequest() - { - Type = PlaybackRequestType.Pause - }; + var syncPlayRequest = new PauseGroupRequest(); + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request stop in SyncPlay group. + /// + /// Stop request sent to all group members. + /// A indicating success. + [HttpPost("Stop")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayStop() + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new StopGroupRequest(); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -147,12 +272,12 @@ namespace Jellyfin.Api.Controllers /// A indicating success. [HttpPost("Seek")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlaySeek([FromQuery] long positionTicks) + public ActionResult SyncPlaySeek( + [FromQuery, Required] long positionTicks) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlaybackRequest() + var syncPlayRequest = new SeekGroupRequest() { - Type = PlaybackRequestType.Seek, PositionTicks = positionTicks }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); @@ -164,19 +289,142 @@ namespace Jellyfin.Api.Controllers /// /// When the request has been made by the client. /// The playback position in ticks. + /// Whether the client's playback is playing or not. + /// The playlist item id. /// Whether the buffering is done. /// Buffering request sent to all group members. /// A indicating success. [HttpPost("Buffering")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayBuffering([FromQuery] DateTime when, [FromQuery] long positionTicks, [FromQuery] bool bufferingDone) + public ActionResult SyncPlayBuffering( + [FromQuery, Required] DateTime when, + [FromQuery, Required] long positionTicks, + [FromQuery, Required] bool isPlaying, + [FromQuery, Required] string playlistItemId, + [FromQuery, Required] bool bufferingDone) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlaybackRequest() + IPlaybackGroupRequest syncPlayRequest; + if (!bufferingDone) { - Type = bufferingDone ? PlaybackRequestType.Ready : PlaybackRequestType.Buffer, - When = when, - PositionTicks = positionTicks + syncPlayRequest = new BufferGroupRequest() + { + When = when, + PositionTicks = positionTicks, + IsPlaying = isPlaying, + PlaylistItemId = playlistItemId + }; + } + else + { + syncPlayRequest = new ReadyGroupRequest() + { + When = when, + PositionTicks = positionTicks, + IsPlaying = isPlaying, + PlaylistItemId = playlistItemId + }; + } + + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request SyncPlay group to ignore member during group-wait. + /// + /// Whether to ignore the member. + /// Member state updated. + /// A indicating success. + [HttpPost("SetIgnoreWait")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlaySetIgnoreWait( + [FromQuery, Required] bool ignoreWait) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new IgnoreWaitGroupRequest() + { + IgnoreWait = ignoreWait + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request next track in SyncPlay group. + /// + /// The playing item id. + /// Next track request sent to all group members. + /// A indicating success. + [HttpPost("NextTrack")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayNextTrack( + [FromQuery, Required] string playlistItemId) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new NextTrackGroupRequest() + { + PlaylistItemId = playlistItemId + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request previous track in SyncPlay group. + /// + /// The playing item id. + /// Previous track request sent to all group members. + /// A indicating success. + [HttpPost("PreviousTrack")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayPreviousTrack( + [FromQuery, Required] string playlistItemId) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new PreviousTrackGroupRequest() + { + PlaylistItemId = playlistItemId + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request to set repeat mode in SyncPlay group. + /// + /// The repeat mode. + /// Play queue update sent to all group members. + /// A indicating success. + [HttpPost("SetRepeatMode")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlaySetRepeatMode( + [FromQuery, Required] string mode) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new SetRepeatModeGroupRequest() + { + Mode = mode + }; + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + + /// + /// Request to set shuffle mode in SyncPlay group. + /// + /// The shuffle mode. + /// Play queue update sent to all group members. + /// A indicating success. + [HttpPost("SetShuffleMode")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlaySetShuffleMode( + [FromQuery, Required] string mode) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new SetShuffleModeGroupRequest() + { + Mode = mode }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); @@ -190,12 +438,12 @@ namespace Jellyfin.Api.Controllers /// A indicating success. [HttpPost("Ping")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayPing([FromQuery] double ping) + public ActionResult SyncPlayPing( + [FromQuery, Required] double ping) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlaybackRequest() + var syncPlayRequest = new PingGroupRequest() { - Type = PlaybackRequestType.Ping, Ping = Convert.ToInt64(ping) }; _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); diff --git a/MediaBrowser.Api/SyncPlay/SyncPlayService.cs b/MediaBrowser.Api/SyncPlay/SyncPlayService.cs deleted file mode 100644 index bd9670f07a..0000000000 --- a/MediaBrowser.Api/SyncPlay/SyncPlayService.cs +++ /dev/null @@ -1,267 +0,0 @@ -using System.Threading; -using System; -using System.Collections.Generic; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Session; -using MediaBrowser.Controller.SyncPlay; -using MediaBrowser.Model.Services; -using MediaBrowser.Model.SyncPlay; -using Microsoft.Extensions.Logging; - -namespace MediaBrowser.Api.SyncPlay -{ - [Route("/SyncPlay/New", "POST", Summary = "Create a new SyncPlay group")] - [Authenticated] - public class SyncPlayNew : IReturnVoid - { - } - - [Route("/SyncPlay/Join", "POST", Summary = "Join an existing SyncPlay group")] - [Authenticated] - public class SyncPlayJoin : IReturnVoid - { - /// - /// Gets or sets the Group id. - /// - /// The Group id to join. - [ApiMember(Name = "GroupId", Description = "Group Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string GroupId { get; set; } - } - - [Route("/SyncPlay/Leave", "POST", Summary = "Leave joined SyncPlay group")] - [Authenticated] - public class SyncPlayLeave : IReturnVoid - { - } - - [Route("/SyncPlay/List", "GET", Summary = "List SyncPlay groups")] - [Authenticated] - public class SyncPlayList : IReturnVoid - { - /// - /// Gets or sets the filter item id. - /// - /// The filter item id. - [ApiMember(Name = "FilterItemId", Description = "Filter by item id", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")] - public string FilterItemId { get; set; } - } - - [Route("/SyncPlay/Play", "POST", Summary = "Request play in SyncPlay group")] - [Authenticated] - public class SyncPlayPlay : IReturnVoid - { - } - - [Route("/SyncPlay/Pause", "POST", Summary = "Request pause in SyncPlay group")] - [Authenticated] - public class SyncPlayPause : IReturnVoid - { - } - - [Route("/SyncPlay/Seek", "POST", Summary = "Request seek in SyncPlay group")] - [Authenticated] - public class SyncPlaySeek : IReturnVoid - { - [ApiMember(Name = "PositionTicks", IsRequired = true, DataType = "long", ParameterType = "query", Verb = "POST")] - public long PositionTicks { get; set; } - } - - [Route("/SyncPlay/Buffering", "POST", Summary = "Request group wait in SyncPlay group while buffering")] - [Authenticated] - public class SyncPlayBuffering : IReturnVoid - { - /// - /// Gets or sets the date used to pin PositionTicks in time. - /// - /// The date related to PositionTicks. - [ApiMember(Name = "When", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")] - public string When { get; set; } - - [ApiMember(Name = "PositionTicks", IsRequired = true, DataType = "long", ParameterType = "query", Verb = "POST")] - public long PositionTicks { get; set; } - - /// - /// Gets or sets whether this is a buffering or a ready request. - /// - /// true if buffering is complete; false otherwise. - [ApiMember(Name = "BufferingDone", IsRequired = true, DataType = "bool", ParameterType = "query", Verb = "POST")] - public bool BufferingDone { get; set; } - } - - [Route("/SyncPlay/Ping", "POST", Summary = "Update session ping")] - [Authenticated] - public class SyncPlayPing : IReturnVoid - { - [ApiMember(Name = "Ping", IsRequired = true, DataType = "double", ParameterType = "query", Verb = "POST")] - public double Ping { get; set; } - } - - /// - /// Class SyncPlayService. - /// - public class SyncPlayService : BaseApiService - { - /// - /// The session context. - /// - private readonly ISessionContext _sessionContext; - - /// - /// The SyncPlay manager. - /// - private readonly ISyncPlayManager _syncPlayManager; - - public SyncPlayService( - ILogger logger, - IServerConfigurationManager serverConfigurationManager, - IHttpResultFactory httpResultFactory, - ISessionContext sessionContext, - ISyncPlayManager syncPlayManager) - : base(logger, serverConfigurationManager, httpResultFactory) - { - _sessionContext = sessionContext; - _syncPlayManager = syncPlayManager; - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayNew request) - { - var currentSession = GetSession(_sessionContext); - _syncPlayManager.NewGroup(currentSession, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayJoin request) - { - var currentSession = GetSession(_sessionContext); - - Guid groupId; - if (!Guid.TryParse(request.GroupId, out groupId)) - { - Logger.LogError("JoinGroup: {0} is not a valid format for GroupId. Ignoring request.", request.GroupId); - return; - } - - var joinRequest = new JoinGroupRequest() - { - GroupId = groupId - }; - - _syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayLeave request) - { - var currentSession = GetSession(_sessionContext); - _syncPlayManager.LeaveGroup(currentSession, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - /// The requested list of groups. - public List Get(SyncPlayList request) - { - var currentSession = GetSession(_sessionContext); - var filterItemId = Guid.Empty; - - if (!string.IsNullOrEmpty(request.FilterItemId) && !Guid.TryParse(request.FilterItemId, out filterItemId)) - { - Logger.LogWarning("ListGroups: {0} is not a valid format for FilterItemId. Ignoring filter.", request.FilterItemId); - } - - return _syncPlayManager.ListGroups(currentSession, filterItemId); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayPlay request) - { - var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PlayGroupRequest(); - _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayPause request) - { - var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PauseGroupRequest(); - _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlaySeek request) - { - var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new SeekGroupRequest() - { - PositionTicks = request.PositionTicks - }; - _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayBuffering request) - { - var currentSession = GetSession(_sessionContext); - - IPlaybackGroupRequest syncPlayRequest; - if (!request.BufferingDone) - { - syncPlayRequest = new BufferGroupRequest() - { - When = DateTime.Parse(request.When), - PositionTicks = request.PositionTicks - }; - } - else - { - syncPlayRequest = new ReadyGroupRequest() - { - When = DateTime.Parse(request.When), - PositionTicks = request.PositionTicks - }; - } - - _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); - } - - /// - /// Handles the specified request. - /// - /// The request. - public void Post(SyncPlayPing request) - { - var currentSession = GetSession(_sessionContext); - var syncPlayRequest = new PingGroupRequest() - { - Ping = Convert.ToInt64(request.Ping) - }; - _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); - } - } -} diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 04c3004ee6..9ad8557ce6 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -143,22 +143,22 @@ namespace MediaBrowser.Controller.Session Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken); /// - /// Sends the SyncPlayCommand. + /// Sends a SyncPlayCommand to a session. /// - /// The session id. + /// The session. /// The command. /// The cancellation token. /// Task. - Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken); + Task SendSyncPlayCommand(SessionInfo session, SendCommand command, CancellationToken cancellationToken); /// - /// Sends the SyncPlayGroupUpdate. + /// Sends a SyncPlayGroupUpdate to a session. /// - /// The session id. + /// The session. /// The group update. /// The cancellation token. /// Task. - Task SendSyncPlayGroupUpdate(string sessionId, GroupUpdate command, CancellationToken cancellationToken); + Task SendSyncPlayGroupUpdate(SessionInfo session, GroupUpdate command, CancellationToken cancellationToken); /// /// Sends the browse command. diff --git a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs b/MediaBrowser.Controller/SyncPlay/GroupInfo.cs deleted file mode 100644 index cdd24d0b59..0000000000 --- a/MediaBrowser.Controller/SyncPlay/GroupInfo.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Collections.Generic; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// - /// Class GroupInfo. - /// - /// - /// Class is not thread-safe, external locking is required when accessing methods. - /// - public class GroupInfo - { - /// - /// The default ping value used for sessions. - /// - public const long DefaultPing = 500; - - /// - /// Gets the group identifier. - /// - /// The group identifier. - public Guid GroupId { get; } = Guid.NewGuid(); - - /// - /// Gets or sets the playing item. - /// - /// The playing item. - public BaseItem PlayingItem { get; set; } - - /// - /// Gets or sets a value indicating whether there are position ticks. - /// - /// The position ticks. - public long PositionTicks { get; set; } - - /// - /// Gets or sets the last activity. - /// - /// The last activity. - public DateTime LastActivity { get; set; } - - /// - /// Gets the participants. - /// - /// The participants, or members of the group. - public Dictionary Participants { get; } = - new Dictionary(StringComparer.OrdinalIgnoreCase); - - /// - /// Checks if a session is in this group. - /// - /// The session id to check. - /// true if the session is in this group; false otherwise. - public bool ContainsSession(string sessionId) - { - return Participants.ContainsKey(sessionId); - } - - /// - /// Adds the session to the group. - /// - /// The session. - public void AddSession(SessionInfo session) - { - Participants.TryAdd( - session.Id, - new GroupMember - { - Session = session, - Ping = DefaultPing, - IsBuffering = false - }); - } - - /// - /// Removes the session from the group. - /// - /// The session. - public void RemoveSession(SessionInfo session) - { - Participants.Remove(session.Id); - } - - /// - /// Updates the ping of a session. - /// - /// The session. - /// The ping. - public void UpdatePing(SessionInfo session, long ping) - { - if (Participants.TryGetValue(session.Id, out GroupMember value)) - { - value.Ping = ping; - } - } - - /// - /// Gets the highest ping in the group. - /// - /// The highest ping in the group. - public long GetHighestPing() - { - long max = long.MinValue; - foreach (var session in Participants.Values) - { - max = Math.Max(max, session.Ping); - } - - return max; - } - - /// - /// Sets the session's buffering state. - /// - /// The session. - /// The state. - public void SetBuffering(SessionInfo session, bool isBuffering) - { - if (Participants.TryGetValue(session.Id, out GroupMember value)) - { - value.IsBuffering = isBuffering; - } - } - - /// - /// Gets the group buffering state. - /// - /// true if there is a session buffering in the group; false otherwise. - public bool IsBuffering() - { - foreach (var session in Participants.Values) - { - if (session.IsBuffering) - { - return true; - } - } - - return false; - } - - /// - /// Checks if the group is empty. - /// - /// true if the group is empty; false otherwise. - public bool IsEmpty() - { - return Participants.Count == 0; - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/GroupMember.cs b/MediaBrowser.Controller/SyncPlay/GroupMember.cs index cde6f8e8ce..9a9d30277f 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupMember.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupMember.cs @@ -7,12 +7,6 @@ namespace MediaBrowser.Controller.SyncPlay /// public class GroupMember { - /// - /// Gets or sets a value indicating whether this member is buffering. - /// - /// true if member is buffering; false otherwise. - public bool IsBuffering { get; set; } - /// /// Gets or sets the session. /// @@ -20,9 +14,21 @@ namespace MediaBrowser.Controller.SyncPlay public SessionInfo Session { get; set; } /// - /// Gets or sets the ping. + /// Gets or sets the ping, in milliseconds. /// /// The ping. public long Ping { get; set; } + + /// + /// Gets or sets a value indicating whether this member is buffering. + /// + /// true if member is buffering; false otherwise. + public bool IsBuffering { get; set; } + + /// + /// Gets or sets a value indicating whether this member is following group playback. + /// + /// true to ignore member on group wait; false if they're following group playback. + public bool IgnoreGroupWait { get; set; } } } diff --git a/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs index a6e87a007f..35ca64c8df 100644 --- a/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs @@ -12,13 +12,12 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Gets the playback request type. /// - /// The playback request type. - PlaybackRequestType Type(); + /// The playback request type. + PlaybackRequestType GetRequestType(); /// /// Applies the request to a group. /// - /// The operation completion status. - bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken); + void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs index 5ac2aeb247..9a4e1ee1ee 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs @@ -1,39 +1,41 @@ using System; using System.Threading; +using Jellyfin.Data.Entities; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// - /// Interface ISyncPlayController. + /// Interface ISyncPlayGroupController. /// - public interface ISyncPlayController + public interface ISyncPlayGroupController { /// - /// Gets the group id. + /// Gets the group identifier. /// - /// The group id. - Guid GetGroupId(); + /// The group identifier. + Guid GroupId { get; } /// - /// Gets the playing item id. + /// Gets the play queue. /// - /// The playing item id. - Guid GetPlayingItemId(); + /// The play queue. + PlayQueueManager PlayQueue { get; } /// /// Checks if the group is empty. /// - /// If the group is empty. + /// If the group is empty. bool IsGroupEmpty(); /// /// Initializes the group with the session's info. /// /// The session. + /// The request. /// The cancellation token. - void CreateGroup(SessionInfo session, CancellationToken cancellationToken); + void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); /// /// Adds the session to the group. @@ -43,6 +45,14 @@ namespace MediaBrowser.Controller.SyncPlay /// The cancellation token. void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); + /// + /// Restores the state of a session that already joined the group. + /// + /// The session. + /// The request. + /// The cancellation token. + void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); + /// /// Removes the session from the group. /// @@ -61,7 +71,15 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Gets the info about the group for the clients. /// - /// The group info for the clients. + /// The group info for the clients. GroupInfoDto GetInfo(); + + /// + /// Checks if a user has access to all content in the play queue. + /// + /// The user. + /// true if the user can access the play queue; false otherwise. + bool HasAccessToPlayQueue(User user); + } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 6fa94e2ce4..9bef3f5593 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -15,8 +15,9 @@ namespace MediaBrowser.Controller.SyncPlay /// Creates a new group. /// /// The session that's creating the group. + /// The request. /// The cancellation token. - void NewGroup(SessionInfo session, CancellationToken cancellationToken); + void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); /// /// Adds the session to a group. @@ -38,9 +39,8 @@ namespace MediaBrowser.Controller.SyncPlay /// Gets list of available groups for a session. /// /// The session. - /// The item id to filter by. - /// The list of available groups. - List ListGroups(SessionInfo session, Guid filterItemId); + /// The list of available groups. + List ListGroups(SessionInfo session); /// /// Handle a request by a session in a group. @@ -56,7 +56,7 @@ namespace MediaBrowser.Controller.SyncPlay /// The session. /// The group. /// - void AddSessionToGroup(SessionInfo session, ISyncPlayController group); + void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group); /// /// Unmaps a session from a group. @@ -64,6 +64,6 @@ namespace MediaBrowser.Controller.SyncPlay /// The session. /// The group. /// - void RemoveSessionFromGroup(SessionInfo session, ISyncPlayController group); + void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group); } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs index 55c9ee938f..290576e30f 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs @@ -15,81 +15,202 @@ namespace MediaBrowser.Controller.SyncPlay /// The group state. GroupState GetGroupState(); + /// + /// Handle a session that joined the group. + /// + /// The context of the state. + /// The previous state. + /// The session. + /// The cancellation token. + void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handle a session that is leaving the group. + /// + /// The context of the state. + /// The previous state. + /// The session. + /// The cancellation token. + void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + /// /// Generic handle. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. - /// The play action. + /// The previous state. + /// The generic action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Handles a play action requested by a session. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The play action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a playlist-item change requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The playlist-item change action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a remove-items change requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The remove-items change action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a move-item change requested by a session. Context's state should not change. + /// + /// The context of the state. + /// The previous state. + /// The move-item change action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a queue change requested by a session. Context's state should not change. + /// + /// The context of the state. + /// The previous state. + /// The queue action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles an unpause action requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The unpause action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Handles a pause action requested by a session. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The pause action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a stop action requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The stop action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Handles a seek action requested by a session. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The seek action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Handles a buffering action requested by a session. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The buffering action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Handles a buffering-done action requested by a session. Context's state can change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The buffering-done action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a next-track action requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The next-track action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a previous-track action requested by a session. Context's state can change. + /// + /// The context of the state. + /// The previous state. + /// The previous-track action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a repeat-mode change requested by a session. Context's state should not change. + /// + /// The context of the state. + /// The previous state. + /// The repeat-mode action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Handles a shuffle-mode change requested by a session. Context's state should not change. + /// + /// The context of the state. + /// The previous state. + /// The shuffle-mode action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// /// Updates ping of a session. Context's state should not change. /// /// The context of the state. - /// Whether the state has been just set. + /// The previous state. /// The buffering-done action. /// The session. /// The cancellation token. - /// The operation completion status. - bool HandleRequest(ISyncPlayStateContext context, bool newState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + + /// + /// Updates whether the session should be considered during group wait. Context's state should not change. + /// + /// The context of the state. + /// The previous state. + /// The ignore-wait action. + /// The session. + /// The cancellation token. + void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs index 9bdb1ace6c..18a6857491 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs @@ -12,10 +12,34 @@ namespace MediaBrowser.Controller.SyncPlay public interface ISyncPlayStateContext { /// - /// Gets the context's group. + /// Gets the default ping value used for sessions, in milliseconds. /// - /// The group. - GroupInfo GetGroup(); + /// The default ping value used for sessions, in milliseconds. + long DefaultPing { get; } + + /// + /// Gets the group identifier. + /// + /// The group identifier. + Guid GroupId { get; } + + /// + /// Gets or sets the position ticks. + /// + /// The position ticks. + long PositionTicks { get; set; } + + /// + /// Gets or sets the last activity. + /// + /// The last activity. + DateTime LastActivity { get; set; } + + /// + /// Gets the play queue. + /// + /// The play queue. + PlayQueueManager PlayQueue { get; } /// /// Sets a new state. @@ -30,7 +54,7 @@ namespace MediaBrowser.Controller.SyncPlay /// The filtering type. /// The message to send. /// The cancellation token. - /// The task. + /// The task. Task SendGroupUpdate(SessionInfo from, SyncPlayBroadcastType type, GroupUpdate message, CancellationToken cancellationToken); /// @@ -40,14 +64,14 @@ namespace MediaBrowser.Controller.SyncPlay /// The filtering type. /// The message to send. /// The cancellation token. - /// The task. + /// The task. Task SendCommand(SessionInfo from, SyncPlayBroadcastType type, SendCommand message, CancellationToken cancellationToken); /// /// Builds a new playback command with some default values. /// /// The command type. - /// The SendCommand. + /// The SendCommand. SendCommand NewSyncPlayCommand(SendCommandType type); /// @@ -55,21 +79,135 @@ namespace MediaBrowser.Controller.SyncPlay /// /// The update type. /// The data to send. - /// The GroupUpdate. + /// The GroupUpdate. GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data); /// /// Converts DateTime to UTC string. /// - /// The date to convert. - /// The UTC string. - string DateToUTCString(DateTime date); + /// The date to convert. + /// The UTC string. + string DateToUTCString(DateTime dateTime); /// /// Sanitizes the PositionTicks, considers the current playing item when available. /// /// The PositionTicks. - /// The sanitized PositionTicks. + /// The sanitized PositionTicks. long SanitizePositionTicks(long? positionTicks); + + /// + /// Updates the ping of a session, in milliseconds. + /// + /// The session. + /// The ping, in milliseconds. + void UpdatePing(SessionInfo session, long ping); + + /// + /// Gets the highest ping in the group, in milliseconds. + /// + /// The highest ping in the group. + long GetHighestPing(); + + /// + /// Sets the session's buffering state. + /// + /// The session. + /// The state. + void SetBuffering(SessionInfo session, bool isBuffering); + + /// + /// Sets the buffering state of all the sessions. + /// + /// The state. + void SetAllBuffering(bool isBuffering); + + /// + /// Gets the group buffering state. + /// + /// true if there is a session buffering in the group; false otherwise. + bool IsBuffering(); + + /// + /// Sets the session's group wait state. + /// + /// The session. + /// The state. + void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait); + + /// + /// Sets a new play queue. + /// + /// The new play queue. + /// The playing item position in the play queue. + /// The start position ticks. + /// true if the play queue has been changed; false is something went wrong. + bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks); + + /// + /// Sets the playing item. + /// + /// The new playing item id. + /// true if the play queue has been changed; false is something went wrong. + bool SetPlayingItem(string playlistItemId); + + /// + /// Removes items from the play queue. + /// + /// The items to remove. + /// true if playing item got removed; false otherwise. + bool RemoveFromPlayQueue(string[] playlistItemIds); + + /// + /// Moves an item in the play queue. + /// + /// The playlist id of the item to move. + /// The new position. + /// true if item has been moved; false is something went wrong. + bool MoveItemInPlayQueue(string playlistItemId, int newIndex); + + /// + /// Updates the play queue. + /// + /// The new items to add to the play queue. + /// The mode with which the items will be added. + /// true if the play queue has been changed; false is something went wrong. + bool AddToPlayQueue(Guid[] newItems, string mode); + + /// + /// Restarts current item in play queue. + /// + void RestartCurrentItem(); + + /// + /// Picks next item in play queue. + /// + /// true if the item changed; false otherwise. + bool NextItemInQueue(); + + /// + /// Picks previous item in play queue. + /// + /// true if the item changed; false otherwise. + bool PreviousItemInQueue(); + + /// + /// Sets the repeat mode. + /// + /// The new mode. + void SetRepeatMode(string mode); + + /// + /// Sets the shuffle mode. + /// + /// The new mode. + void SetShuffleMode(string mode); + + /// + /// Creates a play queue update. + /// + /// The reason for the update. + /// The play queue update. + PlayQueueUpdate GetPlayQueueUpdate(PlayQueueUpdateReason reason); } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs index 21dae8e4e6..0815dd79b2 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs @@ -23,21 +23,27 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// - /// Gets or sets the playing item id. + /// Gets or sets the client playback status. /// - /// The playing item id. - public Guid PlayingItemId { get; set; } + /// The client playback status. + public bool IsPlaying { get; set; } + + /// + /// Gets or sets the playlist item id of the playing item. + /// + /// The playlist item id. + public string PlaylistItemId { get; set; } /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Buffer; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs new file mode 100644 index 0000000000..5466cbe2f7 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class IgnoreWaitGroupRequest. + /// + public class IgnoreWaitGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the client group-wait status. + /// + /// The client group-wait status. + public bool IgnoreWait { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.IgnoreWait; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs new file mode 100644 index 0000000000..7a293c02fd --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs @@ -0,0 +1,36 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class MovePlaylistItemGroupRequest. + /// + public class MovePlaylistItemGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the playlist id of the item. + /// + /// The playlist id of the item. + public string PlaylistItemId { get; set; } + + /// + /// Gets or sets the new position. + /// + /// The new position. + public int NewIndex { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.Queue; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs new file mode 100644 index 0000000000..d19df2c6a0 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class NextTrackGroupRequest. + /// + public class NextTrackGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the playing item id. + /// + /// The playing item id. + public string PlaylistItemId { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.NextTrack; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs index 21a46add8c..facb25155c 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs @@ -10,15 +10,15 @@ namespace MediaBrowser.Controller.SyncPlay public class PauseGroupRequest : IPlaybackGroupRequest { /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Pause; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs index 2f78edfc56..631bf245b1 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs @@ -2,7 +2,6 @@ using System.Threading; using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; -// FIXME: not really group related, can be moved up to SyncPlayController maybe? namespace MediaBrowser.Controller.SyncPlay { /// @@ -17,15 +16,15 @@ namespace MediaBrowser.Controller.SyncPlay public long Ping { get; set; } /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Ping; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs index 942229a775..f3dd769e46 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; @@ -9,16 +10,34 @@ namespace MediaBrowser.Controller.SyncPlay /// public class PlayGroupRequest : IPlaybackGroupRequest { + /// + /// Gets or sets the playing queue. + /// + /// The playing queue. + public Guid[] PlayingQueue { get; set; } + + /// + /// Gets or sets the playing item from the queue. + /// + /// The playing item. + public int PlayingItemPosition { get; set; } + + /// + /// Gets or sets the start position ticks. + /// + /// The start position ticks. + public long StartPositionTicks { get; set; } + /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Play; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs new file mode 100644 index 0000000000..663011b429 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class PreviousTrackGroupRequest. + /// + public class PreviousTrackGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the playing item id. + /// + /// The playing item id. + public string PlaylistItemId { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.PreviousTrack; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs new file mode 100644 index 0000000000..01c08cc860 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class QueueGroupRequest. + /// + public class QueueGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the items to queue. + /// + /// The items to queue. + public Guid[] ItemIds { get; set; } + + /// + /// Gets or sets the mode in which to add the new items. + /// + /// The mode. + public string Mode { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.Queue; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs index ee88ddddbb..16bc67c617 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs @@ -23,21 +23,27 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// - /// Gets or sets the playing item id. + /// Gets or sets the client playback status. /// - /// The playing item id. - public Guid PlayingItemId { get; set; } + /// The client playback status. + public bool IsPlaying { get; set; } + + /// + /// Gets or sets the playlist item id of the playing item. + /// + /// The playlist item id. + public string PlaylistItemId { get; set; } /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Ready; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs new file mode 100644 index 0000000000..3fc77f6771 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class RemoveFromPlaylistGroupRequest. + /// + public class RemoveFromPlaylistGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the playlist ids ot the items. + /// + /// The playlist ids ot the items. + public string[] PlaylistItemIds { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.Queue; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs index bb5e7a343e..24d9be5073 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs @@ -16,15 +16,15 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// - public PlaybackRequestType Type() + public PlaybackRequestType GetRequestType() { return PlaybackRequestType.Seek; } /// - public bool Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) { - return state.HandleRequest(context, false, this, session, cancellationToken); + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs new file mode 100644 index 0000000000..d70559899a --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class SetPlaylistItemGroupRequest. + /// + public class SetPlaylistItemGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the playlist id of the playing item. + /// + /// The playlist id of the playing item. + public string PlaylistItemId { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.SetPlaylistItem; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs new file mode 100644 index 0000000000..5f36f60e45 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class SetRepeatModeGroupRequest. + /// + public class SetRepeatModeGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the repeat mode. + /// + /// The repeat mode. + public string Mode { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.SetRepeatMode; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs new file mode 100644 index 0000000000..472455fd3b --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs @@ -0,0 +1,30 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class SetShuffleModeGroupRequest. + /// + public class SetShuffleModeGroupRequest : IPlaybackGroupRequest + { + /// + /// Gets or sets the shuffle mode. + /// + /// The shuffle mode. + public string Mode { get; set; } + + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.SetShuffleMode; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs new file mode 100644 index 0000000000..f1581c98d9 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs @@ -0,0 +1,24 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class StopGroupRequest. + /// + public class StopGroupRequest : IPlaybackGroupRequest + { + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.Stop; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs new file mode 100644 index 0000000000..1072952081 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs @@ -0,0 +1,24 @@ +using System.Threading; +using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Controller.Session; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// + /// Class UnpauseGroupRequest. + /// + public class UnpauseGroupRequest : IPlaybackGroupRequest + { + /// + public PlaybackRequestType GetRequestType() + { + return PlaybackRequestType.Unpause; + } + + /// + public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs new file mode 100644 index 0000000000..701982cc00 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -0,0 +1,596 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + static class ListShuffleExtension + { + private static Random rng = new Random(); + public static void Shuffle(this IList list) + { + int n = list.Count; + while (n > 1) + { + n--; + int k = rng.Next(n + 1); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } + } + + /// + /// Class PlayQueueManager. + /// + public class PlayQueueManager : IDisposable + { + /// + /// Gets or sets the playing item index. + /// + /// The playing item index. + public int PlayingItemIndex { get; private set; } + + /// + /// Gets or sets the last time the queue has been changed. + /// + /// The last time the queue has been changed. + public DateTime LastChange { get; private set; } + + /// + /// Gets the sorted playlist. + /// + /// The sorted playlist, or play queue of the group. + private List SortedPlaylist { get; set; } = new List(); + + /// + /// Gets the shuffled playlist. + /// + /// The shuffled playlist, or play queue of the group. + private List ShuffledPlaylist { get; set; } = new List(); + + /// + /// Gets or sets the shuffle mode. + /// + /// The shuffle mode. + public GroupShuffleMode ShuffleMode { get; private set; } = GroupShuffleMode.Sorted; + + /// + /// Gets or sets the repeat mode. + /// + /// The repeat mode. + public GroupRepeatMode RepeatMode { get; private set; } = GroupRepeatMode.RepeatNone; + + /// + /// Gets or sets the progressive id counter. + /// + /// The progressive id. + private int ProgressiveId { get; set; } = 0; + + private bool _disposed = false; + + /// + /// Initializes a new instance of the class. + /// + public PlayQueueManager() + { + Reset(); + } + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and optionally managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (_disposed) + { + return; + } + + _disposed = true; + } + + /// + /// Gets the next available id. + /// + /// The next available id. + private int GetNextProgressiveId() { + return ProgressiveId++; + } + + /// + /// Creates a list from the array of items. Each item is given an unique playlist id. + /// + /// The list of queue items. + private List CreateQueueItemsFromArray(Guid[] items) + { + return items.ToList() + .Select(item => new QueueItem() + { + ItemId = item, + PlaylistItemId = "syncPlayItem" + GetNextProgressiveId() + }) + .ToList(); + } + + /// + /// Gets the current playlist, depending on the shuffle mode. + /// + /// The playlist. + private List GetPlaylistAsList() + { + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + return ShuffledPlaylist; + } + else + { + return SortedPlaylist; + } + } + + /// + /// Gets the current playlist as an array, depending on the shuffle mode. + /// + /// The array of items in the playlist. + public QueueItem[] GetPlaylist() { + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + return ShuffledPlaylist.ToArray(); + } + else + { + return SortedPlaylist.ToArray(); + } + } + + /// + /// Sets a new playlist. Playing item is set to none. Resets shuffle mode and repeat mode as well. + /// + /// The new items of the playlist. + public void SetPlaylist(Guid[] items) + { + SortedPlaylist = CreateQueueItemsFromArray(items); + PlayingItemIndex = -1; + ShuffleMode = GroupShuffleMode.Sorted; + RepeatMode = GroupRepeatMode.RepeatNone; + LastChange = DateTime.UtcNow; + } + + /// + /// Appends new items to the playlist. The specified order is mantained for the sorted playlist, whereas items get shuffled for the shuffled playlist. + /// + /// The items to add to the playlist. + public void Queue(Guid[] items) + { + var newItems = CreateQueueItemsFromArray(items); + SortedPlaylist.AddRange(newItems); + + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + newItems.Shuffle(); + ShuffledPlaylist.AddRange(newItems); + } + + LastChange = DateTime.UtcNow; + } + + /// + /// Shuffles the playlist. Shuffle mode is changed. + /// + public void ShufflePlaylist() + { + if (SortedPlaylist.Count() == 0) + { + return; + } + + if (PlayingItemIndex < 0) { + ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist.Shuffle(); + } + else + { + var playingItem = SortedPlaylist[PlayingItemIndex]; + ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist.RemoveAt(PlayingItemIndex); + ShuffledPlaylist.Shuffle(); + ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); + PlayingItemIndex = 0; + } + + ShuffleMode = GroupShuffleMode.Shuffle; + LastChange = DateTime.UtcNow; + } + + /// + /// Resets the playlist to sorted mode. Shuffle mode is changed. + /// + public void SortShuffledPlaylist() + { + if (PlayingItemIndex >= 0) + { + var playingItem = ShuffledPlaylist[PlayingItemIndex]; + PlayingItemIndex = SortedPlaylist.IndexOf(playingItem); + } + + ShuffledPlaylist.Clear(); + + ShuffleMode = GroupShuffleMode.Sorted; + LastChange = DateTime.UtcNow; + } + + /// + /// Clears the playlist. + /// + /// Whether to remove the playing item as well. + public void ClearPlaylist(bool clearPlayingItem) + { + var playingItem = SortedPlaylist[PlayingItemIndex]; + SortedPlaylist.Clear(); + ShuffledPlaylist.Clear(); + LastChange = DateTime.UtcNow; + + if (!clearPlayingItem && playingItem != null) + { + SortedPlaylist.Add(playingItem); + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + SortedPlaylist.Add(playingItem); + } + } + } + + /// + /// Adds new items to the playlist right after the playing item. The specified order is mantained for the sorted playlist, whereas items get shuffled for the shuffled playlist. + /// + /// The items to add to the playlist. + public void QueueNext(Guid[] items) + { + var newItems = CreateQueueItemsFromArray(items); + + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + // Append items to sorted playlist as they are + SortedPlaylist.AddRange(newItems); + // Shuffle items before adding to shuffled playlist + newItems.Shuffle(); + ShuffledPlaylist.InsertRange(PlayingItemIndex + 1, newItems); + } + else + { + SortedPlaylist.InsertRange(PlayingItemIndex + 1, newItems); + } + + LastChange = DateTime.UtcNow; + } + + /// + /// Gets playlist id of the playing item, if any. + /// + /// The playlist id of the playing item. + public string GetPlayingItemPlaylistId() + { + if (PlayingItemIndex < 0) + { + return null; + } + + var list = GetPlaylistAsList(); + + if (list.Count() > 0) + { + return list[PlayingItemIndex].PlaylistItemId; + } + else + { + return null; + } + } + + /// + /// Gets the playing item id, if any. + /// + /// The playing item id. + public Guid GetPlayingItemId() + { + if (PlayingItemIndex < 0) + { + return Guid.Empty; + } + + var list = GetPlaylistAsList(); + + if (list.Count() > 0) + { + return list[PlayingItemIndex].ItemId; + } + else + { + return Guid.Empty; + } + } + + /// + /// Sets the playing item using its id. If not in the playlist, the playing item is reset. + /// + /// The new playing item id. + public void SetPlayingItemById(Guid itemId) + { + var itemIds = GetPlaylistAsList().Select(queueItem => queueItem.ItemId).ToList(); + PlayingItemIndex = itemIds.IndexOf(itemId); + LastChange = DateTime.UtcNow; + } + + /// + /// Sets the playing item using its playlist id. If not in the playlist, the playing item is reset. + /// + /// The new playing item id. + /// true if playing item has been set; false if item is not in the playlist. + public bool SetPlayingItemByPlaylistId(string playlistItemId) + { + var playlistIds = GetPlaylistAsList().Select(queueItem => queueItem.PlaylistItemId).ToList(); + PlayingItemIndex = playlistIds.IndexOf(playlistItemId); + LastChange = DateTime.UtcNow; + return PlayingItemIndex != -1; + } + + /// + /// Sets the playing item using its position. If not in range, the playing item is reset. + /// + /// The new playing item index. + public void SetPlayingItemByIndex(int playlistIndex) + { + var list = GetPlaylistAsList(); + if (playlistIndex < 0 || playlistIndex > list.Count()) + { + PlayingItemIndex = -1; + } + else + { + PlayingItemIndex = playlistIndex; + } + + LastChange = DateTime.UtcNow; + } + + /// + /// Removes items from the playlist. If not removed, the playing item is preserved. + /// + /// The items to remove. + /// true if playing item got removed; false otherwise. + public bool RemoveFromPlaylist(string[] playlistItemIds) + { + var playingItem = SortedPlaylist[PlayingItemIndex]; + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + playingItem = ShuffledPlaylist[PlayingItemIndex]; + } + + var playlistItemIdsList = playlistItemIds.ToList(); + SortedPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); + ShuffledPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); + + LastChange = DateTime.UtcNow; + + if (playingItem != null) + { + if (playlistItemIds.Contains(playingItem.PlaylistItemId)) + { + // Playing item has been removed, picking previous item + PlayingItemIndex--; + if (PlayingItemIndex < 0) + { + // Was first element, picking next if available + PlayingItemIndex = SortedPlaylist.Count() > 0 ? 0 : -1; + } + + return true; + } + else + { + // Restoring playing item + SetPlayingItemByPlaylistId(playingItem.PlaylistItemId); + return false; + } + } + else + { + return false; + } + } + + /// + /// Moves an item in the playlist to another position. + /// + /// The item to move. + /// The new position. + /// true if the item has been moved; false otherwise. + public bool MovePlaylistItem(string playlistItemId, int newIndex) + { + var list = GetPlaylistAsList(); + var playingItem = list[PlayingItemIndex]; + + var playlistIds = list.Select(queueItem => queueItem.PlaylistItemId).ToList(); + var oldIndex = playlistIds.IndexOf(playlistItemId); + if (oldIndex < 0) { + return false; + } + + var queueItem = list[oldIndex]; + list.RemoveAt(oldIndex); + newIndex = newIndex > list.Count() ? list.Count() : newIndex; + newIndex = newIndex < 0 ? 0 : newIndex; + list.Insert(newIndex, queueItem); + + LastChange = DateTime.UtcNow; + PlayingItemIndex = list.IndexOf(playingItem); + return true; + } + + /// + /// Resets the playlist to its initial state. + /// + public void Reset() + { + ProgressiveId = 0; + SortedPlaylist.Clear(); + ShuffledPlaylist.Clear(); + PlayingItemIndex = -1; + ShuffleMode = GroupShuffleMode.Sorted; + RepeatMode = GroupRepeatMode.RepeatNone; + LastChange = DateTime.UtcNow; + } + + /// + /// Sets the repeat mode. + /// + /// The new mode. + public void SetRepeatMode(string mode) + { + switch (mode) + { + case "RepeatOne": + RepeatMode = GroupRepeatMode.RepeatOne; + break; + case "RepeatAll": + RepeatMode = GroupRepeatMode.RepeatAll; + break; + default: + RepeatMode = GroupRepeatMode.RepeatNone; + break; + } + + LastChange = DateTime.UtcNow; + } + + /// + /// Sets the shuffle mode. + /// + /// The new mode. + public void SetShuffleMode(string mode) + { + switch (mode) + { + case "Shuffle": + ShufflePlaylist(); + break; + default: + SortShuffledPlaylist(); + break; + } + } + + /// + /// Toggles the shuffle mode between sorted and shuffled. + /// + public void ToggleShuffleMode() + { + SetShuffleMode(ShuffleMode.Equals(GroupShuffleMode.Shuffle) ? "Shuffle" : ""); + } + + /// + /// Gets the next item in the playlist considering repeat mode and shuffle mode. + /// + /// The next item in the playlist. + public QueueItem GetNextItemPlaylistId() + { + int newIndex; + var playlist = GetPlaylistAsList(); + + switch (RepeatMode) + { + case GroupRepeatMode.RepeatOne: + newIndex = PlayingItemIndex; + break; + case GroupRepeatMode.RepeatAll: + newIndex = PlayingItemIndex + 1; + if (newIndex >= playlist.Count()) + { + newIndex = 0; + } + break; + default: + newIndex = PlayingItemIndex + 1; + break; + } + + if (newIndex < 0 || newIndex >= playlist.Count()) + { + return null; + } + + return playlist[newIndex]; + } + + /// + /// Sets the next item in the queue as playing item. + /// + /// true if the playing item changed; false otherwise. + public bool Next() + { + if (RepeatMode.Equals(GroupRepeatMode.RepeatOne)) + { + LastChange = DateTime.UtcNow; + return true; + } + + PlayingItemIndex++; + if (PlayingItemIndex >= SortedPlaylist.Count()) + { + if (RepeatMode.Equals(GroupRepeatMode.RepeatAll)) + { + PlayingItemIndex = 0; + } + else + { + PlayingItemIndex--; + return false; + } + } + + LastChange = DateTime.UtcNow; + return true; + } + + /// + /// Sets the previous item in the queue as playing item. + /// + /// true if the playing item changed; false otherwise. + public bool Previous() + { + if (RepeatMode.Equals(GroupRepeatMode.RepeatOne)) + { + LastChange = DateTime.UtcNow; + return true; + } + + PlayingItemIndex--; + if (PlayingItemIndex < 0) + { + if (RepeatMode.Equals(GroupRepeatMode.RepeatAll)) + { + PlayingItemIndex = SortedPlaylist.Count() - 1; + } + else + { + PlayingItemIndex++; + return false; + } + } + + LastChange = DateTime.UtcNow; + return true; + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs b/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs deleted file mode 100644 index 0b72d16686..0000000000 --- a/MediaBrowser.Controller/SyncPlay/SyncPlayAbstractState.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Threading; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.SyncPlay; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// - /// Class SyncPlayAbstractState. - /// - /// - /// Class is not thread-safe, external locking is required when accessing methods. - /// - public abstract class SyncPlayAbstractState : ISyncPlayState - { - /// - public abstract GroupState GetGroupState(); - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - return true; - } - - /// - public virtual bool HandleRequest(ISyncPlayStateContext context, bool newState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - GroupInfo group = context.GetGroup(); - - // Collected pings are used to account for network latency when unpausing playback - group.UpdatePing(session, request.Ping); - - return true; - } - } -} diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs index ac84a26dc3..255f6812bd 100644 --- a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs +++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; namespace MediaBrowser.Model.SyncPlay { /// - /// Class GroupInfoView. + /// Class GroupInfoDto. /// public class GroupInfoDto { @@ -16,27 +16,27 @@ namespace MediaBrowser.Model.SyncPlay public string GroupId { get; set; } /// - /// Gets or sets the playing item id. + /// Gets or sets the group name. /// - /// The playing item id. - public string PlayingItemId { get; set; } + /// The group name. + public string GroupName { get; set; } /// - /// Gets or sets the playing item name. + /// Gets or sets the group state. /// - /// The playing item name. - public string PlayingItemName { get; set; } - - /// - /// Gets or sets the position ticks. - /// - /// The position ticks. - public long PositionTicks { get; set; } + /// The group state. + public GroupState State { get; set; } /// /// Gets or sets the participants. /// /// The participants. public IReadOnlyList Participants { get; set; } + + /// + /// Gets or sets the date when this dto has been updated. + /// + /// The date when this dto has been updated. + public string LastUpdatedAt { get; set; } } } diff --git a/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs b/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs new file mode 100644 index 0000000000..4895e57b7f --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupRepeatMode.cs @@ -0,0 +1,23 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Enum GroupRepeatMode. + /// + public enum GroupRepeatMode + { + /// + /// Repeat one item only. + /// + RepeatOne = 0, + + /// + /// Cycle the playlist. + /// + RepeatAll = 1, + + /// + /// Do not repeat. + /// + RepeatNone = 2 + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs b/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs new file mode 100644 index 0000000000..de860883c0 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupShuffleMode.cs @@ -0,0 +1,18 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Enum GroupShuffleMode. + /// + public enum GroupShuffleMode + { + /// + /// Sorted playlist. + /// + Sorted = 0, + + /// + /// Shuffled playlist. + /// + Shuffle = 1 + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs new file mode 100644 index 0000000000..7c7b267e6f --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs @@ -0,0 +1,22 @@ +#nullable disable + +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Class GroupStateUpdate. + /// + public class GroupStateUpdate + { + /// + /// Gets or sets the state of the group. + /// + /// The state of the group. + public GroupState State { get; set; } + + /// + /// Gets or sets the reason of the state change. + /// + /// The reason of the state change. + public PlaybackRequestType Reason { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs index c749f7b13a..7423bff117 100644 --- a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs +++ b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs @@ -26,14 +26,14 @@ namespace MediaBrowser.Model.SyncPlay GroupLeft, /// - /// The group-wait update. Tells members of the group that a user is buffering. + /// The group-state update. Tells members of the group that the state changed. /// - GroupWait, + StateUpdate, /// - /// The prepare-session update. Tells a user to load some content. + /// The play-queue update. Tells a user what's the playing queue of the group. /// - PrepareSession, + PlayQueue, /// /// The not-in-group error. Tells a user that they don't belong to a group. diff --git a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs index 0c77a61322..04f3a73b17 100644 --- a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs +++ b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs @@ -8,9 +8,9 @@ namespace MediaBrowser.Model.SyncPlay public class JoinGroupRequest { /// - /// Gets or sets the Group id. + /// Gets or sets the group id. /// - /// The Group id to join. + /// The id of the group to join. public Guid GroupId { get; set; } } } diff --git a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs new file mode 100644 index 0000000000..ccab5313f7 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs @@ -0,0 +1,16 @@ +#nullable disable + +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Class NewGroupRequest. + /// + public class NewGroupRequest + { + /// + /// Gets or sets the group name. + /// + /// The name of the new group. + public string GroupName { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs new file mode 100644 index 0000000000..5e2740a892 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs @@ -0,0 +1,52 @@ +#nullable disable + +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Class PlayQueueUpdate. + /// + public class PlayQueueUpdate + { + /// + /// Gets or sets the request type that originated this update. + /// + /// The reason for the update. + public PlayQueueUpdateReason Reason { get; set; } + + /// + /// Gets or sets the UTC time of the last change to the playing queue. + /// + /// The UTC time of the last change to the playing queue. + public string LastUpdate { get; set; } + + /// + /// Gets or sets the playlist. + /// + /// The playlist. + public QueueItem[] Playlist { get; set; } + + /// + /// Gets or sets the playing item index in the playlist. + /// + /// The playing item index in the playlist. + public int PlayingItemIndex { get; set; } + + /// + /// Gets or sets the start position ticks. + /// + /// The start position ticks. + public long StartPositionTicks { get; set; } + + /// + /// Gets or sets the shuffle mode. + /// + /// The shuffle mode. + public GroupShuffleMode ShuffleMode { get; set; } + + /// + /// Gets or sets the repeat mode. + /// + /// The repeat mode. + public GroupRepeatMode RepeatMode { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs new file mode 100644 index 0000000000..4b3f6eb4d6 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs @@ -0,0 +1,58 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Enum PlayQueueUpdateReason. + /// + public enum PlayQueueUpdateReason + { + /// + /// A user is requesting to play a new playlist. + /// + NewPlaylist = 0, + + /// + /// A user is changing the playing item. + /// + SetCurrentItem = 1, + + /// + /// A user is removing items from the playlist. + /// + RemoveItems = 2, + + /// + /// A user is moving an item in the playlist. + /// + MoveItem = 3, + + /// + /// A user is making changes to the queue. + /// + Queue = 4, + + /// + /// A user is making changes to the queue. + /// + QueueNext = 5, + + /// + /// A user is requesting the next item in queue. + /// + NextTrack = 6, + + /// + /// A user is requesting the previous item in queue. + /// + PreviousTrack = 7, + + /// + /// A user is changing repeat mode. + /// + RepeatMode = 8, + + /// + /// A user is changing shuffle mode. + /// + ShuffleMode = 9 + } +} diff --git a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs index e89efeed8a..0d0f48ea97 100644 --- a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs +++ b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs @@ -6,33 +6,87 @@ namespace MediaBrowser.Model.SyncPlay public enum PlaybackRequestType { /// - /// A user is requesting a play command for the group. + /// A user is setting a new playlist. /// Play = 0, + /// + /// A user is changing the playlist item. + /// + SetPlaylistItem = 1, + + /// + /// A user is removing items from the playlist. + /// + RemoveFromPlaylist = 2, + + /// + /// A user is moving an item in the playlist. + /// + MovePlaylistItem = 3, + + /// + /// A user is adding items to the playlist. + /// + Queue = 4, + + /// + /// A user is requesting an unpause command for the group. + /// + Unpause = 5, + /// /// A user is requesting a pause command for the group. /// - Pause = 1, + Pause = 6, + + /// + /// A user is requesting a stop command for the group. + /// + Stop = 7, /// /// A user is requesting a seek command for the group. /// - Seek = 2, + Seek = 8, - /// + /// /// A user is signaling that playback is buffering. /// - Buffer = 3, + Buffer = 9, /// /// A user is signaling that playback resumed. /// - Ready = 4, + Ready = 10, /// - /// A user is reporting its ping. + /// A user is requesting next track in playlist. /// - Ping = 5 + NextTrack = 11, + + /// + /// A user is requesting previous track in playlist. + /// + PreviousTrack = 12, + /// + /// A user is setting the repeat mode. + /// + SetRepeatMode = 13, + + /// + /// A user is setting the shuffle mode. + /// + SetShuffleMode = 14, + + /// + /// A user is reporting their ping. + /// + Ping = 15, + + /// + /// A user is requesting to be ignored on group wait. + /// + IgnoreWait = 16 } } diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/QueueItem.cs new file mode 100644 index 0000000000..dc9cfbc229 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/QueueItem.cs @@ -0,0 +1,24 @@ +#nullable disable + +using System; + +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Class QueueItem. + /// + public class QueueItem + { + /// + /// Gets or sets the item id. + /// + /// The item id. + public Guid ItemId { get; set; } + + /// + /// Gets or sets the playlist id of the item. + /// + /// The playlist id of the item. + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs index 0f0be0152d..779f711af0 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommand.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs @@ -13,6 +13,12 @@ namespace MediaBrowser.Model.SyncPlay /// The group identifier. public string GroupId { get; set; } + /// + /// Gets or sets the playlist id of the playing item. + /// + /// The playlist id of the playing item. + public string PlaylistItemId { get; set; } + /// /// Gets or sets the UTC time when to execute the command. /// diff --git a/MediaBrowser.Model/SyncPlay/SendCommandType.cs b/MediaBrowser.Model/SyncPlay/SendCommandType.cs index 86dec9e900..e6b17c60ae 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommandType.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommandType.cs @@ -6,18 +6,23 @@ namespace MediaBrowser.Model.SyncPlay public enum SendCommandType { /// - /// The play command. Instructs users to start playback. + /// The unpause command. Instructs users to unpause playback. /// - Play = 0, + Unpause = 0, /// /// The pause command. Instructs users to pause playback. /// Pause = 1, + /// + /// The stop command. Instructs users to stop playback. + /// + Stop = 2, + /// /// The seek command. Instructs users to seek to a specified time. /// - Seek = 2 + Seek = 3 } } From be4e5eff9ce6a5d93088625575dcc888d955ba69 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 16 Oct 2020 14:58:37 +0100 Subject: [PATCH 0122/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 8545fd5dcf..a6130a8e7a 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -252,20 +252,23 @@ namespace MediaBrowser.Common.Plugins } catch { - return (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); + var config = (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); + SaveConfiguration(config); + return config; } } /// /// Saves the current configuration to the file system. /// - public virtual void SaveConfiguration() + /// Configuration to save. + public virtual void SaveConfiguration(TConfigurationType config) { lock (_configurationSaveLock) { _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); - XmlSerializer.SerializeToFile(Configuration, ConfigurationFilePath); + XmlSerializer.SerializeToFile(config, ConfigurationFilePath); } } @@ -279,7 +282,7 @@ namespace MediaBrowser.Common.Plugins Configuration = (TConfigurationType)configuration; - SaveConfiguration(); + SaveConfiguration(Configuration); } /// From b2662894cf6e7e6b20d12ff22c79ee5159658a2a Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 16 Oct 2020 09:37:35 -0600 Subject: [PATCH 0123/1930] Add whitespace handling and tests --- .../JsonCommaDelimitedArrayConverter.cs | 2 +- .../Json/JsonCommaDelimitedArrayTests.cs | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index 4f6a685314..bf7048c370 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Common.Json.Converters var entries = new T[stringEntries.Length]; for (var i = 0; i < stringEntries.Length; i++) { - entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i]); + entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i].Trim()); } return entries; diff --git a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs index c543cfee9f..16f8a690e6 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs @@ -21,6 +21,19 @@ namespace Jellyfin.Common.Tests.Json Assert.Equal(desiredValue.Value, value?.Value); } + [Fact] + public static void Deserialize_String_Space_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a, b, c"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + [Fact] public static void Deserialize_GenericCommandType_Valid_Success() { @@ -35,6 +48,20 @@ namespace Jellyfin.Common.Tests.Json Assert.Equal(desiredValue.Value, value?.Value); } + [Fact] + public static void Deserialize_GenericCommandType_Space_Valid_Success() + { + var desiredValue = new GenericBodyModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + [Fact] public static void Deserialize_String_Array_Valid_Success() { From 51dd3f1e19c3ed77e2bba2aaecdd743ee627bd09 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 17 Oct 2020 16:01:36 +0200 Subject: [PATCH 0124/1930] Minor improvements --- .../AppBase/BaseApplicationPaths.cs | 2 +- Emby.Server.Implementations/ApplicationHost.cs | 14 +++++++------- .../ServerApplicationPaths.cs | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs index 2adc1d6c34..660bbb2deb 100644 --- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs +++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs @@ -62,7 +62,7 @@ namespace Emby.Server.Implementations.AppBase } /// - public string VirtualDataPath { get; } = "%AppDataPath%"; + public string VirtualDataPath => "%AppDataPath%"; /// /// Gets the image cache path. diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0c8b0339bd..4110b6f3f7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -259,8 +259,8 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); - + _jsonSerializer = new JsonSerializer(); + ServiceCollection = serviceCollection; _networkManager = networkManager; @@ -340,7 +340,7 @@ namespace Emby.Server.Implementations /// Gets the email address for use within a comment section of a user agent field. /// Presently used to provide contact information to MusicBrainz service. /// - public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org"; + public string ApplicationUserAgentAddress => "team@jellyfin.org"; /// /// Gets the current application name. @@ -404,7 +404,7 @@ namespace Emby.Server.Implementations /// /// Resolves this instance. /// - /// The type + /// The type. /// ``0. public T Resolve() => ServiceProvider.GetService(); @@ -1090,7 +1090,7 @@ namespace Emby.Server.Implementations { // No metafile, so lets see if the folder is versioned. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; - + int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver)) { @@ -1099,9 +1099,9 @@ namespace Emby.Server.Implementations } else { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. + // Un-versioned folder - Add it under the path name and version 0.0.0.1. versions.Add((new Version(0, 0, 0, 1), metafile, dir)); - } + } } } catch diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs index dfdd4200e0..ac589b03cf 100644 --- a/Emby.Server.Implementations/ServerApplicationPaths.cs +++ b/Emby.Server.Implementations/ServerApplicationPaths.cs @@ -104,6 +104,6 @@ namespace Emby.Server.Implementations public string InternalMetadataPath { get; set; } /// - public string VirtualInternalMetadataPath { get; } = "%MetadataPath%"; + public string VirtualInternalMetadataPath => "%MetadataPath%"; } } From 49569ca0a0bf5534301e4e51bc263c73cc275a73 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 17 Oct 2020 16:19:57 +0200 Subject: [PATCH 0125/1930] Use nameof where possible --- Emby.Dlna/ContentDirectory/ControlHandler.cs | 32 ++++++++--------- .../Channels/ChannelManager.cs | 2 +- .../Channels/ChannelPostScanTask.cs | 2 +- .../Data/SqliteItemRepository.cs | 34 +++++++++---------- Emby.Server.Implementations/Dto/DtoService.cs | 2 +- .../Images/ArtistImageProvider.cs | 2 +- .../Images/GenreImageProvider.cs | 9 +++-- .../Library/MusicManager.cs | 4 +-- .../Library/SearchEngine.cs | 28 +++++++-------- .../Library/Validators/ArtistsValidator.cs | 2 +- .../Library/Validators/PeopleValidator.cs | 2 +- .../Library/Validators/StudiosValidator.cs | 2 +- .../LiveTv/EmbyTV/EmbyTV.cs | 14 ++++---- .../LiveTv/LiveTvDtoService.cs | 8 ++--- .../LiveTv/LiveTvManager.cs | 22 ++++++------ .../ScheduledTasks/ScheduledTaskWorker.cs | 8 ++--- .../TV/TVSeriesManager.cs | 4 +-- Jellyfin.Api/Controllers/MoviesController.cs | 4 +-- .../Entities/Audio/MusicArtist.cs | 2 +- .../Entities/Audio/MusicGenre.cs | 2 +- MediaBrowser.Controller/Entities/Folder.cs | 4 +-- MediaBrowser.Controller/Entities/Genre.cs | 8 ++++- MediaBrowser.Controller/Entities/TV/Series.cs | 10 +++--- .../Entities/UserViewBuilder.cs | 30 ++++++++-------- MediaBrowser.Controller/Playlists/Playlist.cs | 4 +-- .../TheTvdb/TvdbPersonImageProvider.cs | 2 +- 26 files changed, 127 insertions(+), 116 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 4b108b89ea..b805cd45c1 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -487,7 +487,7 @@ namespace Emby.Dlna.ContentDirectory User = user, Recursive = true, IsMissing = false, - ExcludeItemTypes = new[] { typeof(Book).Name }, + ExcludeItemTypes = new[] { nameof(Book) }, IsFolder = isFolder, MediaTypes = mediaTypes, DtoOptions = GetDtoOptions() @@ -556,7 +556,7 @@ namespace Emby.Dlna.ContentDirectory Limit = limit, StartIndex = startIndex, IsVirtualItem = false, - ExcludeItemTypes = new[] { typeof(Book).Name }, + ExcludeItemTypes = new[] { nameof(Book) }, IsPlaceHolder = false, DtoOptions = GetDtoOptions() }; @@ -575,7 +575,7 @@ namespace Emby.Dlna.ContentDirectory StartIndex = startIndex, Limit = limit, }; - query.IncludeItemTypes = new[] { typeof(LiveTvChannel).Name }; + query.IncludeItemTypes = new[] { nameof(LiveTvChannel) }; SetSorting(query, sort, false); @@ -910,7 +910,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); - query.IncludeItemTypes = new[] { typeof(Series).Name }; + query.IncludeItemTypes = new[] { nameof(Series) }; var result = _libraryManager.GetItemsResult(query); @@ -923,7 +923,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); - query.IncludeItemTypes = new[] { typeof(Movie).Name }; + query.IncludeItemTypes = new[] { nameof(Movie) }; var result = _libraryManager.GetItemsResult(query); @@ -936,7 +936,7 @@ namespace Emby.Dlna.ContentDirectory // query.Parent = parent; query.SetUser(user); - query.IncludeItemTypes = new[] { typeof(BoxSet).Name }; + query.IncludeItemTypes = new[] { nameof(BoxSet) }; var result = _libraryManager.GetItemsResult(query); @@ -949,7 +949,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); - query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name }; + query.IncludeItemTypes = new[] { nameof(MusicAlbum) }; var result = _libraryManager.GetItemsResult(query); @@ -962,7 +962,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); - query.IncludeItemTypes = new[] { typeof(Audio).Name }; + query.IncludeItemTypes = new[] { nameof(Audio) }; var result = _libraryManager.GetItemsResult(query); @@ -975,7 +975,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); query.IsFavorite = true; - query.IncludeItemTypes = new[] { typeof(Audio).Name }; + query.IncludeItemTypes = new[] { nameof(Audio) }; var result = _libraryManager.GetItemsResult(query); @@ -988,7 +988,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); query.IsFavorite = true; - query.IncludeItemTypes = new[] { typeof(Series).Name }; + query.IncludeItemTypes = new[] { }; var result = _libraryManager.GetItemsResult(query); @@ -1001,7 +1001,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); query.IsFavorite = true; - query.IncludeItemTypes = new[] { typeof(Episode).Name }; + query.IncludeItemTypes = new[] { }; var result = _libraryManager.GetItemsResult(query); @@ -1014,7 +1014,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); query.IsFavorite = true; - query.IncludeItemTypes = new[] { typeof(Movie).Name }; + query.IncludeItemTypes = new[] { }; var result = _libraryManager.GetItemsResult(query); @@ -1027,7 +1027,7 @@ namespace Emby.Dlna.ContentDirectory query.Parent = parent; query.SetUser(user); query.IsFavorite = true; - query.IncludeItemTypes = new[] { typeof(MusicAlbum).Name }; + query.IncludeItemTypes = new[] { }; var result = _libraryManager.GetItemsResult(query); @@ -1181,7 +1181,7 @@ namespace Emby.Dlna.ContentDirectory { UserId = user.Id, Limit = 50, - IncludeItemTypes = new[] { typeof(Episode).Name }, + IncludeItemTypes = new[] { }, ParentId = parent == null ? Guid.Empty : parent.Id, GroupItems = false }, @@ -1215,7 +1215,7 @@ namespace Emby.Dlna.ContentDirectory Recursive = true, ParentId = parentId, ArtistIds = new[] { item.Id }, - IncludeItemTypes = new[] { typeof(MusicAlbum).Name }, + IncludeItemTypes = new[] { }, Limit = limit, StartIndex = startIndex, DtoOptions = GetDtoOptions() @@ -1259,7 +1259,7 @@ namespace Emby.Dlna.ContentDirectory Recursive = true, ParentId = parentId, GenreIds = new[] { item.Id }, - IncludeItemTypes = new[] { typeof(MusicAlbum).Name }, + IncludeItemTypes = new[] { }, Limit = limit, StartIndex = startIndex, DtoOptions = GetDtoOptions() diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index fb1bb65a09..db44bf4898 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -543,7 +543,7 @@ namespace Emby.Server.Implementations.Channels return _libraryManager.GetItemIds( new InternalItemsQuery { - IncludeItemTypes = new[] { typeof(Channel).Name }, + IncludeItemTypes = new[] { nameof(Channel) }, OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) } }).Select(i => GetChannelFeatures(i.ToString("N", CultureInfo.InvariantCulture))).ToArray(); } diff --git a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs index eeb49b8fef..2391eed428 100644 --- a/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/Emby.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.Channels var uninstalledChannels = _libraryManager.GetItemList(new InternalItemsQuery { - IncludeItemTypes = new[] { typeof(Channel).Name }, + IncludeItemTypes = new[] { nameof(Channel) }, ExcludeItemIds = installedChannelIds.ToArray() }); diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index d09f84e174..56f0329353 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -3908,7 +3908,7 @@ namespace Emby.Server.Implementations.Data if (query.IsPlayed.HasValue) { // We should probably figure this out for all folders, but for right now, this is the only place where we need it - if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(Series).Name, StringComparison.OrdinalIgnoreCase)) + if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], nameof(Series), StringComparison.OrdinalIgnoreCase)) { if (query.IsPlayed.Value) { @@ -4749,29 +4749,29 @@ namespace Emby.Server.Implementations.Data { var list = new List(); - if (IsTypeInQuery(typeof(Person).Name, query)) + if (IsTypeInQuery(nameof(Person), query)) { - list.Add(typeof(Person).Name); + list.Add(nameof(Person)); } - if (IsTypeInQuery(typeof(Genre).Name, query)) + if (IsTypeInQuery(nameof(Genre), query)) { - list.Add(typeof(Genre).Name); + list.Add(nameof(Genre)); } - if (IsTypeInQuery(typeof(MusicGenre).Name, query)) + if (IsTypeInQuery(nameof(MusicGenre), query)) { - list.Add(typeof(MusicGenre).Name); + list.Add(nameof(MusicGenre)); } - if (IsTypeInQuery(typeof(MusicArtist).Name, query)) + if (IsTypeInQuery(nameof(MusicArtist), query)) { - list.Add(typeof(MusicArtist).Name); + list.Add(nameof(MusicArtist)); } - if (IsTypeInQuery(typeof(Studio).Name, query)) + if (IsTypeInQuery(nameof(Studio), query)) { - list.Add(typeof(Studio).Name); + list.Add(nameof(Studio)); } return list; @@ -4826,12 +4826,12 @@ namespace Emby.Server.Implementations.Data var types = new[] { - typeof(Episode).Name, - typeof(Video).Name, - typeof(Movie).Name, - typeof(MusicVideo).Name, - typeof(Series).Name, - typeof(Season).Name + nameof(Episode), + nameof(Video), + nameof(Movie), + nameof(MusicVideo), + nameof(Series), + nameof(Season) }; if (types.Any(i => query.IncludeItemTypes.Contains(i, StringComparer.OrdinalIgnoreCase))) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index edb8753fd4..73502c2c9f 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -465,7 +465,7 @@ namespace Emby.Server.Implementations.Dto { var parentAlbumIds = _libraryManager.GetItemIds(new InternalItemsQuery { - IncludeItemTypes = new[] { typeof(MusicAlbum).Name }, + IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = item.Album, Limit = 1 }); diff --git a/Emby.Server.Implementations/Images/ArtistImageProvider.cs b/Emby.Server.Implementations/Images/ArtistImageProvider.cs index bf57382ed4..afa4ec7b1b 100644 --- a/Emby.Server.Implementations/Images/ArtistImageProvider.cs +++ b/Emby.Server.Implementations/Images/ArtistImageProvider.cs @@ -42,7 +42,7 @@ namespace Emby.Server.Implementations.Images // return _libraryManager.GetItemList(new InternalItemsQuery // { // ArtistIds = new[] { item.Id }, - // IncludeItemTypes = new[] { typeof(MusicAlbum).Name }, + // IncludeItemTypes = new[] { nameof(MusicAlbum) }, // OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) }, // Limit = 4, // Recursive = true, diff --git a/Emby.Server.Implementations/Images/GenreImageProvider.cs b/Emby.Server.Implementations/Images/GenreImageProvider.cs index 1cd4cd66bd..3817882312 100644 --- a/Emby.Server.Implementations/Images/GenreImageProvider.cs +++ b/Emby.Server.Implementations/Images/GenreImageProvider.cs @@ -42,7 +42,12 @@ namespace Emby.Server.Implementations.Images return _libraryManager.GetItemList(new InternalItemsQuery { Genres = new[] { item.Name }, - IncludeItemTypes = new[] { typeof(MusicAlbum).Name, typeof(MusicVideo).Name, typeof(Audio).Name }, + IncludeItemTypes = new[] + { + nameof(MusicAlbum), + nameof(MusicVideo), + nameof(Audio) + }, OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) }, Limit = 4, Recursive = true, @@ -77,7 +82,7 @@ namespace Emby.Server.Implementations.Images return _libraryManager.GetItemList(new InternalItemsQuery { Genres = new[] { item.Name }, - IncludeItemTypes = new[] { typeof(Series).Name, typeof(Movie).Name }, + IncludeItemTypes = new[] { nameof(Series), nameof(Movie) }, OrderBy = new[] { (ItemSortBy.Random, SortOrder.Ascending) }, Limit = 4, Recursive = true, diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs index 877fdec86e..658c53f288 100644 --- a/Emby.Server.Implementations/Library/MusicManager.cs +++ b/Emby.Server.Implementations/Library/MusicManager.cs @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Library var genres = item .GetRecursiveChildren(user, new InternalItemsQuery(user) { - IncludeItemTypes = new[] { typeof(Audio).Name }, + IncludeItemTypes = new[] { nameof(Audio) }, DtoOptions = dtoOptions }) .Cast public IdleGroupState(ILogger logger) : base(logger) { - // Do nothing + // Do nothing. } /// @@ -36,13 +36,13 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Do nothing + // Do nothing. } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -51,7 +51,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -90,7 +90,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -99,7 +99,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs index 39c0511d9f..f674ec7778 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs @@ -19,7 +19,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public PausedGroupState(ILogger logger) : base(logger) { - // Do nothing + // Do nothing. } /// @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Wait for session to be ready + // Wait for session to be ready. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); @@ -40,13 +40,13 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Do nothing + // Do nothing. } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var playingState = new PlayingGroupState(_logger); context.SetState(playingState); playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -66,23 +66,23 @@ namespace MediaBrowser.Controller.SyncPlay { if (!prevState.Equals(GetGroupState())) { - // Pause group and compute the media playback position + // Pause group and compute the media playback position. var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; - // Seek only if playback actually started - // Pause request may be issued during the delay added to account for latency + // Seek only if playback actually started. + // Pause request may be issued during the delay added to account for latency. context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } else { - // Client got lost, sending current state + // Client got lost, sending current state. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var idleState = new IdleGroupState(_logger); context.SetState(idleState); idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -100,7 +100,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -109,7 +109,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -120,17 +120,17 @@ namespace MediaBrowser.Controller.SyncPlay { if (prevState.Equals(GetGroupState())) { - // Client got lost, sending current state + // Client got lost, sending current state. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } else if (prevState.Equals(GroupState.Waiting)) { - // Sending current state to all clients + // Sending current state to all clients. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } } @@ -138,7 +138,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -147,7 +147,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs index e2909ff91c..a3b0baf963 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public PlayingGroupState(ILogger logger) : base(logger) { - // Do nothing + // Do nothing. } /// @@ -36,7 +36,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Wait for session to be ready + // Wait for session to be ready. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); @@ -45,13 +45,13 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Do nothing + // Do nothing. } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -62,13 +62,13 @@ namespace MediaBrowser.Controller.SyncPlay { if (!prevState.Equals(GetGroupState())) { - // Pick a suitable time that accounts for latency + // Pick a suitable time that accounts for latency. var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing); - // Unpause group and set starting point in future - // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position) - // The added delay does not guarantee, of course, that the command will be received in time - // Playback synchronization will mainly happen client side + // Unpause group and set starting point in future. + // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position). + // The added delay does not guarantee, of course, that the command will be received in time. + // Playback synchronization will mainly happen client side. context.LastActivity = DateTime.UtcNow.AddMilliseconds( delayMillis ); @@ -76,12 +76,12 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } else { - // Client got lost, sending current state + // Client got lost, sending current state. var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } @@ -90,7 +90,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var pausedState = new PausedGroupState(_logger); context.SetState(pausedState); pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -99,7 +99,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var idleState = new IdleGroupState(_logger); context.SetState(idleState); idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -108,7 +108,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -122,7 +122,7 @@ namespace MediaBrowser.Controller.SyncPlay return; } - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -133,13 +133,13 @@ namespace MediaBrowser.Controller.SyncPlay { if (prevState.Equals(GetGroupState())) { - // Group was not waiting, make sure client has latest state + // Group was not waiting, make sure client has latest state. var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } else if (prevState.Equals(GroupState.Waiting)) { - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } } @@ -147,7 +147,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -156,7 +156,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Change state + // Change state. var waitingState = new WaitingGroupState(_logger); context.SetState(waitingState); waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs index 9d839b268b..acf0161b4e 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs @@ -34,7 +34,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public WaitingGroupState(ILogger logger) : base(logger) { - // Do nothing + // Do nothing. } /// @@ -46,7 +46,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -55,23 +55,23 @@ namespace MediaBrowser.Controller.SyncPlay if (prevState.Equals(GroupState.Playing)) { ResumePlaying = true; - // Pause group and compute the media playback position + // Pause group and compute the media playback position. var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; - // Seek only if playback actually started - // Event may happen during the delay added to account for latency + // Seek only if playback actually started. + // Event may happen during the delay added to account for latency. context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; } - // Prepare new session + // Prepare new session. var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NewPlaylist); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, update, cancellationToken); context.SetBuffering(session, true); - // Send pause command to all non-buffering sessions + // Send pause command to all non-buffering sessions. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); } @@ -79,7 +79,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -92,7 +92,7 @@ namespace MediaBrowser.Controller.SyncPlay { if (ResumePlaying) { - // Client, that was buffering, left the group + // Client, that was buffering, left the group. var playingState = new PlayingGroupState(_logger); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); @@ -102,7 +102,7 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Group is ready, returning to previous state + // Group is ready, returning to previous state. var pausedState = new PausedGroupState(_logger); context.SetState(pausedState); @@ -114,7 +114,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -128,7 +128,7 @@ namespace MediaBrowser.Controller.SyncPlay { _logger.LogError("HandleRequest: {0} in group {1}, unable to set playing queue.", request.GetRequestType(), context.GroupId.ToString()); - // Ignore request and return to previous state + // Ignore request and return to previous state. ISyncPlayState newState; switch (prevState) { @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); _logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); @@ -160,7 +160,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -176,12 +176,12 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); } else { - // Return to old state + // Return to old state. ISyncPlayState newState; switch (prevState) { @@ -205,7 +205,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -221,7 +221,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); _logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.GetRequestType(), context.GroupId.ToString()); @@ -232,10 +232,10 @@ namespace MediaBrowser.Controller.SyncPlay { _logger.LogDebug("HandleRequest: {0} in group {1}, ignoring sessions that are not ready and forcing the playback to start.", request.GetRequestType(), context.GroupId.ToString()); - // An Unpause request is forcing the playback to start, ignoring sessions that are not ready + // An Unpause request is forcing the playback to start, ignoring sessions that are not ready. context.SetAllBuffering(false); - // Change state + // Change state. var playingState = new PlayingGroupState(_logger); playingState.IgnoreBuffering = true; context.SetState(playingState); @@ -243,10 +243,10 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Group would have gone to paused state, now will go to playing state when ready + // Group would have gone to paused state, now will go to playing state when ready. ResumePlaying = true; - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } } @@ -255,31 +255,31 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; InitialStateSet = true; } - // Wait for sessions to be ready, then switch to paused state + // Wait for sessions to be ready, then switch to paused state. ResumePlaying = false; - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; InitialStateSet = true; } - // Change state + // Change state. var idleState = new IdleGroupState(_logger); context.SetState(idleState); idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -288,7 +288,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -304,34 +304,34 @@ namespace MediaBrowser.Controller.SyncPlay ResumePlaying = false; } - // Sanitize PositionTicks + // Sanitize PositionTicks. var ticks = context.SanitizePositionTicks(request.PositionTicks); - // Seek + // Seek. context.PositionTicks = ticks; context.LastActivity = DateTime.UtcNow; var command = context.NewSyncPlayCommand(SendCommandType.Seek); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; InitialStateSet = true; } - // Make sure the client is playing the correct item + // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); @@ -346,60 +346,60 @@ namespace MediaBrowser.Controller.SyncPlay if (prevState.Equals(GroupState.Playing)) { - // Resume playback when all ready + // Resume playback when all ready. ResumePlaying = true; context.SetBuffering(session, true); - // Pause group and compute the media playback position + // Pause group and compute the media playback position. var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; - // Send pause command to all non-buffering sessions + // Send pause command to all non-buffering sessions. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); } else if (prevState.Equals(GroupState.Paused)) { - // Don't resume playback when all ready + // Don't resume playback when all ready. ResumePlaying = false; context.SetBuffering(session, true); - // Send pause command to buffering session + // Send pause command to buffering session. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } else if (prevState.Equals(GroupState.Waiting)) { - // Another session is now buffering + // Another session is now buffering. context.SetBuffering(session, true); if (!ResumePlaying) { - // Force update for this session that should be paused + // Force update for this session that should be paused. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } } - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); } /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; InitialStateSet = true; } - // Make sure the client is playing the correct item + // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); @@ -432,28 +432,28 @@ namespace MediaBrowser.Controller.SyncPlay if (ResumePlaying) { // Handle case where session reported as ready but in reality - // it has no clue of the real position nor the playback state + // it has no clue of the real position nor the playback state. if (!request.IsPlaying && Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) { - // Session not ready at all + // Session not ready at all. context.SetBuffering(session, true); - // Correcting session's position + // Correcting session's position. var command = context.NewSyncPlayCommand(SendCommandType.Seek); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); _logger.LogDebug("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); return; } - // Session is ready + // Session is ready. context.SetBuffering(session, false); if (context.IsBuffering()) { - // Others are still buffering, tell this client to pause when ready + // Others are still buffering, tell this client to pause when ready. var command = context.NewSyncPlayCommand(SendCommandType.Pause); var pauseAtTime = currentTime.AddTicks(delayTicks); command.When = context.DateToUTCString(pauseAtTime); @@ -463,11 +463,11 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // If all ready, then start playback - // Let other clients resume as soon as the buffering client catches up + // If all ready, then start playback. + // Let other clients resume as soon as the buffering client catches up. if (delayTicks > context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond) { - // Client that was buffering is recovering, notifying others to resume + // Client that was buffering is recovering, notifying others to resume. context.LastActivity = currentTime.AddTicks(delayTicks); var command = context.NewSyncPlayCommand(SendCommandType.Unpause); var filter = SyncPlayBroadcastType.AllExceptCurrentSession; @@ -482,7 +482,7 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Client, that was buffering, resumed playback but did not update others in time + // Client, that was buffering, resumed playback but did not update others in time. delayTicks = context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond; delayTicks = delayTicks < context.DefaultPing ? context.DefaultPing : delayTicks; @@ -494,7 +494,7 @@ namespace MediaBrowser.Controller.SyncPlay _logger.LogDebug("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); } - // Change state + // Change state. var playingState = new PlayingGroupState(_logger); context.SetState(playingState); playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); @@ -502,35 +502,35 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Check that session is really ready, tollerate half second difference to account for player imperfections + // Check that session is really ready, tollerate half second difference to account for player imperfections. if (Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) { - // Session still not ready + // Session still not ready. context.SetBuffering(session, true); - // Session is seeking to wrong position, correcting + // Session is seeking to wrong position, correcting. var command = context.NewSyncPlayCommand(SendCommandType.Seek); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - // Notify relevant state change event + // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); _logger.LogDebug("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); return; } else { - // Session is ready + // Session is ready. context.SetBuffering(session, false); } if (!context.IsBuffering()) { - // Group is ready, returning to previous state + // Group is ready, returning to previous state. var pausedState = new PausedGroupState(_logger); context.SetState(pausedState); if (InitialState.Equals(GroupState.Playing)) { - // Group went from playing to waiting state and a pause request occured while waiting + // Group went from playing to waiting state and a pause request occured while waiting. var pauserequest = new PauseGroupRequest(); pausedState.HandleRequest(context, GetGroupState(), pauserequest, session, cancellationToken); } @@ -547,7 +547,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -556,7 +556,7 @@ namespace MediaBrowser.Controller.SyncPlay ResumePlaying = true; - // Make sure the client knows the playing item, to avoid duplicate requests + // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); @@ -566,17 +566,17 @@ namespace MediaBrowser.Controller.SyncPlay var newItem = context.NextItemInQueue(); if (newItem) { - // Send playing-queue update + // Send playing-queue update. var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextTrack); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); } else { - // Return to old state + // Return to old state. ISyncPlayState newState; switch (prevState) { @@ -600,7 +600,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - // Save state if first event + // Save state if first event. if (!InitialStateSet) { InitialState = prevState; @@ -609,7 +609,7 @@ namespace MediaBrowser.Controller.SyncPlay ResumePlaying = true; - // Make sure the client knows the playing item, to avoid duplicate requests + // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); @@ -619,17 +619,17 @@ namespace MediaBrowser.Controller.SyncPlay var newItem = context.PreviousItemInQueue(); if (newItem) { - // Send playing-queue update + // Send playing-queue update. var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousTrack); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command + // Reset status of sessions and await for all Ready events before sending Play command. context.SetAllBuffering(true); } else { - // Return to old state + // Return to old state. ISyncPlayState newState; switch (prevState) { diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index a8e30a9eca..6e3b492498 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // TODO: probably remove this event, not used at the moment + // TODO: probably remove this event, not used at the moment. } private void OnSessionManagerPlaybackStart(object sender, PlaybackProgressEventArgs e) @@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // TODO: probably remove this event, not used at the moment + // TODO: probably remove this event, not used at the moment. } private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e) @@ -157,7 +157,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // TODO: probably remove this event, not used at the moment + // TODO: probably remove this event, not used at the moment. } private bool IsSessionInGroup(SessionInfo session) @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations.SyncPlay /// public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken) { - // TODO: determine what happens to users that are in a group and get their permissions revoked + // TODO: determine what happens to users that are in a group and get their permissions revoked. lock (_groupsLock) { _sessionToGroupMap.TryGetValue(session.Id, out var group); diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 9bef3f5593..ae2b0fa50a 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// The session. /// The group. - /// + /// Thrown when the user is in another group already. void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group); /// @@ -63,7 +63,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// The session. /// The group. - /// + /// Thrown when the user is not found in the specified group. void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group); } } diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 701982cc00..6b4f9401e2 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -261,9 +261,9 @@ namespace MediaBrowser.Controller.SyncPlay if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { - // Append items to sorted playlist as they are + // Append items to sorted playlist as they are. SortedPlaylist.AddRange(newItems); - // Shuffle items before adding to shuffled playlist + // Shuffle items before adding to shuffled playlist. newItems.Shuffle(); ShuffledPlaylist.InsertRange(PlayingItemIndex + 1, newItems); } @@ -387,11 +387,11 @@ namespace MediaBrowser.Controller.SyncPlay { if (playlistItemIds.Contains(playingItem.PlaylistItemId)) { - // Playing item has been removed, picking previous item + // Playing item has been removed, picking previous item. PlayingItemIndex--; if (PlayingItemIndex < 0) { - // Was first element, picking next if available + // Was first element, picking next if available. PlayingItemIndex = SortedPlaylist.Count() > 0 ? 0 : -1; } @@ -399,7 +399,7 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Restoring playing item + // Restoring playing item. SetPlayingItemByPlaylistId(playingItem.PlaylistItemId); return false; } From 36fee4e60a033d8d785e62788aaf00999d497c58 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca Date: Wed, 21 Oct 2020 16:42:57 +0200 Subject: [PATCH 0130/1930] Minor fixes --- .../SyncPlay/GroupController.cs | 6 ++--- .../SyncPlay/GroupStates/PausedGroupState.cs | 2 +- .../SyncPlay/GroupStates/WaitingGroupState.cs | 20 +++++++------- .../SyncPlay/ISyncPlayController.cs | 2 +- .../SyncPlay/ISyncPlayManager.cs | 2 +- .../SyncPlay/ISyncPlayState.cs | 4 +-- .../SyncPlay/ISyncPlayStateContext.cs | 18 ++++++------- .../PlaybackRequest/BufferGroupRequest.cs | 6 ++--- .../MovePlaylistItemGroupRequest.cs | 6 ++--- .../PlaybackRequest/NextTrackGroupRequest.cs | 4 +-- .../PlaybackRequest/PingGroupRequest.cs | 2 +- .../PreviousTrackGroupRequest.cs | 4 +-- .../PlaybackRequest/ReadyGroupRequest.cs | 6 ++--- .../RemoveFromPlaylistGroupRequest.cs | 6 ++--- .../SetCurrentItemGroupRequest.cs | 4 +-- .../SyncPlay/Queue/PlayQueueManager.cs | 26 +++++++++---------- .../SyncPlay/GroupUpdateType.cs | 2 +- .../SyncPlay/JoinGroupRequest.cs | 4 +-- MediaBrowser.Model/SyncPlay/QueueItem.cs | 8 +++--- MediaBrowser.Model/SyncPlay/SendCommand.cs | 4 +-- 20 files changed, 68 insertions(+), 68 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index ff1340e46b..26972de8aa 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.SyncPlay /// /// Checks if a session is in this group. /// - /// The session id to check. + /// The session identifier to check. /// true if the session is in this group; false otherwise. private bool ContainsSession(string sessionId) { @@ -509,7 +509,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } - // Check is participants can access the new playing queue. + // Check if participants can access the new playing queue. if (!AllUsersHaveAccessToQueue(playQueue)) { return false; @@ -583,7 +583,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } - // Check is participants can access the new playing queue. + // Check if participants can access the new playing queue. if (!AllUsersHaveAccessToQueue(newItems)) { return false; diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs index f674ec7778..8c4bd20b1c 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs @@ -72,7 +72,7 @@ namespace MediaBrowser.Controller.SyncPlay context.LastActivity = currentTime; // Seek only if playback actually started. // Pause request may be issued during the delay added to account for latency. - context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs index acf0161b4e..ff1d379d77 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs @@ -61,7 +61,7 @@ namespace MediaBrowser.Controller.SyncPlay context.LastActivity = currentTime; // Seek only if playback actually started. // Event may happen during the delay added to account for latency. - context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); } // Prepare new session. @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); _logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); @@ -176,7 +176,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); } else @@ -221,7 +221,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); _logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.GetRequestType(), context.GroupId.ToString()); @@ -314,7 +314,7 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Seek); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); // Notify relevant state change event. @@ -355,7 +355,7 @@ namespace MediaBrowser.Controller.SyncPlay var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; - context.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); // Send pause command to all non-buffering sessions. var command = context.NewSyncPlayCommand(SendCommandType.Pause); @@ -559,7 +559,7 @@ namespace MediaBrowser.Controller.SyncPlay // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { - _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); + _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.GetRequestType(), context.GroupId.ToString()); return; } @@ -571,7 +571,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); } else @@ -612,7 +612,7 @@ namespace MediaBrowser.Controller.SyncPlay // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { - _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist id.", request.GetRequestType(), context.GroupId.ToString()); + _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.GetRequestType(), context.GroupId.ToString()); return; } @@ -624,7 +624,7 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - // Reset status of sessions and await for all Ready events before sending Play command. + // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); } else diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs index 9a4e1ee1ee..2f497ebbb9 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Checks if the group is empty. /// - /// If the group is empty. + /// true if the group is empty, false otherwise bool IsGroupEmpty(); /// diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index ae2b0fa50a..ec13686c64 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -23,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay /// Adds the session to a group. /// /// The session. - /// The group id. + /// The group identifier. /// The request. /// The cancellation token. void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken); diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs index 290576e30f..218e871e36 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Controller.SyncPlay GroupState GetGroupState(); /// - /// Handle a session that joined the group. + /// Handles a session that joined the group. /// /// The context of the state. /// The previous state. @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); /// - /// Handle a session that is leaving the group. + /// Handles a session that is leaving the group. /// /// The context of the state. /// The previous state. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs index 18a6857491..13d38a02bb 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs @@ -71,7 +71,7 @@ namespace MediaBrowser.Controller.SyncPlay /// Builds a new playback command with some default values. /// /// The command type. - /// The SendCommand. + /// The command. SendCommand NewSyncPlayCommand(SendCommandType type); /// @@ -79,7 +79,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// The update type. /// The data to send. - /// The GroupUpdate. + /// The group update. GroupUpdate NewSyncPlayGroupUpdate(GroupUpdateType type, T data); /// @@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.SyncPlay /// Sanitizes the PositionTicks, considers the current playing item when available. /// /// The PositionTicks. - /// The sanitized PositionTicks. + /// The sanitized position ticks. long SanitizePositionTicks(long? positionTicks); /// @@ -141,14 +141,14 @@ namespace MediaBrowser.Controller.SyncPlay /// The new play queue. /// The playing item position in the play queue. /// The start position ticks. - /// true if the play queue has been changed; false is something went wrong. + /// true if the play queue has been changed; false if something went wrong. bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks); /// /// Sets the playing item. /// - /// The new playing item id. - /// true if the play queue has been changed; false is something went wrong. + /// The new playing item identifier. + /// true if the play queue has been changed; false if something went wrong. bool SetPlayingItem(string playlistItemId); /// @@ -161,9 +161,9 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Moves an item in the play queue. /// - /// The playlist id of the item to move. + /// The playlist identifier of the item to move. /// The new position. - /// true if item has been moved; false is something went wrong. + /// true if item has been moved; false if something went wrong. bool MoveItemInPlayQueue(string playlistItemId, int newIndex); /// @@ -171,7 +171,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// The new items to add to the play queue. /// The mode with which the items will be added. - /// true if the play queue has been changed; false is something went wrong. + /// true if the play queue has been changed; false if something went wrong. bool AddToPlayQueue(Guid[] newItems, string mode); /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs index 0815dd79b2..65fced43f1 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.SyncPlay { /// - /// Class BufferingGroupRequest. + /// Class BufferGroupRequest. /// public class BufferGroupRequest : IPlaybackGroupRequest { @@ -29,9 +29,9 @@ namespace MediaBrowser.Controller.SyncPlay public bool IsPlaying { get; set; } /// - /// Gets or sets the playlist item id of the playing item. + /// Gets or sets the playlist item identifier of the playing item. /// - /// The playlist item id. + /// The playlist item identifier. public string PlaylistItemId { get; set; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs index 7a293c02fd..38170facf0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs @@ -10,9 +10,9 @@ namespace MediaBrowser.Controller.SyncPlay public class MovePlaylistItemGroupRequest : IPlaybackGroupRequest { /// - /// Gets or sets the playlist id of the item. + /// Gets or sets the playlist identifier of the item. /// - /// The playlist id of the item. + /// The playlist identifier of the item. public string PlaylistItemId { get; set; } /// @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.SyncPlay /// public PlaybackRequestType GetRequestType() { - return PlaybackRequestType.Queue; + return PlaybackRequestType.MovePlaylistItem; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs index d19df2c6a0..b27c10f169 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs @@ -10,9 +10,9 @@ namespace MediaBrowser.Controller.SyncPlay public class NextTrackGroupRequest : IPlaybackGroupRequest { /// - /// Gets or sets the playing item id. + /// Gets or sets the playing item identifier. /// - /// The playing item id. + /// The playing item identifier. public string PlaylistItemId { get; set; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs index 631bf245b1..5605578d75 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs @@ -5,7 +5,7 @@ using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.SyncPlay { /// - /// Class UpdatePingGroupRequest. + /// Class PingGroupRequest. /// public class PingGroupRequest : IPlaybackGroupRequest { diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs index 663011b429..31b93b9675 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs @@ -10,9 +10,9 @@ namespace MediaBrowser.Controller.SyncPlay public class PreviousTrackGroupRequest : IPlaybackGroupRequest { /// - /// Gets or sets the playing item id. + /// Gets or sets the playing item identifier. /// - /// The playing item id. + /// The playing item identifier. public string PlaylistItemId { get; set; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs index 16bc67c617..8f266ed32e 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.SyncPlay { /// - /// Class BufferingDoneGroupRequest. + /// Class ReadyGroupRequest. /// public class ReadyGroupRequest : IPlaybackGroupRequest { @@ -29,9 +29,9 @@ namespace MediaBrowser.Controller.SyncPlay public bool IsPlaying { get; set; } /// - /// Gets or sets the playlist item id of the playing item. + /// Gets or sets the playlist item identifier of the playing item. /// - /// The playlist item id. + /// The playlist item identifier. public string PlaylistItemId { get; set; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs index 3fc77f6771..78aeb9c6f0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs @@ -10,15 +10,15 @@ namespace MediaBrowser.Controller.SyncPlay public class RemoveFromPlaylistGroupRequest : IPlaybackGroupRequest { /// - /// Gets or sets the playlist ids ot the items. + /// Gets or sets the playlist identifiers ot the items. /// - /// The playlist ids ot the items. + /// The playlist identifiers ot the items. public string[] PlaylistItemIds { get; set; } /// public PlaybackRequestType GetRequestType() { - return PlaybackRequestType.Queue; + return PlaybackRequestType.RemoveFromPlaylist; } /// diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs index d70559899a..070fd71d25 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs @@ -10,9 +10,9 @@ namespace MediaBrowser.Controller.SyncPlay public class SetPlaylistItemGroupRequest : IPlaybackGroupRequest { /// - /// Gets or sets the playlist id of the playing item. + /// Gets or sets the playlist identifier of the playing item. /// - /// The playlist id of the playing item. + /// The playlist identifier of the playing item. public string PlaylistItemId { get; set; } /// diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 6b4f9401e2..aca50f80a7 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -64,9 +64,9 @@ namespace MediaBrowser.Controller.SyncPlay public GroupRepeatMode RepeatMode { get; private set; } = GroupRepeatMode.RepeatNone; /// - /// Gets or sets the progressive id counter. + /// Gets or sets the progressive identifier counter. /// - /// The progressive id. + /// The progressive identifier. private int ProgressiveId { get; set; } = 0; private bool _disposed = false; @@ -101,15 +101,15 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Gets the next available id. + /// Gets the next available identifier. /// - /// The next available id. + /// The next available identifier. private int GetNextProgressiveId() { return ProgressiveId++; } /// - /// Creates a list from the array of items. Each item is given an unique playlist id. + /// Creates a list from the array of items. Each item is given an unique playlist identifier. /// /// The list of queue items. private List CreateQueueItemsFromArray(Guid[] items) @@ -276,9 +276,9 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Gets playlist id of the playing item, if any. + /// Gets playlist identifier of the playing item, if any. /// - /// The playlist id of the playing item. + /// The playlist identifier of the playing item. public string GetPlayingItemPlaylistId() { if (PlayingItemIndex < 0) @@ -299,9 +299,9 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Gets the playing item id, if any. + /// Gets the playing item identifier, if any. /// - /// The playing item id. + /// The playing item identifier. public Guid GetPlayingItemId() { if (PlayingItemIndex < 0) @@ -322,9 +322,9 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Sets the playing item using its id. If not in the playlist, the playing item is reset. + /// Sets the playing item using its identifier. If not in the playlist, the playing item is reset. /// - /// The new playing item id. + /// The new playing item identifier. public void SetPlayingItemById(Guid itemId) { var itemIds = GetPlaylistAsList().Select(queueItem => queueItem.ItemId).ToList(); @@ -333,9 +333,9 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Sets the playing item using its playlist id. If not in the playlist, the playing item is reset. + /// Sets the playing item using its playlist identifier. If not in the playlist, the playing item is reset. /// - /// The new playing item id. + /// The new playing item identifier. /// true if playing item has been set; false if item is not in the playlist. public bool SetPlayingItemByPlaylistId(string playlistItemId) { diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs index 7423bff117..907d1defe0 100644 --- a/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs +++ b/MediaBrowser.Model/SyncPlay/GroupUpdateType.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Model.SyncPlay StateUpdate, /// - /// The play-queue update. Tells a user what's the playing queue of the group. + /// The play-queue update. Tells a user the playing queue of the group. /// PlayQueue, diff --git a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs index 04f3a73b17..27a29b8998 100644 --- a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs +++ b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs @@ -8,9 +8,9 @@ namespace MediaBrowser.Model.SyncPlay public class JoinGroupRequest { /// - /// Gets or sets the group id. + /// Gets or sets the group identifier. /// - /// The id of the group to join. + /// The identifier of the group to join. public Guid GroupId { get; set; } } } diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/QueueItem.cs index dc9cfbc229..ce253b182c 100644 --- a/MediaBrowser.Model/SyncPlay/QueueItem.cs +++ b/MediaBrowser.Model/SyncPlay/QueueItem.cs @@ -10,15 +10,15 @@ namespace MediaBrowser.Model.SyncPlay public class QueueItem { /// - /// Gets or sets the item id. + /// Gets or sets the item identifier. /// - /// The item id. + /// The item identifier. public Guid ItemId { get; set; } /// - /// Gets or sets the playlist id of the item. + /// Gets or sets the playlist identifier of the item. /// - /// The playlist id of the item. + /// The playlist identifier of the item. public string PlaylistItemId { get; set; } } } diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs index 779f711af0..b24f7e97bd 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommand.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs @@ -14,9 +14,9 @@ namespace MediaBrowser.Model.SyncPlay public string GroupId { get; set; } /// - /// Gets or sets the playlist id of the playing item. + /// Gets or sets the playlist identifier of the playing item. /// - /// The playlist id of the playing item. + /// The playlist identifier of the playing item. public string PlaylistItemId { get; set; } /// From 28ee4f0a7f7b7be954ac2dccc374bf72b1eb4f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Thu, 22 Oct 2020 11:09:59 +0200 Subject: [PATCH 0131/1930] [AudioTranscoding] Add FLAC as supported target audio format and be able to define the corresponding target sample rate --- .../MediaEncoding/EncodingJobInfo.cs | 5 +++- .../Encoder/EncoderValidator.cs | 2 ++ MediaBrowser.Model/Dlna/StreamBuilder.cs | 26 +++++++++++++++++++ MediaBrowser.Model/Dlna/StreamInfo.cs | 9 +++++-- 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 6cd0c70d2f..e99c48a704 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -404,7 +404,10 @@ namespace MediaBrowser.Controller.MediaEncoding { // Don't exceed what the encoder supports // Seeing issues of attempting to encode to 88200 - return Math.Min(44100, BaseRequest.AudioSampleRate.Value); + // return Math.Min(44100, BaseRequest.AudioSampleRate.Value); + + // I don't see any reason why limiting the sample rate to a maximum of 44100 ! + return BaseRequest.AudioSampleRate.Value; } return null; diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 3287f9814e..92f16ab95c 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -25,6 +25,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "ac3", "aac", "mp3", + "flac", "h264_qsv", "hevc_qsv", "mpeg2_qsv", @@ -71,6 +72,7 @@ namespace MediaBrowser.MediaEncoding.Encoder "libmp3lame", "libopus", "libvorbis", + "flac", "srt", "h264_amf", "hevc_amf", diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 4959a9b922..cf392ffcec 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1438,6 +1438,32 @@ namespace MediaBrowser.Model.Dlna break; } + case ProfileConditionValue.AudioSampleRate: + { + if (!enableNonQualifiedConditions) + { + continue; + } + + if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var num)) + { + if (condition.Condition == ProfileConditionType.Equals) + { + item.AudioSampleRate = num; + } + else if (condition.Condition == ProfileConditionType.LessThanEqual) + { + item.AudioSampleRate = Math.Min(num, item.AudioSampleRate ?? num); + } + else if (condition.Condition == ProfileConditionType.GreaterThanEqual) + { + item.AudioSampleRate = Math.Max(num, item.AudioSampleRate ?? num); + } + } + + break; + } + case ProfileConditionValue.AudioChannels: { if (string.IsNullOrEmpty(qualifier)) diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 9399d21f16..20ca547735 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -110,6 +110,8 @@ namespace MediaBrowser.Model.Dlna public int? AudioBitrate { get; set; } + public int? AudioSampleRate { get; set; } + public int? VideoBitrate { get; set; } public int? MaxWidth { get; set; } @@ -184,7 +186,7 @@ namespace MediaBrowser.Model.Dlna } if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && - string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase)) + string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) { continue; } @@ -250,6 +252,7 @@ namespace MediaBrowser.Model.Dlna list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); @@ -521,7 +524,9 @@ namespace MediaBrowser.Model.Dlna get { var stream = TargetAudioStream; - return stream == null ? null : stream.SampleRate; + return AudioSampleRate.HasValue && !IsDirectStream + ? AudioSampleRate + : stream == null ? null : stream.SampleRate; } } From 5979151f118ef48a966368530b5db68f2c72991a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Thu, 22 Oct 2020 12:22:31 +0200 Subject: [PATCH 0132/1930] [AudioTranscoding] Add FLAC as supported target audio format and be able to define the corresponding target sample rate --- Emby.Dlna/PlayTo/PlayToController.cs | 5 ++++- MediaBrowser.Model/Dlna/StreamInfo.cs | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index a5b8e2b3ce..2aebc0f1db 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -945,7 +945,10 @@ namespace Emby.Dlna.PlayTo request.DeviceId = values.GetValueOrDefault("DeviceId"); request.MediaSourceId = values.GetValueOrDefault("MediaSourceId"); request.LiveStreamId = values.GetValueOrDefault("LiveStreamId"); - request.IsDirectStream = string.Equals("true", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase); + + // Be careful, IsDirectStream==true by default (Static != false or not in query). + // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. + request.IsDirectStream = !string.Equals("false", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase); request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex"); request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex"); diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 20ca547735..93ea82c1c5 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -185,6 +185,8 @@ namespace MediaBrowser.Model.Dlna continue; } + // Be careful, IsDirectStream==true by default (Static != false or not in query). + // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) { From 95ecedbce7281e215b7c3c7403e648b0f66622e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Thu, 22 Oct 2020 12:49:26 +0200 Subject: [PATCH 0133/1930] [AudioTranscoding] Add FLAC as supported target audio format and be able to define the corresponding target sample rate --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7b4772730a..a97a4c7416 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -104,6 +104,7 @@ - [sorinyo2004](https://github.com/sorinyo2004) - [sparky8251](https://github.com/sparky8251) - [spookbits](https://github.com/spookbits) + - [ssenart] (https://github.com/ssenart) - [stanionascu](https://github.com/stanionascu) - [stevehayles](https://github.com/stevehayles) - [SuperSandro2000](https://github.com/SuperSandro2000) From 1b8adf0f7c21f6596e2fdcc0ac431c831d0ad582 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 22 Oct 2020 13:28:09 +0100 Subject: [PATCH 0134/1930] Update Emby.Server.Implementations/SyncPlay/GroupController.cs --- Emby.Server.Implementations/SyncPlay/GroupController.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 26972de8aa..2d86680149 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -174,8 +174,10 @@ namespace Emby.Server.Implementations.SyncPlay case SyncPlayBroadcastType.CurrentSession: return new SessionInfo[] { from }; case SyncPlayBroadcastType.AllGroup: - return Participants.Values.Select( - session => session.Session).ToArray(); + return Participants + .Values + .Select(session => session.Session) + .ToArray(); case SyncPlayBroadcastType.AllExceptCurrentSession: return Participants.Values.Select( session => session.Session).Where( From f6ab98507ec6ac25e9b2239e519118db07672592 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 22 Oct 2020 13:29:09 +0100 Subject: [PATCH 0135/1930] Update MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs --- MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index aca50f80a7..6373a52116 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -486,7 +486,10 @@ namespace MediaBrowser.Controller.SyncPlay ShufflePlaylist(); break; default: + if (!ShuffleMode.Equals(mode)) + { SortShuffledPlaylist(); + } break; } } From 0b4c7516570f7bc9c85c75c8667a2437d52ad199 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca Date: Thu, 22 Oct 2020 15:40:34 +0200 Subject: [PATCH 0136/1930] Check for null sessions and requests in SyncPlay --- .../SyncPlay/SyncPlayManager.cs | 124 ++++++++++++------ .../SyncPlay/GroupRequestType.cs | 33 +++++ 2 files changed, 119 insertions(+), 38 deletions(-) create mode 100644 MediaBrowser.Model/SyncPlay/GroupRequestType.cs diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 6e3b492498..ab9be145f3 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -160,6 +160,48 @@ namespace Emby.Server.Implementations.SyncPlay // TODO: probably remove this event, not used at the moment. } + private bool IsRequestValid(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true) + { + if (session == null || (request == null && checkRequest)) + { + return false; + } + + var user = _userManager.GetUserById(session.UserId); + + if (user.SyncPlayAccess == SyncPlayAccess.None) + { + _logger.LogWarning("IsRequestValid: {0} does not have access to SyncPlay. Requested {1}.", session.Id, requestType); + + var error = new GroupUpdate() + { + // TODO: rename to a more generic error. Next PR will fix this. + Type = GroupUpdateType.JoinGroupDenied + }; + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return false; + } + + if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) + { + _logger.LogWarning("IsRequestValid: {0} does not have permission to create groups.", session.Id); + + var error = new GroupUpdate + { + Type = GroupUpdateType.CreateGroupDenied + }; + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return false; + } + + return true; + } + + private bool IsRequestValid(SessionInfo session, GroupRequestType requestType) + { + return IsRequestValid(session, requestType, session, false); + } + private bool IsSessionInGroup(SessionInfo session) { return _sessionToGroupMap.ContainsKey(session.Id); @@ -174,17 +216,9 @@ namespace Emby.Server.Implementations.SyncPlay /// public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) + // TODO: create abstract class for GroupRequests to avoid explicit request type here. + if (!IsRequestValid(session, GroupRequestType.NewGroup, request)) { - _logger.LogWarning("NewGroup: {0} does not have permission to create groups.", session.Id); - - var error = new GroupUpdate - { - Type = GroupUpdateType.CreateGroupDenied - }; - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -205,24 +239,17 @@ namespace Emby.Server.Implementations.SyncPlay /// public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken) { - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess == SyncPlayAccess.None) + // TODO: create abstract class for GroupRequests to avoid explicit request type here. + if (!IsRequestValid(session, GroupRequestType.JoinGroup, request)) { - _logger.LogWarning("JoinGroup: {0} does not have access to SyncPlay.", session.Id); - - var error = new GroupUpdate() - { - Type = GroupUpdateType.JoinGroupDenied - }; - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } + var user = _userManager.GetUserById(session.UserId); + lock (_groupsLock) { - ISyncPlayGroupController group; - _groups.TryGetValue(groupId, out group); + _groups.TryGetValue(groupId, out ISyncPlayGroupController group); if (group == null) { @@ -267,6 +294,12 @@ namespace Emby.Server.Implementations.SyncPlay /// public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken) { + // TODO: create abstract class for GroupRequests to avoid explicit request type here. + if (!IsRequestValid(session, GroupRequestType.LeaveGroup)) + { + return; + } + // TODO: determine what happens to users that are in a group and get their permissions revoked. lock (_groupsLock) { @@ -297,32 +330,27 @@ namespace Emby.Server.Implementations.SyncPlay /// public List ListGroups(SessionInfo session) { - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess == SyncPlayAccess.None) + // TODO: create abstract class for GroupRequests to avoid explicit request type here. + if (!IsRequestValid(session, GroupRequestType.ListGroups)) { return new List(); } - return _groups.Values.Where( - group => group.HasAccessToPlayQueue(user)).Select( - group => group.GetInfo()).ToList(); + var user = _userManager.GetUserById(session.UserId); + + return _groups + .Values + .Where(group => group.HasAccessToPlayQueue(user)) + .Select(group => group.GetInfo()) + .ToList(); } /// public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) { - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess == SyncPlayAccess.None) + // TODO: create abstract class for GroupRequests to avoid explicit request type here. + if (!IsRequestValid(session, GroupRequestType.Playback, request)) { - _logger.LogWarning("HandleRequest: {0} does not have access to SyncPlay.", session.Id); - - var error = new GroupUpdate() - { - Type = GroupUpdateType.JoinGroupDenied - }; - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -349,6 +377,16 @@ namespace Emby.Server.Implementations.SyncPlay /// public void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (group == null) + { + throw new InvalidOperationException("Group is null!"); + } + if (IsSessionInGroup(session)) { throw new InvalidOperationException("Session in other group already!"); @@ -360,6 +398,16 @@ namespace Emby.Server.Implementations.SyncPlay /// public void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (group == null) + { + throw new InvalidOperationException("Group is null!"); + } + if (!IsSessionInGroup(session)) { throw new InvalidOperationException("Session not in any group!"); diff --git a/MediaBrowser.Model/SyncPlay/GroupRequestType.cs b/MediaBrowser.Model/SyncPlay/GroupRequestType.cs new file mode 100644 index 0000000000..e7361817ca --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupRequestType.cs @@ -0,0 +1,33 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// + /// Enum GroupRequestType. + /// + public enum GroupRequestType + { + /// + /// A user is requesting to create a new group. + /// + NewGroup, + + /// + /// A user is requesting to join a group. + /// + JoinGroup, + + /// + /// A user is requesting to leave a group. + /// + LeaveGroup, + + /// + /// A user is requesting the list of available groups. + /// + ListGroups, + + /// + /// A user is sending a playback command to a group. + /// + Playback + } +} From 1cabe82b59071a277d81f9438189b565e93f0660 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca Date: Thu, 22 Oct 2020 15:49:37 +0200 Subject: [PATCH 0137/1930] Rewrite play queue logic of SyncPlay group --- .../SyncPlay/GroupController.cs | 2 + .../SyncPlay/Queue/PlayQueueManager.cs | 142 +++++++++++------- 2 files changed, 86 insertions(+), 58 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 26972de8aa..687aa7a3ad 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -263,6 +263,7 @@ namespace Emby.Server.Implementations.SyncPlay if (sessionIsPlayingAnItem) { var playlist = session.NowPlayingQueue.Select(item => item.Id).ToArray(); + PlayQueue.Reset(); PlayQueue.SetPlaylist(playlist); PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id); RunTimeTicks = session.FullNowPlayingItem.RunTimeTicks ?? 0; @@ -515,6 +516,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } + PlayQueue.Reset(); PlayQueue.SetPlaylist(playQueue); PlayQueue.SetPlayingItemByIndex(playingItemPosition); var item = _libraryManager.GetItemById(PlayQueue.GetPlayingItemId()); diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index aca50f80a7..366bedfa1b 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -69,7 +69,11 @@ namespace MediaBrowser.Controller.SyncPlay /// The progressive identifier. private int ProgressiveId { get; set; } = 0; - private bool _disposed = false; + /// + /// Placeholder index for when no item is playing. + /// + /// The no-playing item index. + private const int NoPlayingItemIndex = -1; /// /// Initializes a new instance of the class. @@ -139,6 +143,26 @@ namespace MediaBrowser.Controller.SyncPlay } } + /// + /// Gets the current playing item, depending on the shuffle mode. + /// + /// The playing item. + private QueueItem GetPlayingItem() + { + if (PlayingItemIndex == NoPlayingItemIndex) + { + return null; + } + else if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + return ShuffledPlaylist[PlayingItemIndex]; + } + else + { + return SortedPlaylist[PlayingItemIndex]; + } + } + /// /// Gets the current playlist as an array, depending on the shuffle mode. /// @@ -155,30 +179,36 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Sets a new playlist. Playing item is set to none. Resets shuffle mode and repeat mode as well. + /// Sets a new playlist. Playing item is reset. /// /// The new items of the playlist. public void SetPlaylist(Guid[] items) { + SortedPlaylist.Clear(); + ShuffledPlaylist.Clear(); + SortedPlaylist = CreateQueueItemsFromArray(items); - PlayingItemIndex = -1; - ShuffleMode = GroupShuffleMode.Sorted; - RepeatMode = GroupRepeatMode.RepeatNone; + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist.Shuffle(); + } + + PlayingItemIndex = NoPlayingItemIndex; LastChange = DateTime.UtcNow; } /// - /// Appends new items to the playlist. The specified order is mantained for the sorted playlist, whereas items get shuffled for the shuffled playlist. + /// Appends new items to the playlist. The specified order is mantained. /// /// The items to add to the playlist. public void Queue(Guid[] items) { var newItems = CreateQueueItemsFromArray(items); - SortedPlaylist.AddRange(newItems); + SortedPlaylist.AddRange(newItems); if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { - newItems.Shuffle(); ShuffledPlaylist.AddRange(newItems); } @@ -190,17 +220,13 @@ namespace MediaBrowser.Controller.SyncPlay /// public void ShufflePlaylist() { - if (SortedPlaylist.Count() == 0) - { - return; - } - - if (PlayingItemIndex < 0) { + if (PlayingItemIndex == NoPlayingItemIndex) { ShuffledPlaylist = SortedPlaylist.ToList(); ShuffledPlaylist.Shuffle(); } - else + else if (ShuffleMode.Equals(GroupShuffleMode.Sorted)) { + // First time shuffle. var playingItem = SortedPlaylist[PlayingItemIndex]; ShuffledPlaylist = SortedPlaylist.ToList(); ShuffledPlaylist.RemoveAt(PlayingItemIndex); @@ -208,6 +234,15 @@ namespace MediaBrowser.Controller.SyncPlay ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); PlayingItemIndex = 0; } + else + { + // Re-shuffle playlist. + var playingItem = ShuffledPlaylist[PlayingItemIndex]; + ShuffledPlaylist.RemoveAt(PlayingItemIndex); + ShuffledPlaylist.Shuffle(); + ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); + PlayingItemIndex = 0; + } ShuffleMode = GroupShuffleMode.Shuffle; LastChange = DateTime.UtcNow; @@ -216,9 +251,9 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Resets the playlist to sorted mode. Shuffle mode is changed. /// - public void SortShuffledPlaylist() + public void RestoreSortedPlaylist() { - if (PlayingItemIndex >= 0) + if (PlayingItemIndex != NoPlayingItemIndex) { var playingItem = ShuffledPlaylist[PlayingItemIndex]; PlayingItemIndex = SortedPlaylist.IndexOf(playingItem); @@ -231,12 +266,12 @@ namespace MediaBrowser.Controller.SyncPlay } /// - /// Clears the playlist. + /// Clears the playlist. Shuffle mode is preserved. /// /// Whether to remove the playing item as well. public void ClearPlaylist(bool clearPlayingItem) { - var playingItem = SortedPlaylist[PlayingItemIndex]; + var playingItem = GetPlayingItem(); SortedPlaylist.Clear(); ShuffledPlaylist.Clear(); LastChange = DateTime.UtcNow; @@ -246,13 +281,18 @@ namespace MediaBrowser.Controller.SyncPlay SortedPlaylist.Add(playingItem); if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { - SortedPlaylist.Add(playingItem); + ShuffledPlaylist.Add(playingItem); } + PlayingItemIndex = 0; + } + else + { + PlayingItemIndex = NoPlayingItemIndex; } } /// - /// Adds new items to the playlist right after the playing item. The specified order is mantained for the sorted playlist, whereas items get shuffled for the shuffled playlist. + /// Adds new items to the playlist right after the playing item. The specified order is mantained. /// /// The items to add to the playlist. public void QueueNext(Guid[] items) @@ -261,10 +301,10 @@ namespace MediaBrowser.Controller.SyncPlay if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { - // Append items to sorted playlist as they are. - SortedPlaylist.AddRange(newItems); - // Shuffle items before adding to shuffled playlist. - newItems.Shuffle(); + var playingItem = GetPlayingItem(); + var sortedPlayingItemIndex = SortedPlaylist.IndexOf(playingItem); + // Append items to sorted and shuffled playlist as they are. + SortedPlaylist.InsertRange(sortedPlayingItemIndex + 1, newItems); ShuffledPlaylist.InsertRange(PlayingItemIndex + 1, newItems); } else @@ -281,16 +321,10 @@ namespace MediaBrowser.Controller.SyncPlay /// The playlist identifier of the playing item. public string GetPlayingItemPlaylistId() { - if (PlayingItemIndex < 0) + var playingItem = GetPlayingItem(); + if (playingItem != null) { - return null; - } - - var list = GetPlaylistAsList(); - - if (list.Count() > 0) - { - return list[PlayingItemIndex].PlaylistItemId; + return playingItem.PlaylistItemId; } else { @@ -304,16 +338,10 @@ namespace MediaBrowser.Controller.SyncPlay /// The playing item identifier. public Guid GetPlayingItemId() { - if (PlayingItemIndex < 0) + var playingItem = GetPlayingItem(); + if (playingItem != null) { - return Guid.Empty; - } - - var list = GetPlaylistAsList(); - - if (list.Count() > 0) - { - return list[PlayingItemIndex].ItemId; + return playingItem.ItemId; } else { @@ -342,7 +370,7 @@ namespace MediaBrowser.Controller.SyncPlay var playlistIds = GetPlaylistAsList().Select(queueItem => queueItem.PlaylistItemId).ToList(); PlayingItemIndex = playlistIds.IndexOf(playlistItemId); LastChange = DateTime.UtcNow; - return PlayingItemIndex != -1; + return PlayingItemIndex != NoPlayingItemIndex; } /// @@ -354,7 +382,7 @@ namespace MediaBrowser.Controller.SyncPlay var list = GetPlaylistAsList(); if (playlistIndex < 0 || playlistIndex > list.Count()) { - PlayingItemIndex = -1; + PlayingItemIndex = NoPlayingItemIndex; } else { @@ -371,13 +399,9 @@ namespace MediaBrowser.Controller.SyncPlay /// true if playing item got removed; false otherwise. public bool RemoveFromPlaylist(string[] playlistItemIds) { - var playingItem = SortedPlaylist[PlayingItemIndex]; - if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) - { - playingItem = ShuffledPlaylist[PlayingItemIndex]; - } - + var playingItem = GetPlayingItem(); var playlistItemIdsList = playlistItemIds.ToList(); + SortedPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); ShuffledPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); @@ -392,7 +416,8 @@ namespace MediaBrowser.Controller.SyncPlay if (PlayingItemIndex < 0) { // Was first element, picking next if available. - PlayingItemIndex = SortedPlaylist.Count() > 0 ? 0 : -1; + // Default to no playing item otherwise. + PlayingItemIndex = SortedPlaylist.Count() > 0 ? 0 : NoPlayingItemIndex; } return true; @@ -419,18 +444,19 @@ namespace MediaBrowser.Controller.SyncPlay public bool MovePlaylistItem(string playlistItemId, int newIndex) { var list = GetPlaylistAsList(); - var playingItem = list[PlayingItemIndex]; + var playingItem = GetPlayingItem(); var playlistIds = list.Select(queueItem => queueItem.PlaylistItemId).ToList(); var oldIndex = playlistIds.IndexOf(playlistItemId); - if (oldIndex < 0) { + if (oldIndex < 0) + { return false; } var queueItem = list[oldIndex]; list.RemoveAt(oldIndex); - newIndex = newIndex > list.Count() ? list.Count() : newIndex; - newIndex = newIndex < 0 ? 0 : newIndex; + newIndex = Math.Min(newIndex, list.Count()); + newIndex = Math.Max(newIndex, 0); list.Insert(newIndex, queueItem); LastChange = DateTime.UtcNow; @@ -446,7 +472,7 @@ namespace MediaBrowser.Controller.SyncPlay ProgressiveId = 0; SortedPlaylist.Clear(); ShuffledPlaylist.Clear(); - PlayingItemIndex = -1; + PlayingItemIndex = NoPlayingItemIndex; ShuffleMode = GroupShuffleMode.Sorted; RepeatMode = GroupRepeatMode.RepeatNone; LastChange = DateTime.UtcNow; @@ -486,7 +512,7 @@ namespace MediaBrowser.Controller.SyncPlay ShufflePlaylist(); break; default: - SortShuffledPlaylist(); + RestoreSortedPlaylist(); break; } } From 0c735a039538bfaa44d25df415f3d41519e37194 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca Date: Thu, 22 Oct 2020 15:51:58 +0200 Subject: [PATCH 0138/1930] Address requested changes by review --- .../SyncPlay/GroupController.cs | 50 ++++++++++--------- .../GroupStates/AbstractGroupState.cs | 2 +- .../SyncPlay/GroupStates/IdleGroupState.cs | 3 +- .../SyncPlay/GroupStates/PausedGroupState.cs | 9 +++- .../SyncPlay/GroupStates/PlayingGroupState.cs | 3 +- .../SyncPlay/GroupStates/WaitingGroupState.cs | 17 +++++-- .../SyncPlay/Queue/PlayQueueManager.cs | 25 +--------- 7 files changed, 54 insertions(+), 55 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 687aa7a3ad..65a711fb42 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -126,16 +126,6 @@ namespace Emby.Server.Implementations.SyncPlay State = new IdleGroupState(_logger); } - /// - /// Checks if a session is in this group. - /// - /// The session identifier to check. - /// true if the session is in this group; false otherwise. - private bool ContainsSession(string sessionId) - { - return Participants.ContainsKey(sessionId); - } - /// /// Adds the session to the group. /// @@ -174,16 +164,22 @@ namespace Emby.Server.Implementations.SyncPlay case SyncPlayBroadcastType.CurrentSession: return new SessionInfo[] { from }; case SyncPlayBroadcastType.AllGroup: - return Participants.Values.Select( - session => session.Session).ToArray(); + return Participants + .Values + .Select(session => session.Session) + .ToArray(); case SyncPlayBroadcastType.AllExceptCurrentSession: - return Participants.Values.Select( - session => session.Session).Where( - session => !session.Id.Equals(from.Id)).ToArray(); + return Participants + .Values + .Select(session => session.Session) + .Where(session => !session.Id.Equals(from.Id)) + .ToArray(); case SyncPlayBroadcastType.AllReady: - return Participants.Values.Where( - session => !session.IsBuffering).Select( - session => session.Session).ToArray(); + return Participants + .Values + .Where(session => !session.IsBuffering) + .Select(session => session.Session) + .ToArray(); default: return Array.Empty(); } @@ -236,7 +232,8 @@ namespace Emby.Server.Implementations.SyncPlay } // Get list of users. - var users = Participants.Values + var users = Participants + .Values .Select(participant => _userManager.GetUserById(participant.Session.UserId)); // Find problematic users. @@ -365,7 +362,7 @@ namespace Emby.Server.Implementations.SyncPlay /// public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait) { - if (!ContainsSession(session.Id)) + if (!Participants.ContainsKey(session.Id)) { return; } @@ -443,8 +440,8 @@ namespace Emby.Server.Implementations.SyncPlay public long SanitizePositionTicks(long? positionTicks) { var ticks = positionTicks ?? 0; - ticks = ticks >= 0 ? ticks : 0; - ticks = ticks > RunTimeTicks ? RunTimeTicks : ticks; + ticks = Math.Max(ticks, 0); + ticks = Math.Min(ticks, RunTimeTicks); return ticks; } @@ -663,8 +660,13 @@ namespace Emby.Server.Implementations.SyncPlay { var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - LastActivity; - // Event may happen during the delay added to account for latency. - startPositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0; + // Elapsed time is negative if event happens + // during the delay added to account for latency. + // In this phase clients haven't started the playback yet. + // In other words, LastActivity is in the future, + // when playback unpause is supposed to happen. + // Adjust ticks only if playback actually started. + startPositionTicks += Math.Max(elapsedTime.Ticks, 0); } return new PlayQueueUpdate() diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs index 1eb1107721..26cd51b8d8 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs @@ -212,7 +212,7 @@ namespace MediaBrowser.Controller.SyncPlay private void UnhandledRequest(IPlaybackGroupRequest request) { - _logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.GetRequestType(), this.GetGroupState()); + _logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.GetRequestType(), GetGroupState()); } } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs index b8510715ac..70fe3e0067 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs @@ -16,7 +16,8 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Default constructor. /// - public IdleGroupState(ILogger logger) : base(logger) + public IdleGroupState(ILogger logger) + : base(logger) { // Do nothing. } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs index 8c4bd20b1c..ca2cb0988b 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs @@ -17,7 +17,8 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Default constructor. /// - public PausedGroupState(ILogger logger) : base(logger) + public PausedGroupState(ILogger logger) + : base(logger) { // Do nothing. } @@ -70,8 +71,12 @@ namespace MediaBrowser.Controller.SyncPlay var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; + // Elapsed time is negative if event happens + // during the delay added to account for latency. + // In this phase clients haven't started the playback yet. + // In other words, LastActivity is in the future, + // when playback unpause is supposed to happen. // Seek only if playback actually started. - // Pause request may be issued during the delay added to account for latency. context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); var command = context.NewSyncPlayCommand(SendCommandType.Pause); diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs index a3b0baf963..85119669dd 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs @@ -22,7 +22,8 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Default constructor. /// - public PlayingGroupState(ILogger logger) : base(logger) + public PlayingGroupState(ILogger logger) + : base(logger) { // Do nothing. } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs index ff1d379d77..8e970751f1 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs @@ -32,7 +32,8 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Default constructor. /// - public WaitingGroupState(ILogger logger) : base(logger) + public WaitingGroupState(ILogger logger) + : base(logger) { // Do nothing. } @@ -59,8 +60,12 @@ namespace MediaBrowser.Controller.SyncPlay var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; + // Elapsed time is negative if event happens + // during the delay added to account for latency. + // In this phase clients haven't started the playback yet. + // In other words, LastActivity is in the future, + // when playback unpause is supposed to happen. // Seek only if playback actually started. - // Event may happen during the delay added to account for latency. context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); } @@ -355,6 +360,12 @@ namespace MediaBrowser.Controller.SyncPlay var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - context.LastActivity; context.LastActivity = currentTime; + // Elapsed time is negative if event happens + // during the delay added to account for latency. + // In this phase clients haven't started the playback yet. + // In other words, LastActivity is in the future, + // when playback unpause is supposed to happen. + // Seek only if playback actually started. context.PositionTicks += Math.Max(elapsedTime.Ticks, 0); // Send pause command to all non-buffering sessions. @@ -484,7 +495,7 @@ namespace MediaBrowser.Controller.SyncPlay { // Client, that was buffering, resumed playback but did not update others in time. delayTicks = context.GetHighestPing() * 2 * TimeSpan.TicksPerMillisecond; - delayTicks = delayTicks < context.DefaultPing ? context.DefaultPing : delayTicks; + delayTicks = Math.Max(delayTicks, context.DefaultPing); context.LastActivity = currentTime.AddTicks(delayTicks); diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 366bedfa1b..9ab0dfd2ad 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay /// /// Class PlayQueueManager. /// - public class PlayQueueManager : IDisposable + public class PlayQueueManager { /// /// Gets or sets the playing item index. @@ -83,27 +83,6 @@ namespace MediaBrowser.Controller.SyncPlay Reset(); } - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and optionally managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - _disposed = true; - } - /// /// Gets the next available identifier. /// @@ -284,7 +263,7 @@ namespace MediaBrowser.Controller.SyncPlay ShuffledPlaylist.Add(playingItem); } PlayingItemIndex = 0; - } + } else { PlayingItemIndex = NoPlayingItemIndex; From 82ce8369c387a0c01b0c90e4a8ca2e63b4f48528 Mon Sep 17 00:00:00 2001 From: SHALMON ANANDAS Date: Fri, 23 Oct 2020 02:56:58 +0000 Subject: [PATCH 0139/1930] Added translation using Weblate (Hindi) --- Emby.Server.Implementations/Localization/Core/hi.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/hi.json diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -0,0 +1 @@ +{} From a69397d7141a6f8fde840cb53516244785243de8 Mon Sep 17 00:00:00 2001 From: SHALMON ANANDAS Date: Fri, 23 Oct 2020 02:57:46 +0000 Subject: [PATCH 0140/1930] Translated using Weblate (Hindi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hi/ --- Emby.Server.Implementations/Localization/Core/hi.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index 0967ef424b..df68d3bbd4 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -1 +1,3 @@ -{} +{ + "Albums": "आल्बुम्" +} From 84fd5a09532bd1e854ec3745609f845aa7098da2 Mon Sep 17 00:00:00 2001 From: Orry Verducci Date: Sun, 25 Oct 2020 16:35:03 +0000 Subject: [PATCH 0141/1930] Fix frame rate probing for interlaced MKV files --- .../Probing/ProbeResultNormalizer.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 22537a4d95..cdeefbbbdf 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -666,6 +666,16 @@ namespace MediaBrowser.MediaEncoding.Probing stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate); stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate); + // Interlaced video streams in Matroska containers return the field rate instead of the frame rate + // as both the average and real frame rate, so we half the returned frame rates to get the correct values + // + // https://gitlab.com/mbunkus/mkvtoolnix/-/wikis/Wrong-frame-rate-displayed + if (stream.IsInterlaced && formatInfo.FormatName.Contains("matroska", StringComparison.OrdinalIgnoreCase)) + { + stream.AverageFrameRate /= 2; + stream.RealFrameRate /= 2; + } + if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)) { From a814d01f8c6edab930877031cd9e323f9ceda9d0 Mon Sep 17 00:00:00 2001 From: kevin Date: Sun, 25 Oct 2020 20:42:04 +0000 Subject: [PATCH 0142/1930] Translated using Weblate (Albanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sq/ --- Emby.Server.Implementations/Localization/Core/sq.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sq.json b/Emby.Server.Implementations/Localization/Core/sq.json index ecca5af4cc..0d909b06e9 100644 --- a/Emby.Server.Implementations/Localization/Core/sq.json +++ b/Emby.Server.Implementations/Localization/Core/sq.json @@ -112,5 +112,5 @@ "Artists": "Artistë", "Application": "Aplikacioni", "AppDeviceValues": "Aplikacioni: {0}, Pajisja: {1}", - "Albums": "Albumet" + "Albums": "Albume" } From c11f19f09052bea1d386869574505f506a449cf2 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 26 Oct 2020 11:21:32 +0100 Subject: [PATCH 0143/1930] Fix GET ScheduledTasks return value --- Jellyfin.Api/Controllers/ScheduledTasksController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/ScheduledTasksController.cs b/Jellyfin.Api/Controllers/ScheduledTasksController.cs index ab7920895b..68e4f0586f 100644 --- a/Jellyfin.Api/Controllers/ScheduledTasksController.cs +++ b/Jellyfin.Api/Controllers/ScheduledTasksController.cs @@ -36,7 +36,7 @@ namespace Jellyfin.Api.Controllers /// The list of scheduled tasks. [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] - public IEnumerable GetTasks( + public IEnumerable GetTasks( [FromQuery] bool? isHidden, [FromQuery] bool? isEnabled) { @@ -57,7 +57,7 @@ namespace Jellyfin.Api.Controllers } } - yield return task; + yield return ScheduledTaskHelpers.GetTaskInfo(task); } } From e0045457f900b69530e6d87522d9c4769e2cf01b Mon Sep 17 00:00:00 2001 From: Tomi Date: Mon, 26 Oct 2020 19:09:02 +0000 Subject: [PATCH 0144/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- .../Localization/Core/fi.json | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index aae22583ab..8e219a9cef 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -1,7 +1,7 @@ { "HeaderLiveTV": "Live-TV", "NewVersionIsAvailable": "Uusi versio Jellyfin palvelimesta on ladattavissa.", - "NameSeasonUnknown": "Tuntematon Kausi", + "NameSeasonUnknown": "Tuntematon kausi", "NameSeasonNumber": "Kausi {0}", "NameInstallFailed": "{0} asennus epäonnistui", "MusicVideos": "Musiikkivideot", @@ -19,23 +19,23 @@ "ItemAddedWithName": "{0} lisättiin kirjastoon", "Inherit": "Periytyä", "HomeVideos": "Kotivideot", - "HeaderRecordingGroups": "Nauhoiteryhmät", + "HeaderRecordingGroups": "Tallennusryhmät", "HeaderNextUp": "Seuraavaksi", - "HeaderFavoriteSongs": "Lempikappaleet", - "HeaderFavoriteShows": "Lempisarjat", - "HeaderFavoriteEpisodes": "Lempijaksot", - "HeaderFavoriteArtists": "Lempiartistit", - "HeaderFavoriteAlbums": "Lempialbumit", + "HeaderFavoriteSongs": "Suosikkikappaleet", + "HeaderFavoriteShows": "Suosikkisarjat", + "HeaderFavoriteEpisodes": "Suosikkijaksot", + "HeaderFavoriteArtists": "Suosikkiartistit", + "HeaderFavoriteAlbums": "Suosikkialbumit", "HeaderContinueWatching": "Jatka katsomista", - "HeaderAlbumArtists": "Albumin esittäjä", + "HeaderAlbumArtists": "Albumin artistit", "Genres": "Tyylilajit", "Folders": "Kansiot", "Favorites": "Suosikit", "FailedLoginAttemptWithUserName": "Kirjautuminen epäonnistui kohteesta {0}", "DeviceOnlineWithName": "{0} on yhdistetty", - "DeviceOfflineWithName": "{0} on katkaissut yhteytensä", + "DeviceOfflineWithName": "{0} yhteys on katkaistu", "Collections": "Kokoelmat", - "ChapterNameValue": "Luku: {0}", + "ChapterNameValue": "Jakso: {0}", "Channels": "Kanavat", "CameraImageUploadedFrom": "Uusi kamerakuva on ladattu {0}", "Books": "Kirjat", @@ -61,25 +61,25 @@ "UserPolicyUpdatedWithName": "Käyttöoikeudet päivitetty käyttäjälle {0}", "UserPasswordChangedWithName": "Salasana vaihdettu käyttäjälle {0}", "UserOnlineFromDevice": "{0} on paikalla osoitteesta {1}", - "UserOfflineFromDevice": "{0} yhteys katkaistu {1}", + "UserOfflineFromDevice": "{0} yhteys katkaistu kohteesta {1}", "UserLockedOutWithName": "Käyttäjä {0} lukittu", "UserDownloadingItemWithValues": "{0} lataa {1}", "UserDeletedWithName": "Käyttäjä {0} poistettu", "UserCreatedWithName": "Käyttäjä {0} luotu", - "TvShows": "TV-sarjat", + "TvShows": "TV-ohjelmat", "Sync": "Synkronoi", - "SubtitleDownloadFailureFromForItem": "Tekstitysten lataus ({0} -> {1}) epäonnistui //this string would have to be generated for each provider and movie because of finnish cases, sorry", - "StartupEmbyServerIsLoading": "Jellyfin palvelin latautuu. Kokeile hetken kuluttua uudelleen.", + "SubtitleDownloadFailureFromForItem": "Tekstitystä ei voitu ladata osoitteesta {0} kohteelle {1}", + "StartupEmbyServerIsLoading": "Jellyfin palvelin latautuu. Yritä hetken kuluttua uudelleen.", "Songs": "Kappaleet", - "Shows": "Sarjat", - "ServerNameNeedsToBeRestarted": "{0} täytyy käynnistää uudelleen", + "Shows": "Ohjelmat", + "ServerNameNeedsToBeRestarted": "{0} on käynnistettävä uudelleen", "ProviderValue": "Tarjoaja: {0}", "Plugin": "Liitännäinen", "NotificationOptionVideoPlaybackStopped": "Videon toisto pysäytetty", "NotificationOptionVideoPlayback": "Videota toistetaan", "NotificationOptionUserLockedOut": "Käyttäjä kirjautui ulos", "NotificationOptionTaskFailed": "Ajastettu tehtävä epäonnistui", - "NotificationOptionServerRestartRequired": "Palvelin pitää käynnistää uudelleen", + "NotificationOptionServerRestartRequired": "Palvelin on käynnistettävä uudelleen", "NotificationOptionPluginUpdateInstalled": "Liitännäinen päivitetty", "NotificationOptionPluginUninstalled": "Liitännäinen poistettu", "NotificationOptionPluginInstalled": "Liitännäinen asennettu", @@ -104,10 +104,10 @@ "TaskRefreshPeople": "Päivitä henkilöt", "TaskCleanLogsDescription": "Poistaa lokitiedostot jotka ovat yli {0} päivää vanhoja.", "TaskCleanLogs": "Puhdista lokihakemisto", - "TaskRefreshLibraryDescription": "Skannaa mediakirjastosi uusien tiedostojen varalle, sekä virkistää metatiedot.", + "TaskRefreshLibraryDescription": "Skannaa mediakirjastosi uudet tiedostot ja päivittää metatiedot.", "TaskRefreshLibrary": "Skannaa mediakirjasto", - "TaskRefreshChapterImagesDescription": "Luo pienoiskuvat videoille joissa on lukuja.", - "TaskRefreshChapterImages": "Eristä lukujen kuvat", + "TaskRefreshChapterImagesDescription": "Luo pienoiskuvat videoille joissa on jaksoja.", + "TaskRefreshChapterImages": "Pura jakson kuvat", "TaskCleanCacheDescription": "Poistaa järjestelmälle tarpeettomat väliaikaistiedostot.", "TaskCleanCache": "Tyhjennä välimuisti-hakemisto", "TasksChannelsCategory": "Internet kanavat", From eee95336b561a39ca4178a7d7acf3ea65eb7549e Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 26 Oct 2020 17:18:54 -0600 Subject: [PATCH 0145/1930] Fix setting duplicate keys from auth header --- .../HttpServer/Security/AuthorizationContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 4b407dd9d2..8140fe81be 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -267,7 +267,7 @@ namespace Emby.Server.Implementations.HttpServer.Security if (param.Length == 2) { var value = NormalizeValue(param[1].Trim(new[] { '"' })); - result.Add(param[0], value); + result[param[0]] = value; } } From aff8684d2e513d4c73e7919f464e2d34d6d63047 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Mon, 26 Oct 2020 20:31:10 -0400 Subject: [PATCH 0146/1930] Add caching to users --- .../Users/UserManager.cs | 86 +++++++------------ 1 file changed, 31 insertions(+), 55 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 437833aa38..c8b754514c 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -2,6 +2,7 @@ #pragma warning disable CA1307 using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -48,6 +49,8 @@ namespace Jellyfin.Server.Implementations.Users private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider; private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider; + private readonly IDictionary _users = new ConcurrentDictionary(); + /// /// Initializes a new instance of the class. /// @@ -81,6 +84,17 @@ namespace Jellyfin.Server.Implementations.Users _invalidAuthProvider = _authenticationProviders.OfType().First(); _defaultAuthenticationProvider = _authenticationProviders.OfType().First(); _defaultPasswordResetProvider = _passwordResetProviders.OfType().First(); + + using var dbContext = _dbProvider.CreateContext(); + foreach (var user in dbContext.Users + .Include(user => user.Permissions) + .Include(user => user.Preferences) + .Include(user => user.AccessSchedules) + .Include(user => user.ProfileImage) + .AsEnumerable()) + { + _users.Add(user.Id, user); + } } /// @@ -89,29 +103,13 @@ namespace Jellyfin.Server.Implementations.Users /// public IEnumerable Users { - get - { - using var dbContext = _dbProvider.CreateContext(); - return dbContext.Users - .Include(user => user.Permissions) - .Include(user => user.Preferences) - .Include(user => user.AccessSchedules) - .Include(user => user.ProfileImage) - .ToList(); - } + get { return _users.Values; } } /// public IEnumerable UsersIds { - get - { - using var dbContext = _dbProvider.CreateContext(); - return dbContext.Users - .AsQueryable() - .Select(user => user.Id) - .ToList(); - } + get { return _users.Keys; } } /// @@ -122,13 +120,8 @@ namespace Jellyfin.Server.Implementations.Users throw new ArgumentException("Guid can't be empty", nameof(id)); } - using var dbContext = _dbProvider.CreateContext(); - return dbContext.Users - .Include(user => user.Permissions) - .Include(user => user.Preferences) - .Include(user => user.AccessSchedules) - .Include(user => user.ProfileImage) - .FirstOrDefault(user => user.Id == id); + _users.TryGetValue(id, out var user); + return user; } /// @@ -139,14 +132,7 @@ namespace Jellyfin.Server.Implementations.Users throw new ArgumentException("Invalid username", nameof(name)); } - using var dbContext = _dbProvider.CreateContext(); - return dbContext.Users - .Include(user => user.Permissions) - .Include(user => user.Preferences) - .Include(user => user.AccessSchedules) - .Include(user => user.ProfileImage) - .AsEnumerable() - .FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase)); + return _users.Values.FirstOrDefault(u => string.Equals(u.Username, name, StringComparison.OrdinalIgnoreCase)); } /// @@ -205,13 +191,17 @@ namespace Jellyfin.Server.Implementations.Users ? await dbContext.Users.AsQueryable().Select(u => u.InternalId).MaxAsync().ConfigureAwait(false) : 0; - return new User( + var user = new User( name, _defaultAuthenticationProvider.GetType().FullName, _defaultPasswordResetProvider.GetType().FullName) { InternalId = max + 1 }; + + _users.Add(user.Id, user); + + return user; } /// @@ -237,28 +227,12 @@ namespace Jellyfin.Server.Implementations.Users /// public void DeleteUser(Guid userId) { - using var dbContext = _dbProvider.CreateContext(); - var user = dbContext.Users - .Include(u => u.Permissions) - .Include(u => u.Preferences) - .Include(u => u.AccessSchedules) - .Include(u => u.ProfileImage) - .FirstOrDefault(u => u.Id == userId); - if (user == null) + if (!_users.TryGetValue(userId, out var user)) { throw new ResourceNotFoundException(nameof(userId)); } - if (dbContext.Users.Find(user.Id) == null) - { - throw new ArgumentException(string.Format( - CultureInfo.InvariantCulture, - "The user cannot be deleted because there is no user with the Name {0} and Id {1}.", - user.Username, - user.Id)); - } - - if (dbContext.Users.Count() == 1) + if (_users.Count == 1) { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, @@ -277,6 +251,8 @@ namespace Jellyfin.Server.Implementations.Users nameof(userId)); } + using var dbContext = _dbProvider.CreateContext(); + // Clear all entities related to the user from the database. if (user.ProfileImage != null) { @@ -288,6 +264,7 @@ namespace Jellyfin.Server.Implementations.Users dbContext.RemoveRange(user.AccessSchedules); dbContext.Users.Remove(user); dbContext.SaveChanges(); + _users.Remove(userId); _eventManager.Publish(new UserDeletedEventArgs(user)); } @@ -589,9 +566,7 @@ namespace Jellyfin.Server.Implementations.Users public async Task InitializeAsync() { // TODO: Refactor the startup wizard so that it doesn't require a user to already exist. - await using var dbContext = _dbProvider.CreateContext(); - - if (await dbContext.Users.AsQueryable().AnyAsync().ConfigureAwait(false)) + if (_users.Any()) { return; } @@ -604,6 +579,7 @@ namespace Jellyfin.Server.Implementations.Users _logger.LogWarning("No users, creating one with username {UserName}", defaultName); + await using var dbContext = _dbProvider.CreateContext(); var newUser = await CreateUserInternalAsync(defaultName, dbContext).ConfigureAwait(false); newUser.SetPermission(PermissionKind.IsAdministrator, true); newUser.SetPermission(PermissionKind.EnableContentDeletion, true); From f051590f14d38012bd8885c6e5ed0406d3c91ecc Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Tue, 27 Oct 2020 12:12:08 -0400 Subject: [PATCH 0147/1930] Apply suggestions --- .../Users/UserManager.cs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index c8b754514c..efc3f439d8 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -49,7 +49,7 @@ namespace Jellyfin.Server.Implementations.Users private readonly DefaultAuthenticationProvider _defaultAuthenticationProvider; private readonly DefaultPasswordResetProvider _defaultPasswordResetProvider; - private readonly IDictionary _users = new ConcurrentDictionary(); + private readonly IDictionary _users; /// /// Initializes a new instance of the class. @@ -85,6 +85,7 @@ namespace Jellyfin.Server.Implementations.Users _defaultAuthenticationProvider = _authenticationProviders.OfType().First(); _defaultPasswordResetProvider = _passwordResetProviders.OfType().First(); + _users = new ConcurrentDictionary(); using var dbContext = _dbProvider.CreateContext(); foreach (var user in dbContext.Users .Include(user => user.Permissions) @@ -101,16 +102,10 @@ namespace Jellyfin.Server.Implementations.Users public event EventHandler>? OnUserUpdated; /// - public IEnumerable Users - { - get { return _users.Values; } - } + public IEnumerable Users => _users.Values; /// - public IEnumerable UsersIds - { - get { return _users.Keys; } - } + public IEnumerable UsersIds => _users.Keys; /// public User? GetUserById(Guid id) From 67f39ed54fe4182783efcbbee6338455ceecf30b Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Tue, 27 Oct 2020 12:28:37 -0400 Subject: [PATCH 0148/1930] Properly remove profile images --- Jellyfin.Server.Implementations/Users/UserManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index efc3f439d8..b39333b5cd 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -724,6 +724,7 @@ namespace Jellyfin.Server.Implementations.Users using var dbContext = _dbProvider.CreateContext(); dbContext.Remove(user.ProfileImage); dbContext.SaveChanges(); + user.ProfileImage = null; } private static bool IsValidUsername(string name) From fd9d325fa8619279fb141297826bb457163bb6ab Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 27 Oct 2020 13:32:59 -0600 Subject: [PATCH 0149/1930] Use JsonConverter --- Jellyfin.Api/Controllers/LiveTvController.cs | 3 +-- Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs | 8 +++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 458c62355c..22f140ea62 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -662,11 +662,10 @@ namespace Jellyfin.Api.Controllers } } - var imageTypes = RequestHelpers.GetImageTypes(body.EnableImageTypes); var dtoOptions = new DtoOptions() .AddItemFields(body.Fields) .AddClientFields(Request) - .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, imageTypes); + .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); } diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index d7eaab30de..5811533936 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -1,4 +1,8 @@ using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; +using MediaBrowser.Model.Entities; namespace Jellyfin.Api.Models.LiveTvDtos { @@ -137,7 +141,9 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// Gets or sets the image types to include in the output. /// Optional. /// - public string? EnableImageTypes { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "EnableImageTypes", Justification = "Imported from ServiceStack")] + public ImageType[] EnableImageTypes { get; set; } = Array.Empty(); /// /// Gets or sets include user data. From 36bae6f030f2bcb2879e8463909a806d6b327569 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 27 Oct 2020 13:38:21 -0600 Subject: [PATCH 0150/1930] Use JsonConverter --- Jellyfin.Api/Controllers/LiveTvController.cs | 3 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 29 ------------------- .../Models/LiveTvDtos/GetProgramsDto.cs | 8 ++++- 3 files changed, 8 insertions(+), 32 deletions(-) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 8c316cfbaf..f0602bbc8a 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -661,9 +661,8 @@ namespace Jellyfin.Api.Controllers } } - var fields = RequestHelpers.GetItemFields(body.Fields); var dtoOptions = new DtoOptions() - .AddItemFields(fields) + .AddItemFields(body.Fields) .AddClientFields(Request) .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index fb5c283f59..1e22ab46ad 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -1,12 +1,9 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Net; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; -using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Http; namespace Jellyfin.Api.Helpers @@ -135,31 +132,5 @@ namespace Jellyfin.Api.Helpers .Select(i => new Guid(i)) .ToArray(); } - - /// - /// Gets the item fields. - /// - /// The fields string. - /// IEnumerable{ItemFields}. - internal static ItemFields[] GetItemFields(string? fields) - { - if (string.IsNullOrEmpty(fields)) - { - return Array.Empty(); - } - - return Split(fields, ',', true) - .Select(v => - { - if (Enum.TryParse(v, true, out ItemFields value)) - { - return (ItemFields?)value; - } - - return null; - }).Where(i => i.HasValue) - .Select(i => i!.Value) - .ToArray(); - } } } diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index d7eaab30de..9d79d28d40 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -1,4 +1,8 @@ using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; +using MediaBrowser.Model.Querying; namespace Jellyfin.Api.Models.LiveTvDtos { @@ -161,6 +165,8 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// Gets or sets specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. /// Optional. /// - public string? Fields { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "Fields", Justification = "Imported from ServiceStack")] + public ItemFields[] Fields { get; set; } = Array.Empty(); } } From 50558ffe3d5259b65fd726a629f3c8c11daec8e7 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 27 Oct 2020 17:57:52 -0600 Subject: [PATCH 0151/1930] Add BaseItemManager --- .../BaseItemManager/BaseItemManager.cs | 86 +++++++++++++++++++ .../BaseItemManager/IBaseItemManager.cs | 29 +++++++ 2 files changed, 115 insertions(+) create mode 100644 MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs create mode 100644 MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs new file mode 100644 index 0000000000..967c6fa154 --- /dev/null +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -0,0 +1,86 @@ +using System; +using System.Linq; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Configuration; + +namespace MediaBrowser.Controller.BaseItemManager +{ + /// + public class BaseItemManager : IBaseItemManager + { + private readonly IServerConfigurationManager _serverConfigurationManager; + + /// + /// Initializes a new instance of the class. + /// + /// Instance of the interface. + public BaseItemManager(IServerConfigurationManager serverConfigurationManager) + { + _serverConfigurationManager = serverConfigurationManager; + } + + /// + public bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name) + { + if (baseItem is Channel) + { + // hack alert + return true; + } + + if (baseItem.SourceType == SourceType.Channel) + { + // hack alert + return !baseItem.EnableMediaSourceDisplay; + } + + var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); + if (typeOptions != null) + { + return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + } + + if (!libraryOptions.EnableInternetProviders) + { + return false; + } + + var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); + + return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + } + + /// + public bool IsImageFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name) + { + if (baseItem is Channel) + { + // hack alert + return true; + } + + if (baseItem.SourceType == SourceType.Channel) + { + // hack alert + return !baseItem.EnableMediaSourceDisplay; + } + + var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); + if (typeOptions != null) + { + return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + } + + if (!libraryOptions.EnableInternetProviders) + { + return false; + } + + var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); + + return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs new file mode 100644 index 0000000000..ee4d3dcdcc --- /dev/null +++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs @@ -0,0 +1,29 @@ +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Configuration; + +namespace MediaBrowser.Controller.BaseItemManager +{ + /// + /// The BaseItem manager. + /// + public interface IBaseItemManager + { + /// + /// Is metadata fetcher enabled. + /// + /// The base item. + /// The library options. + /// The metadata fetcher name. + /// true if metadata fetcher is enabled, else false. + bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name); + + /// + /// Is image fetcher enabled. + /// + /// The base item. + /// The library options. + /// The image fetcher name. + /// true if image fetcher is enabled, else false. + bool IsImageFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name); + } +} \ No newline at end of file From 64b32d329023cdb4dc27f167115f399c376d084a Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 27 Oct 2020 18:01:52 -0600 Subject: [PATCH 0152/1930] Use BaseItemManager --- Jellyfin.Server/CoreAppHost.cs | 2 + MediaBrowser.Controller/Entities/BaseItem.cs | 54 ------------------- .../Manager/ProviderManager.cs | 11 ++-- 3 files changed, 10 insertions(+), 57 deletions(-) diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index c44736447f..cb8ae91f56 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -13,6 +13,7 @@ using Jellyfin.Server.Implementations.Events; using Jellyfin.Server.Implementations.Users; using MediaBrowser.Common.Net; using MediaBrowser.Controller; +using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Events; using MediaBrowser.Controller.Library; @@ -76,6 +77,7 @@ namespace Jellyfin.Server options => options.UseSqlite($"Filename={Path.Combine(ApplicationPaths.DataPath, "jellyfin.db")}")); ServiceCollection.AddEventServices(); + ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 2fc7d45c90..1d141c0e93 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -459,60 +459,6 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public string PrimaryImagePath => this.GetImagePath(ImageType.Primary); - public bool IsMetadataFetcherEnabled(LibraryOptions libraryOptions, string name) - { - if (SourceType == SourceType.Channel) - { - // hack alert - return !EnableMediaSourceDisplay; - } - - var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); - if (typeOptions != null) - { - return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); - } - - if (!libraryOptions.EnableInternetProviders) - { - return false; - } - - var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); - - return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); - } - - public bool IsImageFetcherEnabled(LibraryOptions libraryOptions, string name) - { - if (this is Channel) - { - // hack alert - return true; - } - - if (SourceType == SourceType.Channel) - { - // hack alert - return !EnableMediaSourceDisplay; - } - - var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); - if (typeOptions != null) - { - return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); - } - - if (!libraryOptions.EnableInternetProviders) - { - return false; - } - - var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); - - return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); - } - public virtual bool CanDelete() { if (SourceType == SourceType.Channel) diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index a0c7d4ad09..5cff4761c2 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -13,6 +13,7 @@ using Jellyfin.Data.Events; using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; using MediaBrowser.Controller; +using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -51,6 +52,7 @@ namespace MediaBrowser.Providers.Manager private readonly ILibraryManager _libraryManager; private readonly ISubtitleManager _subtitleManager; private readonly IServerConfigurationManager _configurationManager; + private readonly IBaseItemManager _baseItemManager; private readonly ConcurrentDictionary _activeRefreshes = new ConcurrentDictionary(); private readonly CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource(); private readonly SimplePriorityQueue> _refreshQueue = @@ -74,6 +76,7 @@ namespace MediaBrowser.Providers.Manager /// The filesystem. /// The server application paths. /// The library manager. + /// The BaseItem manager. public ProviderManager( IHttpClientFactory httpClientFactory, ISubtitleManager subtitleManager, @@ -82,7 +85,8 @@ namespace MediaBrowser.Providers.Manager ILogger logger, IFileSystem fileSystem, IServerApplicationPaths appPaths, - ILibraryManager libraryManager) + ILibraryManager libraryManager, + IBaseItemManager baseItemManager) { _logger = logger; _httpClientFactory = httpClientFactory; @@ -92,6 +96,7 @@ namespace MediaBrowser.Providers.Manager _appPaths = appPaths; _libraryManager = libraryManager; _subtitleManager = subtitleManager; + _baseItemManager = baseItemManager; } /// @@ -398,7 +403,7 @@ namespace MediaBrowser.Providers.Manager if (provider is IRemoteMetadataProvider) { - if (!forceEnableInternetMetadata && !item.IsMetadataFetcherEnabled(libraryOptions, provider.Name)) + if (!forceEnableInternetMetadata && !_baseItemManager.IsMetadataFetcherEnabled(item, libraryOptions, provider.Name)) { return false; } @@ -442,7 +447,7 @@ namespace MediaBrowser.Providers.Manager if (provider is IRemoteImageProvider || provider is IDynamicImageProvider) { - if (!item.IsImageFetcherEnabled(libraryOptions, provider.Name)) + if (!_baseItemManager.IsImageFetcherEnabled(item, libraryOptions, provider.Name)) { return false; } From c91f42c7a098a572b47464f550e972dbed2c913f Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Wed, 28 Oct 2020 22:27:08 +0800 Subject: [PATCH 0153/1930] Default output audio bitrate to 128k --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 20 +++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index af0519ffa8..ea012f8376 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -155,7 +155,7 @@ namespace Jellyfin.Api.Helpers return new FileContentResult(Array.Empty(), MimeTypes.GetMimeType("playlist.m3u8")); } - var totalBitrate = state.OutputAudioBitrate ?? 0 + state.OutputVideoBitrate ?? 0; + var totalBitrate = (state.OutputAudioBitrate ?? 0) + (state.OutputVideoBitrate ?? 0); var builder = new StringBuilder(); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 61340cd242..996b1b5c1e 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1380,24 +1380,40 @@ namespace MediaBrowser.Controller.MediaEncoding public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream) { + if (audioStream == null) + { + return null; + } + if (request.AudioBitRate.HasValue) { // Don't encode any higher than this return Math.Min(384000, request.AudioBitRate.Value); } - return null; + // Empty bitrate area is not allow on iOS + // Default audio bitrate to 128K if it is not being requested + // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options + return 128000; } public int? GetAudioBitrateParam(int? audioBitRate, MediaStream audioStream) { + if (audioStream == null) + { + return null; + } + if (audioBitRate.HasValue) { // Don't encode any higher than this return Math.Min(384000, audioBitRate.Value); } - return null; + // Empty bitrate area is not allow on iOS + // Default audio bitrate to 128K if it is not being requested + // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options + return 128000; } public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls) From 981f000437467832d78b1eb36d9c449adb38e814 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 28 Oct 2020 08:40:11 -0600 Subject: [PATCH 0154/1930] Use proper IsApiKey flag --- .../HttpServer/Security/AuthorizationContext.cs | 6 ++++++ Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 16 ++++++++-------- Jellyfin.Api/Auth/CustomAuthenticationHandler.cs | 5 ++--- Jellyfin.Api/Constants/InternalClaimTypes.cs | 5 +++++ Jellyfin.Api/Helpers/ClaimHelpers.cs | 13 +++++++++++++ MediaBrowser.Controller/Net/AuthorizationInfo.cs | 13 +++++++++++-- 6 files changed, 45 insertions(+), 13 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 1f647b78bc..d0fcf06e79 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -183,6 +183,12 @@ namespace Emby.Server.Implementations.HttpServer.Security originalAuthenticationInfo.UserName = authInfo.User.Username; updateToken = true; } + + authInfo.IsApiKey = true; + } + else + { + authInfo.IsApiKey = false; } if (updateToken) diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index c4567d058c..7d68aecf99 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -1,5 +1,4 @@ -using System; -using System.Security.Claims; +using System.Security.Claims; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; @@ -51,6 +50,13 @@ namespace Jellyfin.Api.Auth bool localAccessOnly = false, bool requiredDownloadPermission = false) { + // ApiKey is currently global admin, always allow. + var isApiKey = ClaimHelpers.GetIsApiKey(claimsPrincipal); + if (isApiKey) + { + return true; + } + // Ensure claim has userId. var userId = ClaimHelpers.GetUserId(claimsPrincipal); if (!userId.HasValue) @@ -58,12 +64,6 @@ namespace Jellyfin.Api.Auth return false; } - // UserId of Guid.Empty means token is an apikey. - if (userId.Equals(Guid.Empty)) - { - return true; - } - // Ensure userId links to a valid user. var user = _userManager.GetUserById(userId.Value); if (user == null) diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index ec5d172a21..e8cc389072 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using System.Security.Authentication; using System.Security.Claims; @@ -45,8 +44,7 @@ namespace Jellyfin.Api.Auth { var authorizationInfo = _authService.Authenticate(Request); var role = UserRoles.User; - // UserId of Guid.Empty means token is an apikey. - if (authorizationInfo.UserId.Equals(Guid.Empty) || authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator)) + if (authorizationInfo.IsApiKey || authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator)) { role = UserRoles.Administrator; } @@ -61,6 +59,7 @@ namespace Jellyfin.Api.Auth new Claim(InternalClaimTypes.Client, authorizationInfo.Client), new Claim(InternalClaimTypes.Version, authorizationInfo.Version), new Claim(InternalClaimTypes.Token, authorizationInfo.Token), + new Claim(InternalClaimTypes.IsApiKey, authorizationInfo.IsApiKey.ToString(CultureInfo.InvariantCulture)) }; var identity = new ClaimsIdentity(claims, Scheme.Name); diff --git a/Jellyfin.Api/Constants/InternalClaimTypes.cs b/Jellyfin.Api/Constants/InternalClaimTypes.cs index 4d7c7135d5..8323312e51 100644 --- a/Jellyfin.Api/Constants/InternalClaimTypes.cs +++ b/Jellyfin.Api/Constants/InternalClaimTypes.cs @@ -34,5 +34,10 @@ /// Token. /// public const string Token = "Jellyfin-Token"; + + /// + /// Is Api Key. + /// + public const string IsApiKey = "Jellyfin-IsApiKey"; } } diff --git a/Jellyfin.Api/Helpers/ClaimHelpers.cs b/Jellyfin.Api/Helpers/ClaimHelpers.cs index df235ced25..29e6b4193e 100644 --- a/Jellyfin.Api/Helpers/ClaimHelpers.cs +++ b/Jellyfin.Api/Helpers/ClaimHelpers.cs @@ -63,6 +63,19 @@ namespace Jellyfin.Api.Helpers public static string? GetToken(in ClaimsPrincipal user) => GetClaimValue(user, InternalClaimTypes.Token); + /// + /// Gets a flag specifying whether the request is using an api key. + /// + /// Current claims principal. + /// The flag specifying whether the request is using an api key. + public static bool GetIsApiKey(in ClaimsPrincipal user) + { + var claimValue = GetClaimValue(user, InternalClaimTypes.IsApiKey); + return !string.IsNullOrEmpty(claimValue) + && bool.TryParse(claimValue, out var parsedClaimValue) + && parsedClaimValue; + } + private static string? GetClaimValue(in ClaimsPrincipal user, string name) { return user?.Identities diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs index 735c46ef86..5c642edff2 100644 --- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs +++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs @@ -1,10 +1,11 @@ -#pragma warning disable CS1591 - using System; using Jellyfin.Data.Entities; namespace MediaBrowser.Controller.Net { + /// + /// The request authorization info. + /// public class AuthorizationInfo { /// @@ -43,6 +44,14 @@ namespace MediaBrowser.Controller.Net /// The token. public string Token { get; set; } + /// + /// Gets or sets a value indicating whether the authorization is from an api key. + /// + public bool IsApiKey { get; set; } + + /// + /// Gets or sets the user making the request. + /// public User User { get; set; } } } From 8b83e4e972243db618972e33705b959bf98ca9f4 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 28 Oct 2020 17:57:16 -0600 Subject: [PATCH 0155/1930] Fix tests --- .../Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index 4ea5094b66..33534abd2f 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -128,6 +128,7 @@ namespace Jellyfin.Api.Tests.Auth var authorizationInfo = _fixture.Create(); authorizationInfo.User = _fixture.Create(); authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin); + authorizationInfo.IsApiKey = false; _jellyfinAuthServiceMock.Setup( a => a.Authenticate( From c0383ba07d275daf3241c68e0aad5f493cff44cb Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 28 Oct 2020 20:23:39 -0600 Subject: [PATCH 0156/1930] Add missing slashes in ffmpeg argument. --- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 2afa878f41..c41116fa71 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -371,7 +371,7 @@ namespace Jellyfin.Api.Controllers var baseUrlParam = string.Format( CultureInfo.InvariantCulture, - "\"hls{0}\"", + "\"hls/{0}\"/", Path.GetFileNameWithoutExtension(outputPath)); return string.Format( From 96071ef30d422001d474c749502f44e1ef7641ff Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Wed, 28 Oct 2020 20:26:33 -0600 Subject: [PATCH 0157/1930] Move slash to correct location for quoting --- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index c41116fa71..d7bcf79c1f 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -371,7 +371,7 @@ namespace Jellyfin.Api.Controllers var baseUrlParam = string.Format( CultureInfo.InvariantCulture, - "\"hls/{0}\"/", + "\"hls/{0}/\"", Path.GetFileNameWithoutExtension(outputPath)); return string.Format( From 372f0eb38a9c0803d69d5dc3c4f0fdedd948cd0c Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 11:17:13 -0600 Subject: [PATCH 0158/1930] Remove AddItemFields --- Jellyfin.Api/Controllers/ArtistsController.cs | 6 ++---- .../Controllers/ChannelsController.cs | 8 +++---- Jellyfin.Api/Controllers/GenresController.cs | 3 +-- .../Controllers/InstantMixController.cs | 21 +++++++------------ Jellyfin.Api/Controllers/ItemsController.cs | 6 ++---- Jellyfin.Api/Controllers/LibraryController.cs | 3 +-- Jellyfin.Api/Controllers/LiveTvController.cs | 15 +++++-------- Jellyfin.Api/Controllers/MoviesController.cs | 3 +-- .../Controllers/MusicGenresController.cs | 3 +-- Jellyfin.Api/Controllers/PersonsController.cs | 3 +-- .../Controllers/PlaylistsController.cs | 3 +-- Jellyfin.Api/Controllers/StudiosController.cs | 3 +-- Jellyfin.Api/Controllers/TvShowsController.cs | 12 ++++------- .../Controllers/UserLibraryController.cs | 3 +-- Jellyfin.Api/Controllers/YearsController.cs | 3 +-- Jellyfin.Api/Extensions/DtoExtensions.cs | 16 -------------- 16 files changed, 32 insertions(+), 79 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index c39f442a20..ff1d528474 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -113,8 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -322,8 +321,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index e3b9194694..838fec0776 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -133,11 +133,10 @@ namespace Jellyfin.Api.Controllers { Limit = limit, StartIndex = startIndex, - ChannelIds = new[] { channelId }, + ChannelIds = new[] {channelId}, ParentId = folderId ?? Guid.Empty, OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder), - DtoOptions = new DtoOptions() - .AddItemFields(fields) + DtoOptions = new DtoOptions { Fields = fields } }; foreach (var filter in filters) @@ -213,8 +212,7 @@ namespace Jellyfin.Api.Controllers .Where(i => !string.IsNullOrWhiteSpace(i)) .Select(i => new Guid(i)) .ToArray(), - DtoOptions = new DtoOptions() - .AddItemFields(fields) + DtoOptions = new DtoOptions{ Fields = fields } }; foreach (var filter in filters) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 9e71e82a33..da774f7f18 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -114,8 +114,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index b4a4c35754..f40df0a44d 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -78,8 +78,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -115,8 +114,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(album, user, dtoOptions); @@ -152,8 +150,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(playlist, user, dtoOptions); @@ -188,8 +185,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromGenres(new[] { name }, user, dtoOptions); @@ -225,8 +221,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -262,8 +257,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -299,8 +293,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 43f34abbf9..4543888b21 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -233,8 +233,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -544,8 +543,7 @@ namespace Jellyfin.Api.Controllers { var user = _userManager.GetUserById(userId); var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 865b0010d8..4fbf2a4b45 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -892,8 +892,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request); var query = new InternalItemsQuery(user) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 6c1da075dd..0a5ee2f4d1 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -154,8 +154,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool enableFavoriteSorting = false, [FromQuery] bool addCurrentProgram = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -274,8 +273,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isLibraryItem, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -606,8 +604,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); @@ -662,8 +659,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions() - .AddItemFields(body.Fields) + var dtoOptions = new DtoOptions{ Fields = body.Fields } .AddClientFields(Request) .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); @@ -729,8 +725,7 @@ namespace Jellyfin.Api.Controllers GenreIds = RequestHelpers.GetGuids(genreIds) }; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); return _liveTvManager.GetRecommendedPrograms(query, dtoOptions, CancellationToken.None); diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index bf8279e0c7..10c570893c 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -72,8 +72,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request); var categories = new List(); diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 61d6aaf605..b3589442ef 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -113,8 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 4b367f276c..55f6f5a4c3 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -113,8 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index ecb0e37830..3242896ed8 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -176,8 +176,7 @@ namespace Jellyfin.Api.Controllers items = items.Take(limit.Value).ToArray(); } - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 987fe71950..47b4ce01a3 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -112,8 +112,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 1f68b5d9e3..c53201f1e7 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -82,8 +82,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { - var options = new DtoOptions() - .AddItemFields(fields) + var options = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!); @@ -146,8 +145,7 @@ namespace Jellyfin.Api.Controllers var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); - var options = new DtoOptions() - .AddItemFields(fields!) + var options = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!); @@ -217,8 +215,7 @@ namespace Jellyfin.Api.Controllers List episodes; - var dtoOptions = new DtoOptions() - .AddItemFields(fields!) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); @@ -345,8 +342,7 @@ namespace Jellyfin.Api.Controllers AdjacentTo = adjacentTo }); - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index 3857ee08a7..d412933eac 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -287,8 +287,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 0438f49c08..3a5840559f 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -83,8 +83,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool recursive = true, [FromQuery] bool? enableImages = true) { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions{ Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index a886760c64..6dee9db380 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -13,22 +13,6 @@ namespace Jellyfin.Api.Extensions /// public static class DtoExtensions { - /// - /// Add Dto Item fields. - /// - /// - /// Converted from IHasItemFields. - /// Legacy order: 1. - /// - /// DtoOptions object. - /// Array of item fields. - /// Modified DtoOptions object. - internal static DtoOptions AddItemFields(this DtoOptions dtoOptions, ItemFields[] fields) - { - dtoOptions.Fields = fields; - return dtoOptions; - } - /// /// Add additional fields depending on client. /// From 42c2ab97e7292cb8b61ec5dce2b2201450756d81 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 11:32:02 -0600 Subject: [PATCH 0159/1930] Support IReadOnlyList for JsonCommaDelimitedArrayConverter --- ...JsonCommaDelimitedArrayConverterFactory.cs | 4 +- .../Json/JsonCommaDelimitedArrayTests.cs | 26 +++--- .../JsonCommaDelimitedIReadOnlyListTests.cs | 92 +++++++++++++++++++ ...cBodyModel.cs => GenericBodyArrayModel.cs} | 4 +- .../Models/GenericBodyIReadOnlyListModel.cs | 19 ++++ 5 files changed, 128 insertions(+), 17 deletions(-) create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedIReadOnlyListTests.cs rename tests/Jellyfin.Common.Tests/Models/{GenericBodyModel.cs => GenericBodyArrayModel.cs} (93%) create mode 100644 tests/Jellyfin.Common.Tests/Models/GenericBodyIReadOnlyListModel.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs index b7b1daf76a..24ed3ea19e 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs @@ -21,8 +21,8 @@ namespace MediaBrowser.Common.Json.Converters /// public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { - var structType = typeToConvert.GetElementType(); + var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0]; return (JsonConverter)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType)); } } -} \ No newline at end of file +} diff --git a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs index 16f8a690e6..0d2bdd1af9 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs @@ -11,82 +11,82 @@ namespace Jellyfin.Common.Tests.Json [Fact] public static void Deserialize_String_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { "a", "b", "c" } }; var options = new JsonSerializerOptions(); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a,b,c"" }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a,b,c"" }", options); Assert.Equal(desiredValue.Value, value?.Value); } [Fact] public static void Deserialize_String_Space_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { "a", "b", "c" } }; var options = new JsonSerializerOptions(); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a, b, c"" }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a, b, c"" }", options); Assert.Equal(desiredValue.Value, value?.Value); } [Fact] public static void Deserialize_GenericCommandType_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } }; var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options); Assert.Equal(desiredValue.Value, value?.Value); } [Fact] public static void Deserialize_GenericCommandType_Space_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } }; var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options); Assert.Equal(desiredValue.Value, value?.Value); } [Fact] public static void Deserialize_String_Array_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { "a", "b", "c" } }; var options = new JsonSerializerOptions(); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""a"",""b"",""c""] }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""a"",""b"",""c""] }", options); Assert.Equal(desiredValue.Value, value?.Value); } [Fact] public static void Deserialize_GenericCommandType_Array_Valid_Success() { - var desiredValue = new GenericBodyModel + var desiredValue = new GenericBodyArrayModel { Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } }; var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); - var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options); Assert.Equal(desiredValue.Value, value?.Value); } } -} \ No newline at end of file +} diff --git a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedIReadOnlyListTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedIReadOnlyListTests.cs new file mode 100644 index 0000000000..34ad9bac79 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedIReadOnlyListTests.cs @@ -0,0 +1,92 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Jellyfin.Common.Tests.Models; +using MediaBrowser.Model.Session; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public static class JsonCommaDelimitedIReadOnlyListTests + { + [Fact] + public static void Deserialize_String_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a,b,c"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_String_Space_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""a, b, c"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Space_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp, MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_String_Array_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { "a", "b", "c" } + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""a"",""b"",""c""] }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Array_Valid_Success() + { + var desiredValue = new GenericBodyIReadOnlyListModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": [""MoveUp"", ""MoveDown""] }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + } +} diff --git a/tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs b/tests/Jellyfin.Common.Tests/Models/GenericBodyArrayModel.cs similarity index 93% rename from tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs rename to tests/Jellyfin.Common.Tests/Models/GenericBodyArrayModel.cs index 9a6c382fea..276e1bfbe2 100644 --- a/tests/Jellyfin.Common.Tests/Models/GenericBodyModel.cs +++ b/tests/Jellyfin.Common.Tests/Models/GenericBodyArrayModel.cs @@ -8,7 +8,7 @@ namespace Jellyfin.Common.Tests.Models /// The generic body model. /// /// The value type. - public class GenericBodyModel + public class GenericBodyArrayModel { /// /// Gets or sets the value. @@ -17,4 +17,4 @@ namespace Jellyfin.Common.Tests.Models [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] public T[] Value { get; set; } = default!; } -} \ No newline at end of file +} diff --git a/tests/Jellyfin.Common.Tests/Models/GenericBodyIReadOnlyListModel.cs b/tests/Jellyfin.Common.Tests/Models/GenericBodyIReadOnlyListModel.cs new file mode 100644 index 0000000000..627454b25f --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Models/GenericBodyIReadOnlyListModel.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; + +namespace Jellyfin.Common.Tests.Models +{ + /// + /// The generic body IReadOnlyList model. + /// + /// The value type. + public class GenericBodyIReadOnlyListModel + { + /// + /// Gets or sets the value. + /// + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList Value { get; set; } = default!; + } +} From 11d69fd3b1c25927c1046c4a095a3bd9f29fa722 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 11:36:45 -0600 Subject: [PATCH 0160/1930] Make MrLinter happy --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/ChannelsController.cs | 4 ++-- Jellyfin.Api/Controllers/GenresController.cs | 2 +- Jellyfin.Api/Controllers/InstantMixController.cs | 14 +++++++------- Jellyfin.Api/Controllers/ItemsController.cs | 4 ++-- Jellyfin.Api/Controllers/LibraryController.cs | 2 +- Jellyfin.Api/Controllers/LiveTvController.cs | 10 +++++----- Jellyfin.Api/Controllers/MoviesController.cs | 2 +- Jellyfin.Api/Controllers/MusicGenresController.cs | 2 +- Jellyfin.Api/Controllers/PersonsController.cs | 2 +- Jellyfin.Api/Controllers/PlaylistsController.cs | 2 +- Jellyfin.Api/Controllers/StudiosController.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 8 ++++---- Jellyfin.Api/Controllers/UserLibraryController.cs | 2 +- Jellyfin.Api/Controllers/YearsController.cs | 2 +- 15 files changed, 31 insertions(+), 31 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index ff1d528474..6d5d612cb3 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -113,7 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -321,7 +321,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index 838fec0776..c98c0fdd0d 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -133,7 +133,7 @@ namespace Jellyfin.Api.Controllers { Limit = limit, StartIndex = startIndex, - ChannelIds = new[] {channelId}, + ChannelIds = new[] { channelId }, ParentId = folderId ?? Guid.Empty, OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder), DtoOptions = new DtoOptions { Fields = fields } @@ -212,7 +212,7 @@ namespace Jellyfin.Api.Controllers .Where(i => !string.IsNullOrWhiteSpace(i)) .Select(i => new Guid(i)) .ToArray(), - DtoOptions = new DtoOptions{ Fields = fields } + DtoOptions = new DtoOptions { Fields = fields } }; foreach (var filter in filters) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index da774f7f18..57ec02c1ca 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -114,7 +114,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index f40df0a44d..7591c1b091 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -78,7 +78,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -114,7 +114,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(album, user, dtoOptions); @@ -150,7 +150,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(playlist, user, dtoOptions); @@ -185,7 +185,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromGenres(new[] { name }, user, dtoOptions); @@ -221,7 +221,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -257,7 +257,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); @@ -293,7 +293,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); var items = _musicManager.GetInstantMixFromItem(item, user, dtoOptions); diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 4543888b21..4c91652912 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -233,7 +233,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -543,7 +543,7 @@ namespace Jellyfin.Api.Controllers { var user = _userManager.GetUserById(userId); var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 4fbf2a4b45..e0f0bda26f 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -892,7 +892,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request); var query = new InternalItemsQuery(user) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 0a5ee2f4d1..600cf0a299 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -154,7 +154,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool enableFavoriteSorting = false, [FromQuery] bool addCurrentProgram = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -273,7 +273,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isLibraryItem, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); @@ -604,7 +604,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); @@ -659,7 +659,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions{ Fields = body.Fields } + var dtoOptions = new DtoOptions { Fields = body.Fields } .AddClientFields(Request) .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes); return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false); @@ -725,7 +725,7 @@ namespace Jellyfin.Api.Controllers GenreIds = RequestHelpers.GetGuids(genreIds) }; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); return _liveTvManager.GetRecommendedPrograms(query, dtoOptions, CancellationToken.None); diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index 10c570893c..f041946088 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -72,7 +72,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request); var categories = new List(); diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index b3589442ef..fde4faf773 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -113,7 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 55f6f5a4c3..8ffc47f0ac 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -113,7 +113,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 3242896ed8..a1c8219ca9 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -176,7 +176,7 @@ namespace Jellyfin.Api.Controllers items = items.Take(limit.Value).ToArray(); } - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 47b4ce01a3..a9cba9dba5 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -112,7 +112,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index c53201f1e7..e07e906001 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -82,7 +82,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { - var options = new DtoOptions{ Fields = fields } + var options = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!); @@ -145,7 +145,7 @@ namespace Jellyfin.Api.Controllers var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); - var options = new DtoOptions{ Fields = fields } + var options = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImges, enableUserData, imageTypeLimit, enableImageTypes!); @@ -215,7 +215,7 @@ namespace Jellyfin.Api.Controllers List episodes; - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); @@ -342,7 +342,7 @@ namespace Jellyfin.Api.Controllers AdjacentTo = adjacentTo }); - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index d412933eac..ff68cd497b 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -287,7 +287,7 @@ namespace Jellyfin.Api.Controllers } } - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 3a5840559f..0b4a2776b2 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -83,7 +83,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool recursive = true, [FromQuery] bool? enableImages = true) { - var dtoOptions = new DtoOptions{ Fields = fields } + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); From 2c6b31fc7bf45808ca041e9e76046495b7d351d6 Mon Sep 17 00:00:00 2001 From: Oatavandi Date: Thu, 29 Oct 2020 18:39:38 +0000 Subject: [PATCH 0161/1930] Translated using Weblate (Tamil) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ta/ --- Emby.Server.Implementations/Localization/Core/ta.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index ae38f45e1c..8089fc3042 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -101,7 +101,7 @@ "UserOfflineFromDevice": "{0} இலிருந்து {1} துண்டிக்கப்பட்டுள்ளது", "SubtitleDownloadFailureFromForItem": "வசன வரிகள் {0} இலிருந்து {1} க்கு பதிவிறக்கத் தவறிவிட்டன", "TaskDownloadMissingSubtitlesDescription": "மீத்தரவு உள்ளமைவின் அடிப்படையில் வசன வரிகள் காணாமல் போனதற்கு இணையத்தைத் தேடுகிறது.", - "TaskCleanTranscodeDescription": "டிரான்ஸ்கோட் கோப்புகளை ஒரு நாளுக்கு மேல் பழையதாக நீக்குகிறது.", + "TaskCleanTranscodeDescription": "ஒரு நாளைக்கு மேற்பட்ட பழைய டிரான்ஸ்கோட் கோப்புகளை நீக்குகிறது.", "TaskUpdatePluginsDescription": "தானாகவே புதுப்பிக்க கட்டமைக்கப்பட்ட உட்செருகிகளுக்கான புதுப்பிப்புகளை பதிவிறக்குகிறது மற்றும் நிறுவுகிறது.", "TaskRefreshPeopleDescription": "உங்கள் ஊடக நூலகத்தில் உள்ள நடிகர்கள் மற்றும் இயக்குனர்களுக்கான மீத்தரவை புதுப்பிக்கும்.", "TaskCleanLogsDescription": "{0} நாட்களுக்கு மேல் இருக்கும் பதிவு கோப்புகளை நீக்கும்.", From 429e59fb818e605339eab2b368ceaaf2a1bd5c2b Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 13:55:57 -0600 Subject: [PATCH 0162/1930] Fix null reference --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 996b1b5c1e..1d733479cc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -3084,7 +3084,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } - var whichCodec = videoStream.Codec.ToLowerInvariant(); + var whichCodec = videoStream.Codec?.ToLowerInvariant(); switch (whichCodec) { case "avc": From 3568c5f39b7429544c8a26677f400cfee2eaa7fd Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 13:56:29 -0600 Subject: [PATCH 0163/1930] Fix early filestream close --- .../LiveTv/TunerHosts/SharedHttpStream.cs | 2 +- Jellyfin.Api/Controllers/LiveTvController.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 6c10fca8c6..29ab1cd40b 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -55,7 +55,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var typeName = GetType().Name; Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); - using var response = await _httpClientFactory.CreateClient(NamedClient.Default) + var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None) .ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 22f140ea62..2cc2f0e74d 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1220,11 +1220,11 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - await using var memoryStream = new MemoryStream(); await new ProgressiveFileCopier(liveStreamInfo, null, _transcodingJobHelper, CancellationToken.None) - .WriteToAsync(memoryStream, CancellationToken.None) + .WriteToAsync(Response.Body, CancellationToken.None) .ConfigureAwait(false); - return File(memoryStream, MimeTypes.GetMimeType("file." + container)); + Response.ContentType = MimeTypes.GetMimeType("file." + container); + return Ok(); } private void AssertUserCanManageLiveTv() From 0c674b496f3f4503b6d45c763aadc9b1c5d2735d Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 13:58:47 -0600 Subject: [PATCH 0164/1930] Add stream disposal comment. --- .../LiveTv/TunerHosts/SharedHttpStream.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 29ab1cd40b..10e5eab73c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -55,6 +55,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var typeName = GetType().Name; Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url); + // Response stream is disposed manually. var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None) .ConfigureAwait(false); From ef43878bbc204a169adb0ad0639cc143cfd2db11 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 29 Oct 2020 16:11:40 -0600 Subject: [PATCH 0165/1930] Support IReadOnlyList in CommaDelimitedArrayModelBinder --- Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index 208566dc8e..4f012cab20 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Api.ModelBinders public Task BindModelAsync(ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); - var elementType = bindingContext.ModelType.GetElementType(); + var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); if (valueProviderResult.Length > 1) From d887e424052e3f57b7578d9dc7f62bcd8085fcbe Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 29 Oct 2020 19:16:39 -0400 Subject: [PATCH 0166/1930] Fix possible NullReferenceException --- Jellyfin.Server.Implementations/Users/UserManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 437833aa38..5f25c7737a 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -460,7 +460,7 @@ namespace Jellyfin.Server.Implementations.Users // the authentication provider might have created it user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase)); - if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy) + if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null) { UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy()); From 72263613d039ccfb70b70bae9f53da53bc8757c4 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 29 Oct 2020 20:30:33 -0400 Subject: [PATCH 0167/1930] Convert some code in UserManager to async --- Jellyfin.Api/Controllers/ImageController.cs | 6 ++--- Jellyfin.Api/Controllers/UserController.cs | 18 ++++++--------- .../Users/UserManager.cs | 22 +++++++++---------- .../Library/IUserManager.cs | 9 +++++--- 4 files changed, 26 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 05efe23553..4a67c1aede 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -109,7 +109,7 @@ namespace Jellyfin.Api.Controllers var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username); if (user.ProfileImage != null) { - _userManager.ClearProfileImage(user); + await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); } user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType))); @@ -138,7 +138,7 @@ namespace Jellyfin.Api.Controllers [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] - public ActionResult DeleteUserImage( + public async Task DeleteUserImage( [FromRoute, Required] Guid userId, [FromRoute, Required] ImageType imageType, [FromRoute] int? index = null) @@ -158,7 +158,7 @@ namespace Jellyfin.Api.Controllers _logger.LogError(e, "Error deleting user profile image:"); } - _userManager.ClearProfileImage(user); + await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); return NoContent(); } diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 50bb8bb2aa..7b0897bfb9 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -381,17 +381,13 @@ namespace Jellyfin.Api.Controllers var user = _userManager.GetUserById(userId); - if (string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal)) - { - await _userManager.UpdateUserAsync(user).ConfigureAwait(false); - _userManager.UpdateConfiguration(user.Id, updateUser.Configuration); - } - else + if (!string.Equals(user.Username, updateUser.Name, StringComparison.Ordinal)) { await _userManager.RenameUser(user, updateUser.Name).ConfigureAwait(false); - _userManager.UpdateConfiguration(updateUser.Id, updateUser.Configuration); } + await _userManager.UpdateConfigurationAsync(user.Id, updateUser.Configuration).ConfigureAwait(false); + return NoContent(); } @@ -409,7 +405,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status403Forbidden)] - public ActionResult UpdateUserPolicy( + public async Task UpdateUserPolicy( [FromRoute, Required] Guid userId, [FromBody] UserPolicy newPolicy) { @@ -447,7 +443,7 @@ namespace Jellyfin.Api.Controllers _sessionManager.RevokeUserTokens(user.Id, currentToken); } - _userManager.UpdatePolicy(userId, newPolicy); + await _userManager.UpdatePolicyAsync(userId, newPolicy).ConfigureAwait(false); return NoContent(); } @@ -464,7 +460,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] - public ActionResult UpdateUserConfiguration( + public async Task UpdateUserConfiguration( [FromRoute, Required] Guid userId, [FromBody] UserConfiguration userConfig) { @@ -473,7 +469,7 @@ namespace Jellyfin.Api.Controllers return Forbid("User configuration update not allowed"); } - _userManager.UpdateConfiguration(userId, userConfig); + await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false); return NoContent(); } diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index b41a5ee5ca..40b89ed284 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -434,9 +434,7 @@ namespace Jellyfin.Server.Implementations.Users if (authenticationProvider is IHasNewUserPolicy hasNewUserPolicy && user != null) { - UpdatePolicy(user.Id, hasNewUserPolicy.GetNewUserPolicy()); - - await UpdateUserAsync(user).ConfigureAwait(false); + await UpdatePolicyAsync(user.Id, hasNewUserPolicy.GetNewUserPolicy()).ConfigureAwait(false); } } } @@ -615,9 +613,9 @@ namespace Jellyfin.Server.Implementations.Users } /// - public void UpdateConfiguration(Guid userId, UserConfiguration config) + public async Task UpdateConfigurationAsync(Guid userId, UserConfiguration config) { - using var dbContext = _dbProvider.CreateContext(); + await using var dbContext = _dbProvider.CreateContext(); var user = dbContext.Users .Include(u => u.Permissions) .Include(u => u.Preferences) @@ -644,13 +642,13 @@ namespace Jellyfin.Server.Implementations.Users user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes); dbContext.Update(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync().ConfigureAwait(false); } /// - public void UpdatePolicy(Guid userId, UserPolicy policy) + public async Task UpdatePolicyAsync(Guid userId, UserPolicy policy) { - using var dbContext = _dbProvider.CreateContext(); + await using var dbContext = _dbProvider.CreateContext(); var user = dbContext.Users .Include(u => u.Permissions) .Include(u => u.Preferences) @@ -715,15 +713,15 @@ namespace Jellyfin.Server.Implementations.Users user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders); dbContext.Update(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync().ConfigureAwait(false); } /// - public void ClearProfileImage(User user) + public async Task ClearProfileImageAsync(User user) { - using var dbContext = _dbProvider.CreateContext(); + await using var dbContext = _dbProvider.CreateContext(); dbContext.Remove(user.ProfileImage); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync().ConfigureAwait(false); user.ProfileImage = null; } diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs index 6a4f5cf679..8fd3b8c347 100644 --- a/MediaBrowser.Controller/Library/IUserManager.cs +++ b/MediaBrowser.Controller/Library/IUserManager.cs @@ -158,7 +158,8 @@ namespace MediaBrowser.Controller.Library /// /// The user's Id. /// The request containing the new user configuration. - void UpdateConfiguration(Guid userId, UserConfiguration config); + /// A task representing the update. + Task UpdateConfigurationAsync(Guid userId, UserConfiguration config); /// /// This method updates the user's policy. @@ -167,12 +168,14 @@ namespace MediaBrowser.Controller.Library /// /// The user's Id. /// The request containing the new user policy. - void UpdatePolicy(Guid userId, UserPolicy policy); + /// A task representing the update. + Task UpdatePolicyAsync(Guid userId, UserPolicy policy); /// /// Clears the user's profile image. /// /// The user. - void ClearProfileImage(User user); + /// A task representing the clearing of the profile image. + Task ClearProfileImageAsync(User user); } } From face3f8c6538624ab96e03801e958df26b708a7a Mon Sep 17 00:00:00 2001 From: Greenback Date: Fri, 30 Oct 2020 13:54:37 +0000 Subject: [PATCH 0168/1930] Updating to latest network code. --- .../Configuration/NetworkConfiguration.cs | 28 ++++---- .../Jellyfin.Networking.csproj | 10 +-- Jellyfin.Networking/Manager/NetworkManager.cs | 67 ++++++++++++++----- 3 files changed, 68 insertions(+), 37 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index aa75ac305d..301e432511 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -10,8 +10,6 @@ namespace Jellyfin.Networking.Configuration /// public class NetworkConfiguration { - private string _baseUrl = string.Empty; - /// /// Gets the default http port. /// @@ -22,10 +20,12 @@ namespace Jellyfin.Networking.Configuration /// public const int DefaultHttpsPort = 8920; + private string _baseUrl = string.Empty; + /// /// Gets or sets a value indicating whether the server should force connections over HTTPS. /// - public bool RequireHttps { get; set; } = false; + public bool RequireHttps { get; set; } /// /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. @@ -50,7 +50,7 @@ namespace Jellyfin.Networking.Configuration } // Normalize the end of the string - if (value[value.Length - 1] == '/') + if (value[^1] == '/') { // If baseUrl was configured with a trailing slash, remove it for consistency value = value.Remove(value.Length - 1); @@ -85,7 +85,7 @@ namespace Jellyfin.Networking.Configuration /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be /// provided for and . /// - public bool EnableHttps { get; set; } = false; + public bool EnableHttps { get; set; } /// /// Gets or sets the public mapped port. @@ -96,7 +96,7 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.. /// - public bool UPnPCreateHttpPortMap { get; set; } = false; + public bool UPnPCreateHttpPortMap { get; set; } /// /// Gets or sets the UDPPortRange @@ -105,12 +105,12 @@ namespace Jellyfin.Networking.Configuration public string UDPPortRange { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether IPV6 capability is enabled. + /// Gets or sets a value indicating whether gets or sets IPV6 capability.. /// - public bool EnableIPV6 { get; set; } = false; + public bool EnableIPV6 { get; set; } /// - /// Gets or sets a value indicating whether IPV6 capability is enabled. + /// Gets or sets a value indicating whether gets or sets IPV4 capability.. /// public bool EnableIPV4 { get; set; } = true; @@ -118,7 +118,7 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.. /// - public bool EnableSSDPTracing { get; set; } = false; + public bool EnableSSDPTracing { get; set; } /// /// Gets or sets the SSDPTracingFilter @@ -162,7 +162,7 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. /// Depending on the address range implemented ULA ranges might not be used.. /// - public bool TrustAllIP6Interfaces { get; set; } = false; + public bool TrustAllIP6Interfaces { get; set; } /// /// Gets or sets the ports that HDHomerun uses.. @@ -178,7 +178,7 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.. /// - public bool AutoDiscoveryTracing { get; set; } = false; + public bool AutoDiscoveryTracing { get; set; } /// /// Gets or sets a value indicating whether Autodiscovery is enabled.. @@ -193,12 +193,12 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist.. /// - public bool IsRemoteIPFilterBlacklist { get; set; } = false; + public bool IsRemoteIPFilterBlacklist { get; set; } /// /// Gets or sets a value indicating whether to enable automatic port forwarding.. /// - public bool EnableUPnP { get; set; } = false; + public bool EnableUPnP { get; set; } /// /// Gets or sets a value indicating whether access outside of the LAN is permitted.. diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index 7f01f149ec..f9cdfc2907 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -1,7 +1,5 @@ - Jellyfin.Networking - Library netstandard2.1 false true @@ -15,7 +13,8 @@ - + + @@ -25,10 +24,7 @@ - - - - + diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 6d6b7ebc4e..616774d043 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,3 +1,5 @@ +#pragma warning disable CA1021 // Avoid out parameters + using System; using System.Collections.Generic; using System.Globalization; @@ -27,7 +29,7 @@ namespace Jellyfin.Networking.Manager private readonly Dictionary _interfaceNames; /// - /// Threading lock for network interfaces. + /// Threading lock for network properties. /// private readonly object _intLock = new object(); @@ -104,7 +106,7 @@ namespace Jellyfin.Networking.Manager _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); - _interfaceAddresses = new NetCollection(unique: false); + _interfaceAddresses = new NetCollection(); _macAddresses = new List(); _interfaceNames = new Dictionary(); _publishedServerUrls = new Dictionary(); @@ -199,7 +201,7 @@ namespace Jellyfin.Networking.Manager /// public bool IsExcluded(IPAddress ip) { - return _excludedSubnets.Contains(ip); + return _excludedSubnets.ContainsAddress(ip); } /// @@ -227,7 +229,7 @@ namespace Jellyfin.Networking.Manager { if (bracketed) { - AddToCollection(col, v.Substring(1, v.Length - 2)); + AddToCollection(col, v[1..^1]); } } else if (v.StartsWith('!')) @@ -329,6 +331,11 @@ namespace Jellyfin.Networking.Manager public string GetBindInterface(IPObject source, out int? port) { port = null; + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + // Do we have a source? bool haveSource = !source.Address.Equals(IPAddress.None); bool isExternal = false; @@ -470,7 +477,7 @@ namespace Jellyfin.Networking.Manager } // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); + return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address); } /// @@ -495,7 +502,7 @@ namespace Jellyfin.Networking.Manager /// public bool IsExcludedInterface(IPAddress address) { - return _bindExclusions.Contains(address); + return _bindExclusions.ContainsAddress(address); } /// @@ -503,7 +510,7 @@ namespace Jellyfin.Networking.Manager { if (filter == null) { - return NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)); + return _lanSubnets.Exclude(_excludedSubnets).AsNetworks(); } return _lanSubnets.Exclude(filter); @@ -512,7 +519,7 @@ namespace Jellyfin.Networking.Manager /// public bool IsValidInterfaceAddress(IPAddress address) { - return _interfaceAddresses.Contains(address); + return _interfaceAddresses.ContainsAddress(address); } /// @@ -611,12 +618,32 @@ namespace Jellyfin.Networking.Manager } } - private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) + /// + /// Trys to identify the string and return an object of that class. + /// + /// String to parse. + /// IPObject to return. + /// True if the value parsed successfully. + private static bool TryParse(string addr, out IPObject result) { - if (evt.Key.Equals("network", StringComparison.Ordinal)) + if (!string.IsNullOrEmpty(addr)) { - UpdateSettings(evt.NewConfiguration); + // Is it an IP address + if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) + { + result = nw; + return true; + } + + if (IPHost.TryParse(addr, out IPHost h)) + { + result = h; + return true; + } } + + result = IPNetAddress.None; + return false; } /// @@ -625,7 +652,7 @@ namespace Jellyfin.Networking.Manager /// /// Address to convert. /// URI save conversion of the address. - private string FormatIP6String(IPAddress address) + private static string FormatIP6String(IPAddress address) { var str = address.ToString(); if (address.AddressFamily == AddressFamily.InterNetworkV6) @@ -643,6 +670,14 @@ namespace Jellyfin.Networking.Manager return str; } + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) + { + if (evt.Key.Equals("network", StringComparison.Ordinal)) + { + UpdateSettings(evt.NewConfiguration); + } + } + /// /// Checks the string to see if it matches any interface names. /// @@ -701,7 +736,7 @@ namespace Jellyfin.Networking.Manager } } } - else if (NetCollection.TryParse(token, out IPObject obj)) + else if (TryParse(token, out IPObject obj)) { if (!IsIP6Enabled) { @@ -896,7 +931,7 @@ namespace Jellyfin.Networking.Manager // Create lists from user settings. _lanSubnets = CreateIPCollection(subnets); - _excludedSubnets = NetCollection.AsNetworks(CreateIPCollection(subnets, true)); + _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks(); // If no LAN addresses are specified - all private subnets are deemed to be the LAN _usingPrivateAddresses = _lanSubnets.Count == 0; @@ -946,7 +981,7 @@ namespace Jellyfin.Networking.Manager _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets); _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets); - _logger.LogInformation("Using LAN addresses: {0}", NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets))); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks()); } } @@ -986,7 +1021,7 @@ namespace Jellyfin.Networking.Manager { if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { - IPNetAddress nw = new IPNetAddress(info.Address, info.IPv4Mask) + IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) { // Keep the number of gateways on this interface, along with its index. Tag = ipProperties.GetIPv4Properties().Index From ec57eeff2b53081e28118fa29c435d2352cdb636 Mon Sep 17 00:00:00 2001 From: Greenback Date: Fri, 30 Oct 2020 14:06:11 +0000 Subject: [PATCH 0169/1930] Updated to latest version of code. --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- .../Middleware/IpBasedAccessValidationMiddleware.cs | 2 +- RSSDP/SsdpDevicePublisher.cs | 4 ++-- RSSDP/SsdpRootDevice.cs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index a644d2c8cc..504bde996b 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -297,7 +297,7 @@ namespace Emby.Dlna.Main CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri, // Must point to the URL that serves your devices UPnP description document. Address = address.Address, - SubnetMask = address.Mask, + PrefixLength = address.PrefixLength, FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 6f636819fc..c3533d7956 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -52,7 +52,7 @@ namespace Jellyfin.Server.Middleware if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp)) { // remoteAddressFilter is a whitelist or blacklist. - bool isListed = remoteAddressFilter.Contains(remoteIp); + bool isListed = remoteAddressFilter.ContainsAddress(remoteIp); if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist) { // Black list, so flip over. diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index ca382c905a..ae175d8c9d 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -302,8 +302,8 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { var root = device.ToRootDevice(); - var source = new IPNetAddress(root.Address, root.SubnetMask); - var destination = new IPNetAddress(remoteEndPoint.Address, root.SubnetMask); + var source = new IPNetAddress(root.Address, root.PrefixLength); + var destination = new IPNetAddress(remoteEndPoint.Address, root.PrefixLength); if (!_sendOnlyMatchedHost || source.NetworkAddress.Equals(destination.NetworkAddress)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); diff --git a/RSSDP/SsdpRootDevice.cs b/RSSDP/SsdpRootDevice.cs index 8937ec331f..d5abe4a4ca 100644 --- a/RSSDP/SsdpRootDevice.cs +++ b/RSSDP/SsdpRootDevice.cs @@ -45,9 +45,9 @@ namespace Rssdp public IPAddress Address { get; set; } /// - /// Gets or sets the SubnetMask used to check if the received message from same interface with this device/tree. Required. + /// Gets or sets the prefix length used to check if the received message from same interface with this device/tree. Required. /// - public IPAddress SubnetMask { get; set; } + public byte PrefixLength { get; set; } /// /// The base URL to use for all relative url's provided in other propertise (and those of child devices). Optional. From c25ec72864768633417e06e6e34b1a2af7cc0df0 Mon Sep 17 00:00:00 2001 From: Greenback Date: Fri, 30 Oct 2020 14:48:33 +0000 Subject: [PATCH 0170/1930] Updated libraries. --- Jellyfin.Networking/Jellyfin.Networking.csproj | 2 +- MediaBrowser.Common/MediaBrowser.Common.csproj | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index f9cdfc2907..330d36a80d 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -13,7 +13,7 @@ - + diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index d992f6b092..0b8f431c04 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -20,9 +20,9 @@ - + - + From 00f0c14d7b953111e0bacc134b161c329b8e5fa1 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Sat, 31 Oct 2020 16:09:22 +0800 Subject: [PATCH 0171/1930] respect music quality settings when transcoding --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 12 +++++++++--- Jellyfin.Api/Controllers/MediaInfoController.cs | 4 ++-- Jellyfin.Api/Controllers/UniversalAudioController.cs | 8 +++++--- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 4 ++-- MediaBrowser.Model/Dlna/AudioOptions.cs | 4 ++-- MediaBrowser.Model/Dlna/DeviceProfile.cs | 4 ++-- MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs | 2 +- 7 files changed, 23 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 1153a601e7..e07690e110 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -295,6 +295,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Whether to break on non key frames. /// Optional. Specify a specific audio sample rate, e.g. 44100. /// Optional. The maximum audio bit depth. + /// Optional. The maximum streaming bitrate. /// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults. /// Optional. Specify a specific number of audio channels to encode to, e.g. 2. /// Optional. Specify a maximum number of audio channels to encode to, e.g. 2. @@ -351,6 +352,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? breakOnNonKeyFrames, [FromQuery] int? audioSampleRate, [FromQuery] int? maxAudioBitDepth, + [FromQuery] int? maxStreamingBitrate, [FromQuery] int? audioBitRate, [FromQuery] int? audioChannels, [FromQuery] int? maxAudioChannels, @@ -403,7 +405,7 @@ namespace Jellyfin.Api.Controllers BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, AudioSampleRate = audioSampleRate, MaxAudioChannels = maxAudioChannels, - AudioBitRate = audioBitRate, + AudioBitRate = audioBitRate ?? maxStreamingBitrate, MaxAudioBitDepth = maxAudioBitDepth, AudioChannels = audioChannels, Profile = profile, @@ -623,6 +625,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Whether to break on non key frames. /// Optional. Specify a specific audio sample rate, e.g. 44100. /// Optional. The maximum audio bit depth. + /// Optional. The maximum streaming bitrate. /// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults. /// Optional. Specify a specific number of audio channels to encode to, e.g. 2. /// Optional. Specify a maximum number of audio channels to encode to, e.g. 2. @@ -677,6 +680,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? breakOnNonKeyFrames, [FromQuery] int? audioSampleRate, [FromQuery] int? maxAudioBitDepth, + [FromQuery] int? maxStreamingBitrate, [FromQuery] int? audioBitRate, [FromQuery] int? audioChannels, [FromQuery] int? maxAudioChannels, @@ -729,7 +733,7 @@ namespace Jellyfin.Api.Controllers BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, AudioSampleRate = audioSampleRate, MaxAudioChannels = maxAudioChannels, - AudioBitRate = audioBitRate, + AudioBitRate = audioBitRate ?? maxStreamingBitrate, MaxAudioBitDepth = maxAudioBitDepth, AudioChannels = audioChannels, Profile = profile, @@ -959,6 +963,7 @@ namespace Jellyfin.Api.Controllers /// Optional. Whether to break on non key frames. /// Optional. Specify a specific audio sample rate, e.g. 44100. /// Optional. The maximum audio bit depth. + /// Optional. The maximum streaming bitrate. /// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults. /// Optional. Specify a specific number of audio channels to encode to, e.g. 2. /// Optional. Specify a maximum number of audio channels to encode to, e.g. 2. @@ -1017,6 +1022,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? breakOnNonKeyFrames, [FromQuery] int? audioSampleRate, [FromQuery] int? maxAudioBitDepth, + [FromQuery] int? maxStreamingBitrate, [FromQuery] int? audioBitRate, [FromQuery] int? audioChannels, [FromQuery] int? maxAudioChannels, @@ -1069,7 +1075,7 @@ namespace Jellyfin.Api.Controllers BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, AudioSampleRate = audioSampleRate, MaxAudioChannels = maxAudioChannels, - AudioBitRate = audioBitRate, + AudioBitRate = audioBitRate ?? maxStreamingBitrate, MaxAudioBitDepth = maxAudioBitDepth, AudioChannels = audioChannels, Profile = profile, diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index 4c21999b1b..186024585b 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -104,7 +104,7 @@ namespace Jellyfin.Api.Controllers public async Task> GetPostedPlaybackInfo( [FromRoute, Required] Guid itemId, [FromQuery] Guid? userId, - [FromQuery] long? maxStreamingBitrate, + [FromQuery] int? maxStreamingBitrate, [FromQuery] long? startTimeTicks, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, @@ -234,7 +234,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? openToken, [FromQuery] Guid? userId, [FromQuery] string? playSessionId, - [FromQuery] long? maxStreamingBitrate, + [FromQuery] int? maxStreamingBitrate, [FromQuery] long? startTimeTicks, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index df20a92b3d..1cfdb9d8b4 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -76,6 +76,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum number of audio channels. /// Optional. The number of how many audio channels to transcode to. /// Optional. The maximum streaming bitrate. + /// Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults. /// Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms. /// Optional. The container to transcode to. /// Optional. The transcoding protocol. @@ -104,7 +105,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? audioCodec, [FromQuery] int? maxAudioChannels, [FromQuery] int? transcodingAudioChannels, - [FromQuery] long? maxStreamingBitrate, + [FromQuery] int? maxStreamingBitrate, + [FromQuery] int? audioBitRate, [FromQuery] long? startTimeTicks, [FromQuery] string? transcodingContainer, [FromQuery] string? transcodingProtocol, @@ -212,7 +214,7 @@ namespace Jellyfin.Api.Controllers AudioSampleRate = maxAudioSampleRate, MaxAudioChannels = maxAudioChannels, MaxAudioBitDepth = maxAudioBitDepth, - AudioChannels = isStatic ? (int?)null : Convert.ToInt32(Math.Min(maxStreamingBitrate ?? 192000, int.MaxValue)), + AudioBitRate = audioBitRate ?? maxStreamingBitrate, StartTimeTicks = startTimeTicks, SubtitleMethod = SubtitleDeliveryMethod.Hls, RequireAvc = true, @@ -244,7 +246,7 @@ namespace Jellyfin.Api.Controllers BreakOnNonKeyFrames = breakOnNonKeyFrames, AudioSampleRate = maxAudioSampleRate, MaxAudioChannels = maxAudioChannels, - AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(maxStreamingBitrate ?? 192000, int.MaxValue)), + AudioBitRate = isStatic ? (int?)null : (audioBitRate ?? maxStreamingBitrate), MaxAudioBitDepth = maxAudioBitDepth, AudioChannels = maxAudioChannels, CopyTimestamps = true, diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index e78f63b256..0d8315dee1 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -166,7 +166,7 @@ namespace Jellyfin.Api.Helpers MediaSourceInfo mediaSource, DeviceProfile profile, AuthorizationInfo auth, - long? maxBitrate, + int? maxBitrate, long startTimeTicks, string mediaSourceId, int? audioStreamIndex, @@ -551,7 +551,7 @@ namespace Jellyfin.Api.Helpers } } - private long? GetMaxBitrate(long? clientMaxBitrate, User user, string ipAddress) + private int? GetMaxBitrate(int? clientMaxBitrate, User user, string ipAddress) { var maxBitrate = clientMaxBitrate; var remoteClientMaxBitrate = user.RemoteClientBitrateLimit ?? 0; diff --git a/MediaBrowser.Model/Dlna/AudioOptions.cs b/MediaBrowser.Model/Dlna/AudioOptions.cs index 67e4ffe03e..bbb8bf4263 100644 --- a/MediaBrowser.Model/Dlna/AudioOptions.cs +++ b/MediaBrowser.Model/Dlna/AudioOptions.cs @@ -49,7 +49,7 @@ namespace MediaBrowser.Model.Dlna /// /// The application's configured quality setting. /// - public long? MaxBitrate { get; set; } + public int? MaxBitrate { get; set; } /// /// Gets or sets the context. @@ -67,7 +67,7 @@ namespace MediaBrowser.Model.Dlna /// Gets the maximum bitrate. /// /// System.Nullable<System.Int32>. - public long? GetMaxBitrate(bool isAudio) + public int? GetMaxBitrate(bool isAudio) { if (MaxBitrate.HasValue) { diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 44412f3e41..e842efead9 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -62,9 +62,9 @@ namespace MediaBrowser.Model.Dlna public int? MaxIconHeight { get; set; } - public long? MaxStreamingBitrate { get; set; } + public int? MaxStreamingBitrate { get; set; } - public long? MaxStaticBitrate { get; set; } + public int? MaxStaticBitrate { get; set; } public int? MusicStreamingTranscodingBitrate { get; set; } diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs index 83bda5d569..a8ea405e28 100644 --- a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs +++ b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs @@ -37,7 +37,7 @@ namespace MediaBrowser.Model.MediaInfo public string PlaySessionId { get; set; } - public long? MaxStreamingBitrate { get; set; } + public int? MaxStreamingBitrate { get; set; } public long? StartTimeTicks { get; set; } From 7f8a73d8e9a7d07f2f528bcf41998bed4b130cca Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 31 Oct 2020 12:49:41 +0100 Subject: [PATCH 0172/1930] Http1AndHttp2 is the default, no need to explicitly enable it --- Jellyfin.Server/Program.cs | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 5573c04395..97a51c202b 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -290,23 +290,19 @@ namespace Jellyfin.Server { _logger.LogInformation("Kestrel listening on {IpAddress}", address); options.Listen(address, appHost.HttpPort); + if (appHost.ListenWithHttps) { - options.Listen(address, appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(appHost.Certificate); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); + options.Listen( + address, + appHost.HttpsPort, + listenOptions => listenOptions.UseHttps(appHost.Certificate)); } else if (builderContext.HostingEnvironment.IsDevelopment()) { try { - options.Listen(address, appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); + options.Listen(address, appHost.HttpsPort, listenOptions => listenOptions.UseHttps()); } catch (InvalidOperationException ex) { @@ -322,21 +318,15 @@ namespace Jellyfin.Server if (appHost.ListenWithHttps) { - options.ListenAnyIP(appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(appHost.Certificate); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); + options.ListenAnyIP( + appHost.HttpsPort, + listenOptions => listenOptions.UseHttps(appHost.Certificate)); } else if (builderContext.HostingEnvironment.IsDevelopment()) { try { - options.ListenAnyIP(appHost.HttpsPort, listenOptions => - { - listenOptions.UseHttps(); - listenOptions.Protocols = HttpProtocols.Http1AndHttp2; - }); + options.ListenAnyIP(appHost.HttpsPort, listenOptions => listenOptions.UseHttps()); } catch (InvalidOperationException ex) { From d34be6faf4cf2d8d916593e28cc7d0da5ec3a40a Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Sun, 1 Nov 2020 00:33:38 +0800 Subject: [PATCH 0173/1930] fix aac directstreaming --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 5 +++-- MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs | 5 +++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 996b1b5c1e..33256e4bf2 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2675,9 +2675,10 @@ namespace MediaBrowser.Controller.MediaEncoding state.MediaSource = mediaSource; var request = state.BaseRequest; - if (!string.IsNullOrWhiteSpace(request.AudioCodec)) + var supportedAudioCodecs = state.SupportedAudioCodecs; + if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0) { - var supportedAudioCodecsList = request.AudioCodec.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + var supportedAudioCodecsList = supportedAudioCodecs.ToList(); ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 6cd0c70d2f..6e9362cd14 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -287,6 +287,11 @@ namespace MediaBrowser.Controller.MediaEncoding return BaseRequest.AudioChannels; } + if (BaseRequest.TranscodingMaxAudioChannels.HasValue) + { + return BaseRequest.TranscodingMaxAudioChannels; + } + if (!string.IsNullOrEmpty(codec)) { var value = BaseRequest.GetOption(codec, "audiochannels"); From 83af636c610744903b709117f7f2a7b7e34da1f0 Mon Sep 17 00:00:00 2001 From: Greenback Date: Sat, 31 Oct 2020 18:21:46 +0000 Subject: [PATCH 0174/1930] Updated with new NetManager --- Emby.Dlna/Main/DlnaEntryPoint.cs | 4 +- .../HdHomerun/HdHomerunUdpStream.cs | 25 +- .../Jellyfin.Networking.csproj | 4 - Jellyfin.Networking/Manager/NetworkManager.cs | 49 +- .../IpBasedAccessValidationMiddleware.cs | 3 +- .../Middleware/LanFilteringMiddleware.cs | 1 - Jellyfin.Server/Program.cs | 4 +- .../MediaBrowser.Common.csproj | 1 - MediaBrowser.Common/Net/INetworkManager.cs | 4 +- MediaBrowser.Common/Net/IPHost.cs | 447 ++++++++++++++++++ MediaBrowser.Common/Net/IPNetAddress.cs | 277 +++++++++++ MediaBrowser.Common/Net/IPObject.cs | 395 ++++++++++++++++ MediaBrowser.Common/Net/NetworkExtensions.cs | 254 ++++++++++ MediaBrowser.sln | 7 + RSSDP/SsdpDevicePublisher.cs | 1 - .../Jellyfin.Networking.Tests.csproj | 28 ++ .../NetworkTesting/UnitTesting.cs | 425 +++++++++++++++++ 17 files changed, 1895 insertions(+), 34 deletions(-) create mode 100644 MediaBrowser.Common/Net/IPHost.cs create mode 100644 MediaBrowser.Common/Net/IPNetAddress.cs create mode 100644 MediaBrowser.Common/Net/IPObject.cs create mode 100644 MediaBrowser.Common/Net/NetworkExtensions.cs create mode 100644 tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj create mode 100644 tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 504bde996b..be618be2b3 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; +using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -26,7 +27,6 @@ using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; using MediaBrowser.Model.System; using Microsoft.Extensions.Logging; -using NetworkCollection; using Rssdp; using Rssdp.Infrastructure; using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; @@ -261,7 +261,7 @@ namespace Emby.Dlna.Main { var udn = CreateUuid(_appHost.SystemId); - var bindAddresses = new NetCollection( + var bindAddresses = NetworkManager.CreateCollection( _networkManager.GetInternalBindAddresses() .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index cfc5278ece..c4176eb7ba 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -3,7 +3,9 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Net; +using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -16,7 +18,6 @@ using MediaBrowser.Model.IO; using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging; -using NetworkCollection.Udp; namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { @@ -51,6 +52,25 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun EnableStreamSharing = true; } + /// + /// Returns an unused UDP port number in the range specified. + /// + /// Upper and Lower boundary of ports to select. + /// System.Int32. + private static int GetUdpPortFromRange((int Min, int Max) range) + { + var properties = IPGlobalProperties.GetIPGlobalProperties(); + + // Get active udp listeners. + var udpListenerPorts = properties.GetActiveUdpListeners() + .Where(n => n.Port >= range.Min && n.Port <= range.Max) + .Select(n => n.Port); + + return Enumerable.Range(range.Min, range.Max) + .Where(i => !udpListenerPorts.Contains(i)) + .FirstOrDefault(); + } + public override async Task Open(CancellationToken openCancellationToken) { LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested(); @@ -58,7 +78,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var mediaSource = OriginalMediaSource; var uri = new Uri(mediaSource.Path); - var localPort = UdpHelper.GetRandomUnusedUdpPort(); + // Temporary Code to reduce PR size. + var localPort = GetUdpPortFromRange((49152, 65535)); Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath)); diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index 330d36a80d..1747a1dc7a 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -23,10 +23,6 @@ ../jellyfin.ruleset - - - - diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 616774d043..76ac02d791 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -13,8 +13,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -using NetworkCollection; -using NetworkCollection.Udp; +using NetCollection = System.Collections.ObjectModel.Collection; namespace Jellyfin.Networking.Manager { @@ -154,6 +153,22 @@ namespace Jellyfin.Networking.Manager /// public Dictionary PublishedServerUrls => _publishedServerUrls; + /// + /// Creates a new network collection. + /// + /// Items to assign the collection, or null. + /// The collection created. + public static NetCollection CreateCollection(IEnumerable? source) + { + var result = new NetCollection(); + if (source != null) + { + return result.AddRange(source); + } + + return result; + } + /// public void Dispose() { @@ -162,10 +177,10 @@ namespace Jellyfin.Networking.Manager } /// - public List GetMacAddresses() + public IReadOnlyCollection GetMacAddresses() { // Populated in construction - so always has values. - return _macAddresses.ToList(); + return _macAddresses.AsReadOnly(); } /// @@ -187,12 +202,12 @@ namespace Jellyfin.Networking.Manager NetCollection nc = new NetCollection(); if (IsIP4Enabled) { - nc.Add(IPAddress.Loopback); + nc.AddItem(IPAddress.Loopback); } if (IsIP6Enabled) { - nc.Add(IPAddress.IPv6Loopback); + nc.AddItem(IPAddress.IPv6Loopback); } return nc; @@ -276,12 +291,12 @@ namespace Jellyfin.Networking.Manager if (IsIP4Enabled) { - result.Add(IPAddress.Any); + result.AddItem(IPAddress.Any); } if (IsIP6Enabled) { - result.Add(IPAddress.IPv6Any); + result.AddItem(IPAddress.IPv6Any); } return result; @@ -375,7 +390,7 @@ namespace Jellyfin.Networking.Manager } // Get the first LAN interface address that isn't a loopback. - var interfaces = new NetCollection(_interfaceAddresses + var interfaces = CreateCollection(_interfaceAddresses .Exclude(_bindExclusions) .Where(p => IsInLocalNetwork(p)) .OrderBy(p => p.Tag)); @@ -418,11 +433,11 @@ namespace Jellyfin.Networking.Manager if (_bindExclusions.Count > 0) { // Return all the internal interfaces except the ones excluded. - return new NetCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); + return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); } // No bind address, so return all internal interfaces. - return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } return new NetCollection(_bindAddresses); @@ -572,7 +587,7 @@ namespace Jellyfin.Networking.Manager } TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; - UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding; + // UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding; if (string.IsNullOrEmpty(MockNetworkSettings)) { @@ -941,7 +956,7 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); // Internal interfaces must be private and not excluded. - _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i))); // Subnets are the same as the calculated internal interface. _lanSubnets = new NetCollection(); @@ -976,7 +991,7 @@ namespace Jellyfin.Networking.Manager } // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i))); } _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets); @@ -1082,7 +1097,7 @@ namespace Jellyfin.Networking.Manager IPHost host = new IPHost(Dns.GetHostName()); foreach (var a in host.GetAddresses()) { - _interfaceAddresses.Add(a); + _interfaceAddresses.AddItem(a); } if (_interfaceAddresses.Count == 0) @@ -1189,7 +1204,7 @@ namespace Jellyfin.Networking.Manager if (isExternal) { // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - bindResult = new NetCollection(nc + bindResult = CreateCollection(nc .Where(p => !IsInLocalNetwork(p)) .OrderBy(p => p.Tag)); defaultGateway = bindResult.FirstOrDefault()?.Address; @@ -1246,7 +1261,7 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = new NetCollection(_interfaceAddresses + var extResult = CreateCollection(_interfaceAddresses .Exclude(_bindExclusions) .Where(p => !IsInLocalNetwork(p)) .OrderBy(p => p.Tag)); diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index c3533d7956..525cd9ffe2 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -5,7 +5,6 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; -using NetworkCollection; namespace Jellyfin.Server.Middleware { @@ -47,7 +46,7 @@ namespace Jellyfin.Server.Middleware { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. - NetCollection remoteAddressFilter = networkManager.RemoteAddressFilter; + var remoteAddressFilter = networkManager.RemoteAddressFilter; if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp)) { diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 1f4e80053d..8065054a1e 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -7,7 +7,6 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; -using NetworkCollection; namespace Jellyfin.Server.Middleware { diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index fd300da7f1..61f7da16a6 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -14,6 +14,7 @@ using Emby.Server.Implementations; using Emby.Server.Implementations.IO; using Jellyfin.Api.Controllers; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; @@ -23,7 +24,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using NetworkCollection; using Serilog; using Serilog.Extensions.Logging; using SQLitePCL; @@ -271,7 +271,7 @@ namespace Jellyfin.Server return builder .UseKestrel((builderContext, options) => { - NetCollection addresses = appHost.NetManager.GetAllBindInterfaces(); + var addresses = appHost.NetManager.GetAllBindInterfaces(); bool flagged = false; foreach (IPObject netAdd in addresses) diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 0b8f431c04..777136f8bf 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -22,7 +22,6 @@ - diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index f60f369d6a..a7beabbdcb 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using Microsoft.AspNetCore.Http; -using NetworkCollection; +using NetCollection = System.Collections.ObjectModel.Collection; namespace MediaBrowser.Common.Net { @@ -130,7 +130,7 @@ namespace MediaBrowser.Common.Net /// Get a list of all the MAC addresses associated with active interfaces. /// /// List of MAC addresses. - List GetMacAddresses(); + IReadOnlyCollection GetMacAddresses(); /// /// Checks to see if the IP Address provided matches an interface that has a gateway. diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs new file mode 100644 index 0000000000..80052727af --- /dev/null +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -0,0 +1,447 @@ +#nullable enable +using System; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace MediaBrowser.Common.Net +{ + /// + /// Object that holds a host name. + /// + public class IPHost : IPObject + { + /// + /// Represents an IPHost that has no value. + /// + public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); + + /// + /// Time when last resolved. + /// + private long _lastResolved; + + /// + /// Gets the IP Addresses, attempting to resolve the name, if there are none. + /// + private IPAddress[] _addresses; + + /// + /// Initializes a new instance of the class. + /// + /// Host name to assign. + public IPHost(string name) + { + HostName = name ?? throw new ArgumentNullException(nameof(name)); + _addresses = Array.Empty(); + Resolved = false; + } + + /// + /// Initializes a new instance of the class. + /// + /// Host name to assign. + /// Address to assign. + private IPHost(string name, IPAddress address) + { + HostName = name ?? throw new ArgumentNullException(nameof(name)); + _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) }; + Resolved = !address.Equals(IPAddress.None); + } + + /// + /// Gets or sets the object's first IP address. + /// + public override IPAddress Address + { + get + { + return ResolveHost() ? this[0] : IPAddress.None; + } + + set + { + // Not implemented. + } + } + + /// + /// Gets or sets the object's first IP's subnet prefix. + /// The setter does nothing, but shouldn't raise an exception. + /// + public override byte PrefixLength + { + get + { + return (byte)(ResolveHost() ? 128 : 0); + } + + set + { + // Not implemented. + } + } + + /// + /// Gets or sets timeout value before resolve required, in minutes. + /// + public byte Timeout { get; set; } = 30; + + /// + /// Gets a value indicating whether the address has a value. + /// + public bool HasAddress + { + get + { + return _addresses.Length > 0; + } + } + + /// + /// Gets the host name of this object. + /// + public string HostName { get; } + + /// + /// Gets a value indicating whether this host has attempted to be resolved. + /// + public bool Resolved { get; private set; } + + /// + /// Gets or sets the IP Addresses associated with this object. + /// + /// Index of address. + public IPAddress this[int index] + { + get + { + ResolveHost(); + return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None; + } + } + + /// + /// Attempts to parse the host string. + /// + /// Host name to parse. + /// Object representing the string, if it has successfully been parsed. + /// Success result of the parsing. + public static bool TryParse(string host, out IPHost hostObj) + { + if (!string.IsNullOrEmpty(host)) + { + // See if it's an IPv6 with port address e.g. [::1]:120. + int i = host.IndexOf("]:", StringComparison.OrdinalIgnoreCase); + if (i != -1) + { + return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); + } + else + { + // See if it's an IPv6 in [] with no port. + i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); + if (i != -1) + { + return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); + } + + // Is it a host or IPv4 with port? + string[] hosts = host.Split(':'); + + if (hosts.Length > 2) + { + hostObj = new IPHost(string.Empty, IPAddress.None); + return false; + } + + // Remove port from IPv4 if it exists. + host = hosts[0]; + + if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) + { + hostObj = new IPHost(host, new IPAddress(Ipv4Loopback)); + return true; + } + + if (IPNetAddress.TryParse(host, out IPNetAddress netIP)) + { + // Host name is an ip address, so fake resolve. + hostObj = new IPHost(host, netIP.Address); + return true; + } + } + + // Only thing left is to see if it's a host string. + if (!string.IsNullOrEmpty(host)) + { + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); + if (re.Match(host).Success) + { + hostObj = new IPHost(host); + return true; + } + } + } + + hostObj = IPHost.None; + return false; + } + + /// + /// Attempts to parse the host string. + /// + /// Host name to parse. + /// Object representing the string, if it has successfully been parsed. + public static IPHost Parse(string host) + { + if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) + { + return res; + } + + throw new InvalidCastException("Host does not contain a valid value. {host}"); + } + + /// + /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type. + /// + /// Host name to parse. + /// Addressfamily filter. + /// Object representing the string, if it has successfully been parsed. + public static IPHost Parse(string host, AddressFamily family) + { + if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) + { + if (family == AddressFamily.InterNetwork) + { + res.Remove(AddressFamily.InterNetworkV6); + } + else + { + res.Remove(AddressFamily.InterNetwork); + } + + return res; + } + + throw new InvalidCastException("Host does not contain a valid value. {host}"); + } + + /// + /// Returns the Addresses that this item resolved to. + /// + /// IPAddress Array. + public IPAddress[] GetAddresses() + { + ResolveHost(); + return _addresses; + } + + /// + public override bool Contains(IPAddress address) + { + if (address != null && !Address.Equals(IPAddress.None)) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + foreach (var addr in GetAddresses()) + { + if (address.Equals(addr)) + { + return true; + } + } + } + + return false; + } + + /// + public override bool Equals(IPObject? other) + { + if (other is IPHost otherObj) + { + // Do we have the name Hostname? + if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (!ResolveHost() || !otherObj.ResolveHost()) + { + return false; + } + + // Do any of our IP addresses match? + foreach (IPAddress addr in _addresses) + { + foreach (IPAddress otherAddress in otherObj._addresses) + { + if (addr.Equals(otherAddress)) + { + return true; + } + } + } + } + + return false; + } + + /// + public override bool IsIP6() + { + // Returns true if interfaces are only IP6. + if (ResolveHost()) + { + foreach (IPAddress i in _addresses) + { + if (i.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + } + + return true; + } + + return false; + } + + /// + public override string ToString() + { + // StringBuilder not optimum here. + string output = string.Empty; + if (_addresses.Length > 0) + { + bool moreThanOne = _addresses.Length > 1; + if (moreThanOne) + { + output = "["; + } + + foreach (var i in _addresses) + { + if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified) + { + output += HostName + ","; + } + else if (i.Equals(IPAddress.Any)) + { + output += "Any IP4 Address,"; + } + else if (Address.Equals(IPAddress.IPv6Any)) + { + output += "Any IP6 Address,"; + } + else if (i.Equals(IPAddress.Broadcast)) + { + output += "Any Address,"; + } + else + { + output += $"{i}/32,"; + } + } + + output = output[0..^1]; + + if (moreThanOne) + { + output += "]"; + } + } + else + { + output = HostName; + } + + return output; + } + + /// + public override void Remove(AddressFamily family) + { + if (ResolveHost()) + { + _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray(); + } + } + + /// + public override bool Contains(IPObject address) + { + // An IPHost cannot contain another IPObject, it can only be equal. + return Equals(address); + } + + /// + protected override IPObject CalculateNetworkAddress() + { + var netAddr = NetworkAddressOf(this[0], PrefixLength); + return new IPNetAddress(netAddr.Address, netAddr.PrefixLength); + } + + /// + /// Attempt to resolve the ip address of a host. + /// + /// The result of the comparison function. + private bool ResolveHost() + { + // When was the last time we resolved? + if (_lastResolved == 0) + { + _lastResolved = DateTime.Now.Ticks; + } + + // If we haven't resolved before, or out timer has run out... + if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.Now.Ticks - _lastResolved).TotalMinutes > Timeout)) + { + _lastResolved = DateTime.Now.Ticks; + ResolveHostInternal().GetAwaiter().GetResult(); + Resolved = true; + } + + return _addresses.Length > 0; + } + + /// + /// Task that looks up a Host name and returns its IP addresses. + /// + /// Array of IPAddress objects. + private async Task ResolveHostInternal() + { + if (!string.IsNullOrEmpty(HostName)) + { + // Resolves the host name - so save a DNS lookup. + if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase)) + { + _addresses = new IPAddress[] { new IPAddress(Ipv4Loopback), new IPAddress(Ipv6Loopback) }; + return; + } + + if (Uri.CheckHostName(HostName).Equals(UriHostNameType.Dns)) + { + try + { + IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false); + _addresses = ip.AddressList; + } + catch (SocketException) + { + // Ignore socket errors, as the result value will just be an empty array. + } + } + } + } + } +} diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs new file mode 100644 index 0000000000..bcd049f3d5 --- /dev/null +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -0,0 +1,277 @@ +#nullable enable +using System; +using System.Net; +using System.Net.Sockets; + +namespace MediaBrowser.Common.Net +{ + /// + /// An object that holds and IP address and subnet mask. + /// + public class IPNetAddress : IPObject + { + /// + /// Represents an IPNetAddress that has no value. + /// + public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None); + + /// + /// IPv4 multicast address. + /// + public static readonly IPAddress MulticastIPv4 = IPAddress.Parse("239.255.255.250"); + + /// + /// IPv6 local link multicast address. + /// + public static readonly IPAddress MulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); + + /// + /// IPv6 site local multicast address. + /// + public static readonly IPAddress MulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); + + /// + /// IP4Loopback address host. + /// + public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/32"); + + /// + /// IP6Loopback address host. + /// + public static readonly IPNetAddress IP6Loopback = IPNetAddress.Parse("::1"); + + /// + /// Object's IP address. + /// + private IPAddress _address; + + /// + /// Initializes a new instance of the class. + /// + /// Address to assign. + public IPNetAddress(IPAddress address) + { + _address = address ?? throw new ArgumentNullException(nameof(address)); + PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + } + + /// + /// Initializes a new instance of the class. + /// + /// IP Address. + /// Mask as a CIDR. + public IPNetAddress(IPAddress address, byte prefixLength) + { + if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address))) + { + _address = address.MapToIPv4(); + } + else + { + _address = address; + } + + PrefixLength = prefixLength; + } + + /// + /// Gets or sets the object's IP address. + /// + public override IPAddress Address + { + get + { + return _address; + } + + set + { + _address = value ?? IPAddress.None; + } + } + + /// + public override byte PrefixLength { get; set; } + + /// + /// Try to parse the address and subnet strings into an IPNetAddress object. + /// + /// IP address to parse. Can be CIDR or X.X.X.X notation. + /// Resultant object. + /// True if the values parsed successfully. False if not, resulting in the IP being null. + public static bool TryParse(string addr, out IPNetAddress ip) + { + if (!string.IsNullOrEmpty(addr)) + { + addr = addr.Trim(); + + // Try to parse it as is. + if (IPAddress.TryParse(addr, out IPAddress res)) + { + ip = new IPNetAddress(res); + return true; + } + + // Is it a network? + string[] tokens = addr.Split("/"); + + if (tokens.Length == 2) + { + tokens[0] = tokens[0].TrimEnd(); + tokens[1] = tokens[1].TrimStart(); + + if (IPAddress.TryParse(tokens[0], out res)) + { + // Is the subnet part a cidr? + if (byte.TryParse(tokens[1], out byte cidr)) + { + ip = new IPNetAddress(res, cidr); + return true; + } + + // Is the subnet in x.y.a.b form? + if (IPAddress.TryParse(tokens[1], out IPAddress mask)) + { + ip = new IPNetAddress(res, MaskToCidr(mask)); + return true; + } + } + } + } + + ip = None; + return false; + } + + /// + /// Parses the string provided, throwing an exception if it is badly formed. + /// + /// String to parse. + /// IPNetAddress object. + public static IPNetAddress Parse(string addr) + { + if (TryParse(addr, out IPNetAddress o)) + { + return o; + } + + throw new ArgumentException("Unable to recognise object :" + addr); + } + + /// + public override bool Contains(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + var altAddress = NetworkAddressOf(address, PrefixLength); + return NetworkAddress.Address.Equals(altAddress.Address) && NetworkAddress.PrefixLength >= altAddress.PrefixLength; + } + + /// + public override bool Contains(IPObject address) + { + if (address is IPHost addressObj && addressObj.HasAddress) + { + foreach (IPAddress addr in addressObj.GetAddresses()) + { + if (Contains(addr)) + { + return true; + } + } + } + else if (address is IPNetAddress netaddrObj) + { + // Have the same network address, but different subnets? + if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address)) + { + return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength; + } + + var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength); + return NetworkAddress.Address.Equals(altAddress.Address); + } + + return false; + } + + /// + public override bool Equals(IPObject? other) + { + if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None)) + { + return Address.Equals(otherObj.Address) && + PrefixLength == otherObj.PrefixLength; + } + + return false; + } + + /// + public override bool Equals(IPAddress address) + { + if (address != null && !address.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) + { + return address.Equals(Address); + } + + return false; + } + + /// + public override string ToString() + { + return ToString(false); + } + + /// + /// Returns a textual representation of this object. + /// + /// Set to true, if the subnet is to be included as part of the address. + /// String representation of this object. + public string ToString(bool shortVersion) + { + if (!Address.Equals(IPAddress.None)) + { + if (Address.Equals(IPAddress.Any)) + { + return "Any IP4 Address"; + } + + if (Address.Equals(IPAddress.IPv6Any)) + { + return "Any IP6 Address"; + } + + if (Address.Equals(IPAddress.Broadcast)) + { + return "Any Address"; + } + + if (shortVersion) + { + return Address.ToString(); + } + + return $"{Address}/{PrefixLength}"; + } + + return string.Empty; + } + + /// + protected override IPObject CalculateNetworkAddress() + { + var value = NetworkAddressOf(_address, PrefixLength); + return new IPNetAddress(value.Address, value.PrefixLength); + } + } +} diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs new file mode 100644 index 0000000000..a08694c266 --- /dev/null +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -0,0 +1,395 @@ +#nullable enable +using System; +using System.Net; +using System.Net.Sockets; + +namespace MediaBrowser.Common.Net +{ + /// + /// Base network object class. + /// + public abstract class IPObject : IEquatable + { + /// + /// IPv6 Loopback address. + /// + protected static readonly byte[] Ipv6Loopback = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; + + /// + /// IPv4 Loopback address. + /// + protected static readonly byte[] Ipv4Loopback = { 127, 0, 0, 1 }; + + /// + /// The network address of this object. + /// + private IPObject? _networkAddress; + + /// + /// Gets or sets the user defined functions that need storage in this object. + /// + public int Tag { get; set; } + + /// + /// Gets or sets the object's IP address. + /// + public abstract IPAddress Address { get; set; } + + /// + /// Gets the object's network address. + /// + public IPObject NetworkAddress + { + get + { + if (_networkAddress == null) + { + _networkAddress = CalculateNetworkAddress(); + } + + return _networkAddress; + } + } + + /// + /// Gets or sets the object's IP address. + /// + public abstract byte PrefixLength { get; set; } + + /// + /// Gets the AddressFamily of this object. + /// + public AddressFamily AddressFamily + { + get + { + // Keep terms separate as Address performs other functions in inherited objects. + IPAddress address = Address; + return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily; + } + } + + /// + /// Returns the network address of an object. + /// + /// IP Address to convert. + /// Subnet prefix. + /// IPAddress. + public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (IsLoopback(address)) + { + return (Address: address, PrefixLength: prefixLength); + } + + byte[] addressBytes = address.GetAddressBytes(); + + int div = prefixLength / 8; + int mod = prefixLength % 8; + if (mod != 0) + { + mod = 8 - mod; + addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod); + div++; + } + + for (int octet = div; octet < addressBytes.Length; octet++) + { + addressBytes[octet] = 0; + } + + return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); + } + + /// + /// Tests to see if the ip address is a Loopback address. + /// + /// Value to test. + /// True if it is. + public static bool IsLoopback(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (!address.Equals(IPAddress.None)) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback); + } + + return false; + } + + /// + /// Tests to see if the ip address is an IP6 address. + /// + /// Value to test. + /// True if it is. + public static bool IsIP6(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6); + } + + /// + /// Tests to see if the address in the private address range. + /// + /// Object to test. + /// True if it contains a private address. + public static bool IsPrivateAddressRange(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (!address.Equals(IPAddress.None)) + { + if (address.AddressFamily == AddressFamily.InterNetwork) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + byte[] octet = address.GetAddressBytes(); + + return (octet[0] == 10) || + (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) || // RFC1918 + (octet[0] == 192 && octet[1] == 168) || // RFC1918 + (octet[0] == 127); // RFC1122 + } + else + { + byte[] octet = address.GetAddressBytes(); + uint word = (uint)(octet[0] << 8) + octet[1]; + + return (word >= 0xfe80 && word <= 0xfebf) || // fe80::/10 :Local link. + (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. + } + } + + return false; + } + + /// + /// Returns true if the IPAddress contains an IP6 Local link address. + /// + /// IPAddress object to check. + /// True if it is a local link address. + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// + public static bool IsIPv6LinkLocal(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + + byte[] octet = address.GetAddressBytes(); + uint word = (uint)(octet[0] << 8) + octet[1]; + + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. + } + + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(byte cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + addr = + ((addr & 0xff000000) >> 24) | + ((addr & 0x00ff0000) >> 8) | + ((addr & 0x0000ff00) << 8) | + ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// + /// Convert a mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. + /// + /// Subnet mask. + /// Byte CIDR representing the mask. + public static byte MaskToCidr(IPAddress mask) + { + if (mask == null) + { + throw new ArgumentNullException(nameof(mask)); + } + + byte cidrnet = 0; + if (!mask.Equals(IPAddress.Any)) + { + byte[] bytes = mask.GetAddressBytes(); + + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) + { + if (zeroed) + { + // Invalid netmask. + return (byte)~cidrnet; + } + + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; + } + } + } + } + + return cidrnet; + } + + /// + /// Tests to see if this object is a Loopback address. + /// + /// True if it is. + public virtual bool IsLoopback() + { + return IsLoopback(Address); + } + + /// + /// Removes all addresses of a specific type from this object. + /// + /// Type of address to remove. + public virtual void Remove(AddressFamily family) + { + // This method only peforms a function in the IPHost implementation of IPObject. + } + + /// + /// Tests to see if this object is an IPv6 address. + /// + /// True if it is. + public virtual bool IsIP6() + { + return IsIP6(Address); + } + + /// + /// Returns true if this IP address is in the RFC private address range. + /// + /// True this object has a private address. + public virtual bool IsPrivateAddressRange() + { + return IsPrivateAddressRange(Address); + } + + /// + /// Compares this to the object passed as a parameter. + /// + /// Object to compare to. + /// Equality result. + public virtual bool Equals(IPAddress ip) + { + if (ip != null) + { + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + return !Address.Equals(IPAddress.None) && Address.Equals(ip); + } + + return false; + } + + /// + /// Compares this to the object passed as a parameter. + /// + /// Object to compare to. + /// Equality result. + public virtual bool Equals(IPObject? other) + { + if (other != null && other is IPObject otherObj) + { + return !Address.Equals(IPAddress.None) && Address.Equals(otherObj.Address); + } + + return false; + } + + /// + /// Compares the address in this object and the address in the object passed as a parameter. + /// + /// Object's IP address to compare to. + /// Comparison result. + public abstract bool Contains(IPObject address); + + /// + /// Compares the address in this object and the address in the object passed as a parameter. + /// + /// Object's IP address to compare to. + /// Comparison result. + public abstract bool Contains(IPAddress address); + + /// + public override int GetHashCode() + { + return Address.GetHashCode(); + } + + /// + public override bool Equals(object obj) + { + return Equals(obj as IPObject); + } + + /// + /// Calculates the network address of this object. + /// + /// Returns the network address of this object. + protected abstract IPObject CalculateNetworkAddress(); + } +} diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs new file mode 100644 index 0000000000..6e9cb46dc1 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -0,0 +1,254 @@ +#pragma warning disable CA1062 // Validate arguments of public methods +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Runtime.CompilerServices; +using NetCollection = System.Collections.ObjectModel.Collection; + +namespace MediaBrowser.Common.Net +{ + /// + /// Defines the . + /// + public static class NetworkExtensions + { + /// + /// Add an address to the collection. + /// + /// The . + /// Item to add. + public static void AddItem(this NetCollection source, IPAddress ip) + { + if (!source.ContainsAddress(ip)) + { + source.Add(new IPNetAddress(ip, 32)); + } + } + + /// + /// Add multiple items to the collection. + /// + /// The . + /// Item to add. + /// Return the collection. + public static NetCollection AddRange(this NetCollection destination, IEnumerable source) + { + foreach (var item in source) + { + destination.Add(item); + } + + return destination; + } + + /// + /// Adds a network to the collection. + /// + /// The . + /// Item to add. + public static void AddItem(this NetCollection source, IPObject item) + { + if (!source.ContainsAddress(item)) + { + source.Add(item); + } + } + + /// + /// Converts this object to a string. + /// + /// The . + /// Returns a string representation of this object. + public static string Readable(this NetCollection source) + { + string output = "["; + if (source.Count > 0) + { + foreach (var i in source) + { + output += $"{i},"; + } + + output = output[0..^1]; + } + + return $"{output}]"; + } + + /// + /// Returns true if the collection contains an item with the ip address, + /// or the ip address falls within any of the collection's network ranges. + /// + /// The . + /// The item to look for. + /// True if the collection contains the item. + public static bool ContainsAddress(this NetCollection source, IPAddress item) + { + if (source.Count == 0) + { + return false; + } + + if (item == null) + { + throw new ArgumentNullException(nameof(item)); + } + + if (item.IsIPv4MappedToIPv6) + { + item = item.MapToIPv4(); + } + + foreach (var i in source) + { + if (i.Contains(item)) + { + return true; + } + } + + return false; + } + + /// + /// Returns true if the collection contains an item with the ip address, + /// or the ip address falls within any of the collection's network ranges. + /// + /// The . + /// The item to look for. + /// True if the collection contains the item. + public static bool ContainsAddress(this NetCollection source, IPObject item) + { + if (source.Count == 0) + { + return false; + } + + if (item == null) + { + throw new ArgumentNullException(nameof(item)); + } + + foreach (var i in source) + { + if (i.Contains(item)) + { + return true; + } + } + + return false; + } + + /// + /// Returns a collection containing the subnets of this collection given. + /// + /// The . + /// NetCollection object containing the subnets. + public static NetCollection AsNetworks(this NetCollection source) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + NetCollection res = new NetCollection(); + + foreach (IPObject i in source) + { + if (i is IPNetAddress nw) + { + // Add the subnet calculated from the interface address/mask. + var na = nw.NetworkAddress; + na.Tag = i.Tag; + res.Add(na); + } + else + { + // Flatten out IPHost and add all its ip addresses. + foreach (var addr in ((IPHost)i).GetAddresses()) + { + IPNetAddress host = new IPNetAddress(addr) + { + Tag = i.Tag + }; + + res.Add(host); + } + } + } + + return res; + } + + /// + /// Excludes all the items from this list that are found in excludeList. + /// + /// The . + /// Items to exclude. + /// A new collection, with the items excluded. + public static NetCollection Exclude(this NetCollection source, NetCollection excludeList) + { + if (source.Count == 0 || excludeList == null) + { + return new NetCollection(source); + } + + NetCollection results = new NetCollection(); + + bool found; + foreach (var outer in source) + { + found = false; + + foreach (var inner in excludeList) + { + if (outer.Equals(inner)) + { + found = true; + break; + } + } + + if (!found) + { + results.Add(outer); + } + } + + return results; + } + + /// + /// Returns all items that co-exist in this object and target. + /// + /// The . + /// Collection to compare with. + /// A collection containing all the matches. + public static NetCollection Union(this NetCollection source, NetCollection target) + { + if (source.Count == 0) + { + return new NetCollection(); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + NetCollection nc = new NetCollection(); + + foreach (IPObject i in source) + { + if (target.ContainsAddress(i)) + { + nc.Add(i); + } + } + + return nc; + } + } +} diff --git a/MediaBrowser.sln b/MediaBrowser.sln index d460c0ab0c..cb204137bd 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -68,6 +68,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementat EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\NetworkTesting\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -182,6 +184,10 @@ Global {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -193,6 +199,7 @@ Global {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index ae175d8c9d..3e89d7f602 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -6,7 +6,6 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; -using NetworkCollection; namespace Rssdp.Infrastructure { diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj new file mode 100644 index 0000000000..fa18316dff --- /dev/null +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -0,0 +1,28 @@ + + + + + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} + + + + netcoreapp3.1 + false + true + enable + + + + + + + + + + + + + + + + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs new file mode 100644 index 0000000000..9e7e8d3ac3 --- /dev/null +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -0,0 +1,425 @@ +using System; +using System.Net; +using Emby.Dlna.PlayTo; +using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Manager; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using Moq; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; +using NetCollection = System.Collections.ObjectModel.Collection; +using XMLProperties = System.Collections.Generic.Dictionary; + +namespace NetworkTesting +{ + public class NetTesting + { + /// + /// Trys to identify the string and return an object of that class. + /// + /// String to parse. + /// IPObject to return. + /// True if the value parsed successfully. + private static bool TryParse(string addr, out IPObject result) + { + if (!string.IsNullOrEmpty(addr)) + { + // Is it an IP address + if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) + { + result = nw; + return true; + } + + if (IPHost.TryParse(addr, out IPHost h)) + { + result = h; + return true; + } + } + + result = IPNetAddress.None; + return false; + } + + + private IConfigurationManager GetMockConfig(NetworkConfiguration conf) + { + var configManager = new Mock + { + CallBase = true + }; + configManager.Setup(x => x.GetConfiguration(It.IsAny())).Returns(conf); + return (IConfigurationManager)configManager.Object; + } + + [Theory] + [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] + [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212;200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + LocalNetworkSubnets = lan.Split(';') + }; + + NetworkManager.MockNetworkSettings = interfaces; + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + NetworkManager.MockNetworkSettings = string.Empty; + + Assert.True(string.Equals(nm.GetInternalBindAddresses().ToString(), value, StringComparison.Ordinal)); + } + + [Theory] + [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")] + public void TextIsInNetwork(string network, string value) + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + LocalNetworkSubnets = network.Split(',') + }; + + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + Assert.True(!nm.IsInLocalNetwork(value)); + } + + [Theory] + [InlineData("127.0.0.1")] + [InlineData("127.0.0.1:123")] + [InlineData("localhost")] + [InlineData("localhost:1345")] + [InlineData("www.google.co.uk")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] + [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]:124")] + [InlineData("fe80::7add:12ff:febb:c67b%16")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] + [InlineData("192.168.1.2/255.255.255.0")] + [InlineData("192.168.1.2/24")] + + public void TestCollectionCreation(string address) + { + Assert.True(TryParse(address, out _)); + } + + [Theory] + [InlineData("256.128.0.0.0.1")] + [InlineData("127.0.0.1#")] + [InlineData("localhost!")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] + public void TestInvalidCollectionCreation(string address) + { + Assert.False(TryParse(address, out _)); + } + + [Theory] + // Src, IncIP6, incIP4, exIP6, ecIP4, net + [InlineData("127.0.0.1#", + "[]", + "[]", + "[]", + "[]", + "[]")] + [InlineData("[127.0.0.1]", + "[]", + "[]", + "[127.0.0.1/32]", + "[127.0.0.1/32]", + "[]")] + [InlineData("", + "[]", + "[]", + "[]", + "[]", + "[]")] + [InlineData("192.158.1.2/255.255.0.0,192.169.1.2/8", + "[192.158.1.2/16,192.169.1.2/8]", + "[192.158.1.2/16,192.169.1.2/8]", + "[]", + "[]", + "[192.158.0.0/16,192.0.0.0/8]")] + [InlineData("192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, [10.10.10.10]", + "[192.158.1.2/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]", + "[192.158.1.2/16,127.0.0.1/32]", + "[10.10.10.10/32]", + "[10.10.10.10/32]", + "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] + public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5) + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + }; + + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + // Test included, IP6. + NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); + Assert.True(string.Equals(nc.ToString(), result1, System.StringComparison.OrdinalIgnoreCase)); + + // Text excluded, non IP6. + nc = nm.CreateIPCollection(settings.Split(","), true); + Assert.True(string.Equals(nc?.ToString(), result3, System.StringComparison.OrdinalIgnoreCase)); + + conf.EnableIPV6 = false; + nm.UpdateSettings(conf); + + // Test included, non IP6. + nc = nm.CreateIPCollection(settings.Split(","), false); + Assert.True(string.Equals(nc.ToString(), result2, System.StringComparison.OrdinalIgnoreCase)); + + // Test excluded, including IPv6. + nc = nm.CreateIPCollection(settings.Split(","), true); + Assert.True(string.Equals(nc.ToString(), result4, System.StringComparison.OrdinalIgnoreCase)); + + conf.EnableIPV6 = true; + nm.UpdateSettings(conf); + + // Test network addresses of collection. + nc = nm.CreateIPCollection(settings.Split(","), false); + nc = nc.AsNetworks(); + Assert.True(string.Equals(nc.ToString(), result5, System.StringComparison.OrdinalIgnoreCase)); + } + + [Theory] + [InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")] + [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")] + public void UnionCheck(string settings, string compare, string result) + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + }; + + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false); + NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false); + + Assert.True(nc1.Union(nc2).ToString() == result); + } + + [Theory] + [InlineData("192.168.5.85/24", "192.168.5.1")] + [InlineData("192.168.5.85/24", "192.168.5.254")] + [InlineData("10.128.240.50/30", "10.128.240.48")] + [InlineData("10.128.240.50/30", "10.128.240.49")] + [InlineData("10.128.240.50/30", "10.128.240.50")] + [InlineData("10.128.240.50/30", "10.128.240.51")] + [InlineData("127.0.0.1/8", "127.0.0.1")] + public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) + { + var ipAddressObj = IPNetAddress.Parse(netMask); + Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + } + + [Theory] + [InlineData("192.168.5.85/24", "192.168.4.254")] + [InlineData("192.168.5.85/24", "191.168.5.254")] + [InlineData("10.128.240.50/30", "10.128.240.47")] + [InlineData("10.128.240.50/30", "10.128.240.52")] + [InlineData("10.128.240.50/30", "10.128.239.50")] + [InlineData("10.128.240.50/30", "10.127.240.51")] + public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) + { + var ipAddressObj = IPNetAddress.Parse(netMask); + Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + } + + [Theory] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")] + [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] + public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) + { + var ipAddressObj = IPNetAddress.Parse(netMask); + Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + } + + [Theory] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")] + [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")] + [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] + public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) + { + var ipAddressObj = IPNetAddress.Parse(netMask); + Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + } + + [Theory] + [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")] + [InlineData("10.0.0.0/8", "10.10.10.1/32")] + [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")] + + [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")] + [InlineData("10.10.0.0/16", "10.10.10.1/32")] + [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")] + + [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")] + [InlineData("10.10.10.0/24", "10.10.10.1/32")] + [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")] + + public void TestSubnets(string network, string ip) + { + Assert.True(TryParse(network, out IPObject? networkObj)); + Assert.True(TryParse(ip, out IPObject? ipObj)); + +#pragma warning disable CS8602 // Dereference of a possibly null reference. +#pragma warning disable CS8604 // Possible null reference argument. + Assert.True(networkObj.Contains(ipObj)); +#pragma warning restore CS8604 // Possible null reference argument. +#pragma warning restore CS8602 // Dereference of a possibly null reference. + } + + [Theory] + [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")] + [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")] + [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")] + [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")] + [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")] + + public void TestMatches(string source, string dest, string result) + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true + }; + + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + // Test included, IP6. + NetCollection ncSource = nm.CreateIPCollection(source.Split(",")); + NetCollection ncDest = nm.CreateIPCollection(dest.Split(",")); + NetCollection ncResult = ncSource.Union(ncDest); + NetCollection resultCollection = nm.CreateIPCollection(result.Split(",")); + Assert.True(ncResult.Equals(resultCollection)); + } + + + [Theory] + [InlineData("10.1.1.1/32", "10.1.1.1")] + [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")] + + public void TestEquals(string source, string dest) + { + Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest))); + Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source))); + } + + [Theory] + + // Testing bind interfaces. These are set for my system so won't work elsewhere. + // On my system eth16 is internal, eth11 external (Windows defines the indexes). + // + // This test is to replicate how DNLA requests work throughout the system. + + // User on internal network, we're bound internal and external - so result is internal. + [InlineData("192.168.1.1", "eth16,eth11", false, "eth16")] + // User on external network, we're bound internal and external - so result is external. + [InlineData("8.8.8.8", "eth16,eth11", false, "eth11")] + // User on internal network, we're bound internal only - so result is internal. + [InlineData("10.10.10.10", "eth16", false, "eth16")] + // User on internal network, no binding specified - so result is the 1st internal. + [InlineData("192.168.1.1", "", false, "eth16")] + // User on external network, internal binding only - so result is the 1st internal. + [InlineData("jellyfin.org", "eth16", false, "eth16")] + // User on external network, no binding - so result is the 1st external. + [InlineData("jellyfin.org", "", false, "eth11")] + // User assumed to be internal, no binding - so result is the 1st internal. + [InlineData("", "", false, "eth16")] + public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result) + { + var conf = new NetworkConfiguration() + { + LocalNetworkAddresses = bindAddresses.Split(','), + EnableIPV6 = ipv6enabled, + EnableIPV4 = true + }; + + NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + NetworkManager.MockNetworkSettings = string.Empty; + + _ = nm.TryParseInterface(result, out NetCollection? resultObj); + + if (resultObj != null) + { + result = ((IPNetAddress)resultObj[0]).ToString(true); + var intf = nm.GetBindInterface(source, out int? _); + + Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase)); + } + } + + [Theory] + + // Testing bind interfaces. These are set for my system so won't work elsewhere. + // On my system eth16 is internal, eth11 external (Windows defines the indexes). + // + // This test is to replicate how subnet bound ServerPublisherUri work throughout the system. + + // User on internal network, we're bound internal and external - so result is internal override. + [InlineData("192.168.1.1", "192.168.1.0/24", "eth16,eth11", false, "192.168.1.0/24=internal.jellyfin", "internal.jellyfin")] + + // User on external network, we're bound internal and external - so result is override. + [InlineData("8.8.8.8", "192.168.1.0/24", "eth16,eth11", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")] + + // User on internal network, we're bound internal only, but the address isn't in the LAN - so return the override. + [InlineData("10.10.10.10", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://internalButNotDefinedAsLan.com", "http://internalButNotDefinedAsLan.com")] + + // User on internal network, no binding specified - so result is the 1st internal. + [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")] + + // User on external network, internal binding only - so asumption is a proxy forward, return external override. + [InlineData("jellyfin.org", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")] + + // User on external network, no binding - so result is the 1st external which is overriden. + [InlineData("jellyfin.org", "192.168.1.0/24", "", false, "0.0.0.0 = http://helloworld.com", "http://helloworld.com")] + + // User assumed to be internal, no binding - so result is the 1st internal. + [InlineData("", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")] + + // User is internal, no binding - so result is the 1st internal, which is then overridden. + [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "eth16=http://helloworld.com", "http://helloworld.com")] + + public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result) + { + var conf = new NetworkConfiguration() + { + LocalNetworkSubnets = lan.Split(','), + LocalNetworkAddresses = bindAddresses.Split(','), + EnableIPV6 = ipv6enabled, + EnableIPV4 = true, + PublishedServerUriBySubnet = new string[] { publishedServers } + }; + + NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; + var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + NetworkManager.MockNetworkSettings = string.Empty; + + if (nm.TryParseInterface(result, out NetCollection? resultObj) && resultObj != null) + { + // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). + result = ((IPNetAddress)resultObj[0]).ToString(true); + } + + var intf = nm.GetBindInterface(source, out int? _); + + Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase)); + } + } +} From f06e4826c764c1214478a741b0f93315a8bba76b Mon Sep 17 00:00:00 2001 From: Greenback Date: Sat, 31 Oct 2020 19:16:28 +0000 Subject: [PATCH 0175/1930] Fixed testing units --- Jellyfin.Networking/Manager/NetworkManager.cs | 55 +++++++++-------- MediaBrowser.Common/Net/NetworkExtensions.cs | 60 ++++++++++++------- .../NetworkTesting/UnitTesting.cs | 16 ++--- 3 files changed, 77 insertions(+), 54 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 76ac02d791..2ec2a0ba52 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -158,12 +158,15 @@ namespace Jellyfin.Networking.Manager /// /// Items to assign the collection, or null. /// The collection created. - public static NetCollection CreateCollection(IEnumerable? source) + public static NetCollection CreateCollection(IEnumerable? source = null) { var result = new NetCollection(); if (source != null) { - return result.AddRange(source); + foreach (var item in source) + { + result.AddItem(item); + } } return result; @@ -433,7 +436,7 @@ namespace Jellyfin.Networking.Manager if (_bindExclusions.Count > 0) { // Return all the internal interfaces except the ones excluded. - return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p))); + return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); } // No bind address, so return all internal interfaces. @@ -463,7 +466,7 @@ namespace Jellyfin.Networking.Manager } // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address); + return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address); } /// @@ -471,7 +474,7 @@ namespace Jellyfin.Networking.Manager { if (IPHost.TryParse(address, out IPHost ep)) { - return _lanSubnets.Contains(ep) && !_excludedSubnets.Contains(ep); + return _lanSubnets.ContainsAddress(ep) && !_excludedSubnets.ContainsAddress(ep); } return false; @@ -559,7 +562,7 @@ namespace Jellyfin.Networking.Manager ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { - result.Add(iface); + result.AddItem(iface); } } @@ -603,7 +606,7 @@ namespace Jellyfin.Networking.Manager var address = IPNetAddress.Parse(parts[0]); var index = int.Parse(parts[1], CultureInfo.InvariantCulture); address.Tag = index; - _interfaceAddresses.Add(address); + _interfaceAddresses.AddItem(address); _interfaceNames.Add(parts[2], Math.Abs(index)); } } @@ -747,7 +750,7 @@ namespace Jellyfin.Networking.Manager ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { - col.Add(iface); + col.AddItem(iface); } } } @@ -759,7 +762,7 @@ namespace Jellyfin.Networking.Manager obj.Remove(AddressFamily.InterNetworkV6); if (!obj.IsIP6()) { - col.Add(obj); + col.AddItem(obj); } } else if (!IsIP4Enabled) @@ -768,12 +771,12 @@ namespace Jellyfin.Networking.Manager obj.Remove(AddressFamily.InterNetwork); if (obj.IsIP6()) { - col.Add(obj); + col.AddItem(obj); } } else { - col.Add(obj); + col.AddItem(obj); } } else @@ -956,7 +959,7 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); // Internal interfaces must be private and not excluded. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); // Subnets are the same as the calculated internal interface. _lanSubnets = new NetCollection(); @@ -964,17 +967,17 @@ namespace Jellyfin.Networking.Manager // We must listen on loopback for LiveTV to function regardless of the settings. if (IsIP6Enabled) { - _lanSubnets.Add(IPNetAddress.IP6Loopback); - _lanSubnets.Add(IPNetAddress.Parse("fc00::/7")); // ULA - _lanSubnets.Add(IPNetAddress.Parse("fe80::/10")); // Site local + _lanSubnets.AddItem(IPNetAddress.IP6Loopback); + _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA + _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local } if (IsIP4Enabled) { - _lanSubnets.Add(IPNetAddress.IP4Loopback); - _lanSubnets.Add(IPNetAddress.Parse("10.0.0.0/8")); - _lanSubnets.Add(IPNetAddress.Parse("172.16.0.0/12")); - _lanSubnets.Add(IPNetAddress.Parse("192.168.0.0/16")); + _lanSubnets.AddItem(IPNetAddress.IP4Loopback); + _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8")); + _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12")); + _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16")); } } else @@ -982,16 +985,16 @@ namespace Jellyfin.Networking.Manager // We must listen on loopback for LiveTV to function regardless of the settings. if (IsIP6Enabled) { - _lanSubnets.Add(IPNetAddress.IP6Loopback); + _lanSubnets.AddItem(IPNetAddress.IP6Loopback); } if (IsIP4Enabled) { - _lanSubnets.Add(IPNetAddress.IP4Loopback); + _lanSubnets.AddItem(IPNetAddress.IP4Loopback); } // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); } _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets); @@ -1049,7 +1052,7 @@ namespace Jellyfin.Networking.Manager nw.Tag *= -1; } - _interfaceAddresses.Add(nw); + _interfaceAddresses.AddItem(nw); // Store interface name so we can use the name in Collections. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; @@ -1070,7 +1073,7 @@ namespace Jellyfin.Networking.Manager nw.Tag *= -1; } - _interfaceAddresses.Add(nw); + _interfaceAddresses.AddItem(nw); // Store interface name so we can use the name in Collections. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; @@ -1104,10 +1107,10 @@ namespace Jellyfin.Networking.Manager { _logger.LogError("No interfaces information available. Resolving DNS name."); // Last ditch attempt - use loopback address. - _interfaceAddresses.Add(IPNetAddress.IP4Loopback); + _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); if (IsIP6Enabled) { - _interfaceAddresses.Add(IPNetAddress.IP6Loopback); + _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); } } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 6e9cb46dc1..39499460ea 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Net; using System.Runtime.CompilerServices; +using System.Text; using NetCollection = System.Collections.ObjectModel.Collection; namespace MediaBrowser.Common.Net @@ -26,22 +27,6 @@ namespace MediaBrowser.Common.Net } } - /// - /// Add multiple items to the collection. - /// - /// The . - /// Item to add. - /// Return the collection. - public static NetCollection AddRange(this NetCollection destination, IEnumerable source) - { - foreach (var item in source) - { - destination.Add(item); - } - - return destination; - } - /// /// Adds a network to the collection. /// @@ -62,6 +47,7 @@ namespace MediaBrowser.Common.Net /// Returns a string representation of this object. public static string Readable(this NetCollection source) { + var sb = new StringBuilder(); string output = "["; if (source.Count > 0) { @@ -141,6 +127,40 @@ namespace MediaBrowser.Common.Net return false; } + /// + /// Compares two NetCollection objects. The order is ignored. + /// + /// The . + /// Item to compare to. + /// True if both are equal. + public static bool Compare(this NetCollection source, NetCollection dest) + { + if (dest == null || source.Count != dest.Count) + { + return false; + } + + foreach (var sourceItem in source) + { + bool found = false; + foreach (var destItem in dest) + { + if (sourceItem.Equals(destItem)) + { + found = true; + break; + } + } + + if (!found) + { + return false; + } + } + + return true; + } + /// /// Returns a collection containing the subnets of this collection given. /// @@ -162,7 +182,7 @@ namespace MediaBrowser.Common.Net // Add the subnet calculated from the interface address/mask. var na = nw.NetworkAddress; na.Tag = i.Tag; - res.Add(na); + res.AddItem(na); } else { @@ -174,7 +194,7 @@ namespace MediaBrowser.Common.Net Tag = i.Tag }; - res.Add(host); + res.AddItem(host); } } } @@ -213,7 +233,7 @@ namespace MediaBrowser.Common.Net if (!found) { - results.Add(outer); + results.AddItem(outer); } } @@ -244,7 +264,7 @@ namespace MediaBrowser.Common.Net { if (target.ContainsAddress(i)) { - nc.Add(i); + nc.AddItem(i); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index 9e7e8d3ac3..fe64d1cfce 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -71,7 +71,7 @@ namespace NetworkTesting var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.True(string.Equals(nm.GetInternalBindAddresses().ToString(), value, StringComparison.Ordinal)); + Assert.True(string.Equals(nm.GetInternalBindAddresses().Readable(), value, StringComparison.Ordinal)); } [Theory] @@ -163,22 +163,22 @@ namespace NetworkTesting // Test included, IP6. NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc.ToString(), result1, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc.Readable(), result1, System.StringComparison.OrdinalIgnoreCase)); // Text excluded, non IP6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc?.ToString(), result3, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.Readable(), result3, System.StringComparison.OrdinalIgnoreCase)); conf.EnableIPV6 = false; nm.UpdateSettings(conf); // Test included, non IP6. nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc.ToString(), result2, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc.Readable(), result2, System.StringComparison.OrdinalIgnoreCase)); // Test excluded, including IPv6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc.ToString(), result4, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc.Readable(), result4, System.StringComparison.OrdinalIgnoreCase)); conf.EnableIPV6 = true; nm.UpdateSettings(conf); @@ -186,7 +186,7 @@ namespace NetworkTesting // Test network addresses of collection. nc = nm.CreateIPCollection(settings.Split(","), false); nc = nc.AsNetworks(); - Assert.True(string.Equals(nc.ToString(), result5, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc.Readable(), result5, System.StringComparison.OrdinalIgnoreCase)); } [Theory] @@ -205,7 +205,7 @@ namespace NetworkTesting NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false); NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false); - Assert.True(nc1.Union(nc2).ToString() == result); + Assert.True(nc1.Union(nc2).Readable() == result); } [Theory] @@ -306,7 +306,7 @@ namespace NetworkTesting NetCollection ncDest = nm.CreateIPCollection(dest.Split(",")); NetCollection ncResult = ncSource.Union(ncDest); NetCollection resultCollection = nm.CreateIPCollection(result.Split(",")); - Assert.True(ncResult.Equals(resultCollection)); + Assert.True(ncResult.Compare(resultCollection)); } From 0bcf4c02b4281ed897b2ea9415db0397a9875ec0 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sat, 31 Oct 2020 15:50:56 -0400 Subject: [PATCH 0176/1930] Remove jellyfin-ffmpeg dep from server package Being added to the metapackage instead. --- debian/control | 1 - 1 file changed, 1 deletion(-) diff --git a/debian/control b/debian/control index 39c2aa055b..9216d24fe3 100644 --- a/debian/control +++ b/debian/control @@ -20,7 +20,6 @@ Breaks: jellyfin (<<10.6.0) Architecture: any Depends: at, libsqlite3-0, - jellyfin-ffmpeg (>= 4.2.1-2), libfontconfig1, libfreetype6, libssl1.1 From e5237384d5f4d525f0427b4571d2c4a2182adae8 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Sun, 1 Nov 2020 04:20:25 +0800 Subject: [PATCH 0177/1930] fix the route of audio containers --- Jellyfin.Api/Controllers/UniversalAudioController.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index df20a92b3d..70848aed6c 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -88,16 +88,14 @@ namespace Jellyfin.Api.Controllers /// Redirected to remote audio stream. /// A containing the audio file. [HttpGet("Audio/{itemId}/universal")] - [HttpGet("Audio/{itemId}/universal.{container}", Name = "GetUniversalAudioStream_2")] [HttpHead("Audio/{itemId}/universal", Name = "HeadUniversalAudioStream")] - [HttpHead("Audio/{itemId}/universal.{container}", Name = "HeadUniversalAudioStream_2")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status302Found)] [ProducesAudioFile] public async Task GetUniversalAudioStream( [FromRoute, Required] Guid itemId, - [FromRoute] string? container, + [FromQuery] string? container, [FromQuery] string? mediaSourceId, [FromQuery] string? deviceId, [FromQuery] Guid? userId, From 59619b6ea74ab555977fd213f6ee5737897b0fbd Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 10:47:31 +0100 Subject: [PATCH 0178/1930] Enable nullable in Emby.Naming --- Emby.Naming/AudioBook/AudioBookFileInfo.cs | 19 +- Emby.Naming/AudioBook/AudioBookInfo.cs | 4 +- .../AudioBook/AudioBookListResolver.cs | 8 +- Emby.Naming/AudioBook/AudioBookResolver.cs | 14 +- Emby.Naming/Common/EpisodeExpression.cs | 4 +- Emby.Naming/Common/NamingOptions.cs | 515 ++++++++---------- Emby.Naming/Emby.Naming.csproj | 1 + Emby.Naming/Subtitles/SubtitleInfo.cs | 9 +- Emby.Naming/Subtitles/SubtitleParser.cs | 10 +- Emby.Naming/TV/EpisodeInfo.cs | 13 +- Emby.Naming/TV/EpisodePathParserResult.cs | 2 +- Emby.Naming/TV/EpisodeResolver.cs | 3 +- Emby.Naming/Video/ExtraResult.cs | 2 +- Emby.Naming/Video/ExtraRule.cs | 8 + Emby.Naming/Video/FileStack.cs | 2 +- Emby.Naming/Video/Format3DParser.cs | 2 +- Emby.Naming/Video/Format3DResult.cs | 2 +- Emby.Naming/Video/Format3DRule.cs | 8 +- Emby.Naming/Video/StubTypeRule.cs | 6 + Emby.Naming/Video/VideoFileInfo.cs | 12 +- Emby.Naming/Video/VideoInfo.cs | 4 +- Emby.Naming/Video/VideoListResolver.cs | 11 +- Emby.Naming/Video/VideoResolver.cs | 6 +- .../Library/LibraryManager.cs | 5 +- .../MediaBrowser.Common.csproj | 4 +- .../AudioBook/AudioBookFileInfoTests.cs | 10 +- .../AudioBook/AudioBookResolverTests.cs | 32 +- 27 files changed, 349 insertions(+), 367 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs index c4863b50ab..e5200416ee 100644 --- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs @@ -7,6 +7,23 @@ namespace Emby.Naming.AudioBook /// public class AudioBookFileInfo : IComparable { + /// + /// Initializes a new instance of the class. + /// + /// Path to audiobook file. + /// File type. + /// Number of part this file represents. + /// Number of chapter this file represents. + /// Indication if we are looking at file or directory. + public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default, bool isDirectory = default) + { + Path = path; + Container = container; + PartNumber = partNumber; + ChapterNumber = chapterNumber; + IsDirectory = isDirectory; + } + /// /// Gets or sets the path. /// @@ -38,7 +55,7 @@ namespace Emby.Naming.AudioBook public bool IsDirectory { get; set; } /// - public int CompareTo(AudioBookFileInfo other) + public int CompareTo(AudioBookFileInfo? other) { if (ReferenceEquals(this, other)) { diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index b0b5bd881f..fba11ea726 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -10,11 +10,13 @@ namespace Emby.Naming.AudioBook /// /// Initializes a new instance of the class. /// - public AudioBookInfo() + /// Name of audiobook. + public AudioBookInfo(string name) { Files = new List(); Extras = new List(); AlternateVersions = new List(); + Name = name; } /// diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index f4ba11a0d1..f350e5a4ae 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 +using System; using System.Collections.Generic; using System.Linq; using Emby.Naming.Common; @@ -23,7 +24,7 @@ namespace Emby.Naming.AudioBook var audiobookFileInfos = files .Select(i => audioBookResolver.Resolve(i.FullName, i.IsDirectory)) - .Where(i => i != null) + .OfType() .ToList(); // Filter out all extras, otherwise they could cause stacks to not be resolved @@ -36,9 +37,10 @@ namespace Emby.Naming.AudioBook foreach (var stack in stackResult) { - var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).ToList(); + var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).OfType().ToList(); stackFiles.Sort(); - var info = new AudioBookInfo { Files = stackFiles, Name = stack.Name }; + // TODO nullable discover if name can be empty + var info = new AudioBookInfo(stack.Name ?? string.Empty) { Files = stackFiles }; yield return info; } diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index 5807d4688c..e76cfd744d 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -42,14 +42,12 @@ namespace Emby.Naming.AudioBook var parsingResult = new AudioBookFilePathParser(_options).Parse(path); - return new AudioBookFileInfo - { - Path = path, - Container = container, - ChapterNumber = parsingResult.ChapterNumber, - PartNumber = parsingResult.PartNumber, - IsDirectory = isDirectory - }; + return new AudioBookFileInfo( + path, + container, + chapterNumber: parsingResult.ChapterNumber, + partNumber: parsingResult.PartNumber, + isDirectory: isDirectory ); } } } diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs index ed6ba8881c..00b27541a6 100644 --- a/Emby.Naming/Common/EpisodeExpression.cs +++ b/Emby.Naming/Common/EpisodeExpression.cs @@ -8,11 +8,11 @@ namespace Emby.Naming.Common public class EpisodeExpression { private string _expression; - private Regex _regex; + private Regex? _regex; public EpisodeExpression(string expression, bool byDate) { - Expression = expression; + _expression = expression; IsByDate = byDate; DateTimeFormats = Array.Empty(); SupportsAbsoluteEpisodeNumbers = true; diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index fd4244f64d..78bb6242d6 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -75,56 +75,45 @@ namespace Emby.Naming.Common StubTypes = new[] { - new StubTypeRule - { - StubType = "dvd", - Token = "dvd" - }, - new StubTypeRule - { - StubType = "hddvd", - Token = "hddvd" - }, - new StubTypeRule - { - StubType = "bluray", - Token = "bluray" - }, - new StubTypeRule - { - StubType = "bluray", - Token = "brrip" - }, - new StubTypeRule - { - StubType = "bluray", - Token = "bd25" - }, - new StubTypeRule - { - StubType = "bluray", - Token = "bd50" - }, - new StubTypeRule - { - StubType = "vhs", - Token = "vhs" - }, - new StubTypeRule - { - StubType = "tv", - Token = "HDTV" - }, - new StubTypeRule - { - StubType = "tv", - Token = "PDTV" - }, - new StubTypeRule - { - StubType = "tv", - Token = "DSR" - } + new StubTypeRule( + stubType: "dvd", + token: "dvd"), + + new StubTypeRule( + stubType: "hddvd", + token: "hddvd"), + + new StubTypeRule( + stubType: "bluray", + token: "bluray"), + + new StubTypeRule( + stubType: "bluray", + token: "brrip"), + + new StubTypeRule( + stubType: "bluray", + token: "bd25"), + + new StubTypeRule( + stubType: "bluray", + token: "bd50"), + + new StubTypeRule( + stubType: "vhs", + token: "vhs"), + + new StubTypeRule( + stubType: "tv", + token: "HDTV"), + + new StubTypeRule( + stubType: "tv", + token: "PDTV"), + + new StubTypeRule( + stubType: "tv", + token: "DSR") }; VideoFileStackingExpressions = new[] @@ -381,247 +370,193 @@ namespace Emby.Naming.Common VideoExtraRules = new[] { - new ExtraRule - { - ExtraType = ExtraType.Trailer, - RuleType = ExtraRuleType.Filename, - Token = "trailer", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Trailer, - RuleType = ExtraRuleType.Suffix, - Token = "-trailer", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Trailer, - RuleType = ExtraRuleType.Suffix, - Token = ".trailer", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Trailer, - RuleType = ExtraRuleType.Suffix, - Token = "_trailer", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Trailer, - RuleType = ExtraRuleType.Suffix, - Token = " trailer", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.Filename, - Token = "sample", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.Suffix, - Token = "-sample", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.Suffix, - Token = ".sample", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.Suffix, - Token = "_sample", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.Suffix, - Token = " sample", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.ThemeSong, - RuleType = ExtraRuleType.Filename, - Token = "theme", - MediaType = MediaType.Audio - }, - new ExtraRule - { - ExtraType = ExtraType.Scene, - RuleType = ExtraRuleType.Suffix, - Token = "-scene", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Clip, - RuleType = ExtraRuleType.Suffix, - Token = "-clip", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Interview, - RuleType = ExtraRuleType.Suffix, - Token = "-interview", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.BehindTheScenes, - RuleType = ExtraRuleType.Suffix, - Token = "-behindthescenes", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.DeletedScene, - RuleType = ExtraRuleType.Suffix, - Token = "-deleted", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Clip, - RuleType = ExtraRuleType.Suffix, - Token = "-featurette", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.Clip, - RuleType = ExtraRuleType.Suffix, - Token = "-short", - MediaType = MediaType.Video - }, - new ExtraRule - { - ExtraType = ExtraType.BehindTheScenes, - RuleType = ExtraRuleType.DirectoryName, - Token = "behind the scenes", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.DeletedScene, - RuleType = ExtraRuleType.DirectoryName, - Token = "deleted scenes", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Interview, - RuleType = ExtraRuleType.DirectoryName, - Token = "interviews", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Scene, - RuleType = ExtraRuleType.DirectoryName, - Token = "scenes", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Sample, - RuleType = ExtraRuleType.DirectoryName, - Token = "samples", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Clip, - RuleType = ExtraRuleType.DirectoryName, - Token = "shorts", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Clip, - RuleType = ExtraRuleType.DirectoryName, - Token = "featurettes", - MediaType = MediaType.Video, - }, - new ExtraRule - { - ExtraType = ExtraType.Unknown, - RuleType = ExtraRuleType.DirectoryName, - Token = "extras", - MediaType = MediaType.Video, - }, + new ExtraRule( + ExtraType.Trailer, + ExtraRuleType.Filename, + "trailer", + MediaType.Video), + + new ExtraRule( + ExtraType.Trailer, + ExtraRuleType.Suffix, + "-trailer", + MediaType.Video), + + new ExtraRule( + ExtraType.Trailer, + ExtraRuleType.Suffix, + ".trailer", + MediaType.Video), + + new ExtraRule( + ExtraType.Trailer, + ExtraRuleType.Suffix, + "_trailer", + MediaType.Video), + + new ExtraRule( + ExtraType.Trailer, + ExtraRuleType.Suffix, + " trailer", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.Filename, + "sample", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.Suffix, + "-sample", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.Suffix, + ".sample", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.Suffix, + "_sample", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.Suffix, + " sample", + MediaType.Video), + + new ExtraRule( + ExtraType.ThemeSong, + ExtraRuleType.Filename, + "theme", + MediaType.Audio), + + new ExtraRule( + ExtraType.Scene, + ExtraRuleType.Suffix, + "-scene", + MediaType.Video), + + new ExtraRule( + ExtraType.Clip, + ExtraRuleType.Suffix, + "-clip", + MediaType.Video), + + new ExtraRule( + ExtraType.Interview, + ExtraRuleType.Suffix, + "-interview", + MediaType.Video), + + new ExtraRule( + ExtraType.BehindTheScenes, + ExtraRuleType.Suffix, + "-behindthescenes", + MediaType.Video), + + new ExtraRule( + ExtraType.DeletedScene, + ExtraRuleType.Suffix, + "-deleted", + MediaType.Video), + + new ExtraRule( + ExtraType.Clip, + ExtraRuleType.Suffix, + "-featurette", + MediaType.Video), + + new ExtraRule( + ExtraType.Clip, + ExtraRuleType.Suffix, + "-short", + MediaType.Video), + + new ExtraRule( + ExtraType.BehindTheScenes, + ExtraRuleType.DirectoryName, + "behind the scenes", + MediaType.Video), + + new ExtraRule( + ExtraType.DeletedScene, + ExtraRuleType.DirectoryName, + "deleted scenes", + MediaType.Video), + + new ExtraRule( + ExtraType.Interview, + ExtraRuleType.DirectoryName, + "interviews", + MediaType.Video), + + new ExtraRule( + ExtraType.Scene, + ExtraRuleType.DirectoryName, + "scenes", + MediaType.Video), + + new ExtraRule( + ExtraType.Sample, + ExtraRuleType.DirectoryName, + "samples", + MediaType.Video), + + new ExtraRule( + ExtraType.Clip, + ExtraRuleType.DirectoryName, + "shorts", + MediaType.Video), + + new ExtraRule( + ExtraType.Clip, + ExtraRuleType.DirectoryName, + "featurettes", + MediaType.Video), + + new ExtraRule( + ExtraType.Unknown, + ExtraRuleType.DirectoryName, + "extras", + MediaType.Video), }; Format3DRules = new[] { // Kodi rules: - new Format3DRule - { - PreceedingToken = "3d", - Token = "hsbs" - }, - new Format3DRule - { - PreceedingToken = "3d", - Token = "sbs" - }, - new Format3DRule - { - PreceedingToken = "3d", - Token = "htab" - }, - new Format3DRule - { - PreceedingToken = "3d", - Token = "tab" - }, - // Media Browser rules: - new Format3DRule - { - Token = "fsbs" - }, - new Format3DRule - { - Token = "hsbs" - }, - new Format3DRule - { - Token = "sbs" - }, - new Format3DRule - { - Token = "ftab" - }, - new Format3DRule - { - Token = "htab" - }, - new Format3DRule - { - Token = "tab" - }, - new Format3DRule - { - Token = "sbs3d" - }, - new Format3DRule - { - Token = "mvc" - } + new Format3DRule( + preceedingToken: "3d", + token: "hsbs"), + + new Format3DRule( + preceedingToken: "3d", + token: "sbs"), + + new Format3DRule( + preceedingToken: "3d", + token: "htab"), + + new Format3DRule( + preceedingToken: "3d", + token: "tab"), + + // Media Browser rules: + new Format3DRule("fsbs"), + new Format3DRule("hsbs"), + new Format3DRule("sbs"), + new Format3DRule("ftab"), + new Format3DRule("htab"), + new Format3DRule("tab"), + new Format3DRule("sbs3d"), + new Format3DRule("mvc") }; + AudioBookPartsExpressions = new[] { // Detect specified chapters, like CH 01 @@ -737,15 +672,15 @@ namespace Emby.Naming.Common public ExtraRule[] VideoExtraRules { get; set; } - public Regex[] VideoFileStackingRegexes { get; private set; } + public Regex[] VideoFileStackingRegexes { get; private set; } = Array.Empty(); - public Regex[] CleanDateTimeRegexes { get; private set; } + public Regex[] CleanDateTimeRegexes { get; private set; } = Array.Empty(); - public Regex[] CleanStringRegexes { get; private set; } + public Regex[] CleanStringRegexes { get; private set; } = Array.Empty(); - public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } + public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } = Array.Empty(); - public Regex[] EpisodeMultiPartRegexes { get; private set; } + public Regex[] EpisodeMultiPartRegexes { get; private set; } = Array.Empty(); public void Compile() { diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 6857f9952c..93770b1561 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -14,6 +14,7 @@ true true snupkg + enable diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs index f39c496b7a..2f16fb2df9 100644 --- a/Emby.Naming/Subtitles/SubtitleInfo.cs +++ b/Emby.Naming/Subtitles/SubtitleInfo.cs @@ -4,6 +4,13 @@ namespace Emby.Naming.Subtitles { public class SubtitleInfo { + public SubtitleInfo(string path, bool isDefault, bool isForced) + { + Path = path; + IsDefault = isDefault; + IsForced = isForced; + } + /// /// Gets or sets the path. /// @@ -14,7 +21,7 @@ namespace Emby.Naming.Subtitles /// Gets or sets the language. /// /// The language. - public string Language { get; set; } + public string? Language { get; set; } /// /// Gets or sets a value indicating whether this instance is default. diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index 24e59f90a3..c8659e1b26 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -31,12 +31,10 @@ namespace Emby.Naming.Subtitles } var flags = GetFlags(path); - var info = new SubtitleInfo - { - Path = path, - IsDefault = _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)), - IsForced = _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)) - }; + var info = new SubtitleInfo( + path, + _options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase)), + _options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparer.OrdinalIgnoreCase))); var parts = flags.Where(i => !_options.SubtitleDefaultFlags.Contains(i, StringComparer.OrdinalIgnoreCase) && !_options.SubtitleForcedFlags.Contains(i, StringComparer.OrdinalIgnoreCase)) diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs index 250df4e2d3..a9ee82da36 100644 --- a/Emby.Naming/TV/EpisodeInfo.cs +++ b/Emby.Naming/TV/EpisodeInfo.cs @@ -4,6 +4,11 @@ namespace Emby.Naming.TV { public class EpisodeInfo { + public EpisodeInfo(string path) + { + Path = path; + } + /// /// Gets or sets the path. /// @@ -14,19 +19,19 @@ namespace Emby.Naming.TV /// Gets or sets the container. /// /// The container. - public string Container { get; set; } + public string? Container { get; set; } /// /// Gets or sets the name of the series. /// /// The name of the series. - public string SeriesName { get; set; } + public string? SeriesName { get; set; } /// /// Gets or sets the format3 d. /// /// The format3 d. - public string Format3D { get; set; } + public string? Format3D { get; set; } /// /// Gets or sets a value indicating whether [is3 d]. @@ -44,7 +49,7 @@ namespace Emby.Naming.TV /// Gets or sets the type of the stub. /// /// The type of the stub. - public string StubType { get; set; } + public string? StubType { get; set; } public int? SeasonNumber { get; set; } diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs index 05f921edc9..9c48d07a3b 100644 --- a/Emby.Naming/TV/EpisodePathParserResult.cs +++ b/Emby.Naming/TV/EpisodePathParserResult.cs @@ -10,7 +10,7 @@ namespace Emby.Naming.TV public int? EndingEpsiodeNumber { get; set; } - public string SeriesName { get; set; } + public string? SeriesName { get; set; } public bool Success { get; set; } diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 6994f69fc4..002de21175 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -54,9 +54,8 @@ namespace Emby.Naming.TV var parsingResult = new EpisodePathParser(_options) .Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo); - return new EpisodeInfo + return new EpisodeInfo(path) { - Path = path, Container = container, IsStub = isStub, EndingEpsiodeNumber = parsingResult.EndingEpsiodeNumber, diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs index 15db32e876..6be7e60525 100644 --- a/Emby.Naming/Video/ExtraResult.cs +++ b/Emby.Naming/Video/ExtraResult.cs @@ -16,6 +16,6 @@ namespace Emby.Naming.Video /// Gets or sets the rule. /// /// The rule. - public ExtraRule Rule { get; set; } + public ExtraRule? Rule { get; set; } } } diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs index 7c9702e244..c018894fdf 100644 --- a/Emby.Naming/Video/ExtraRule.cs +++ b/Emby.Naming/Video/ExtraRule.cs @@ -10,6 +10,14 @@ namespace Emby.Naming.Video /// public class ExtraRule { + public ExtraRule(ExtraType extraType, ExtraRuleType ruleType, string token, MediaType mediaType) + { + Token = token; + ExtraType = extraType; + RuleType = ruleType; + MediaType = mediaType; + } + /// /// Gets or sets the token to use for matching against the file path. /// diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs index 3ef190b865..b0a22b18b0 100644 --- a/Emby.Naming/Video/FileStack.cs +++ b/Emby.Naming/Video/FileStack.cs @@ -13,7 +13,7 @@ namespace Emby.Naming.Video Files = new List(); } - public string Name { get; set; } + public string Name { get; set; } = string.Empty; public List Files { get; set; } diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index 51c26af863..3a9eaa1a14 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -57,7 +57,7 @@ namespace Emby.Naming.Video else { var foundPrefix = false; - string format = null; + string? format = null; foreach (var flag in videoFlags) { diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs index fa0e9d3b80..36dc1c12b2 100644 --- a/Emby.Naming/Video/Format3DResult.cs +++ b/Emby.Naming/Video/Format3DResult.cs @@ -21,7 +21,7 @@ namespace Emby.Naming.Video /// Gets or sets the format3 d. /// /// The format3 d. - public string Format3D { get; set; } + public string? Format3D { get; set; } /// /// Gets or sets the tokens. diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs index 310ec84e8f..a35f0d9d97 100644 --- a/Emby.Naming/Video/Format3DRule.cs +++ b/Emby.Naming/Video/Format3DRule.cs @@ -4,6 +4,12 @@ namespace Emby.Naming.Video { public class Format3DRule { + public Format3DRule(string token, string? preceedingToken = null) + { + Token = token; + PreceedingToken = preceedingToken; + } + /// /// Gets or sets the token. /// @@ -14,6 +20,6 @@ namespace Emby.Naming.Video /// Gets or sets the preceeding token. /// /// The preceeding token. - public string PreceedingToken { get; set; } + public string? PreceedingToken { get; set; } } } diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs index 8285cb51a3..fa42af6049 100644 --- a/Emby.Naming/Video/StubTypeRule.cs +++ b/Emby.Naming/Video/StubTypeRule.cs @@ -4,6 +4,12 @@ namespace Emby.Naming.Video { public class StubTypeRule { + public StubTypeRule(string token, string stubType) + { + Token = token; + StubType = stubType; + } + /// /// Gets or sets the token. /// diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 11e789b663..12bd8c4364 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -11,19 +11,19 @@ namespace Emby.Naming.Video /// Gets or sets the path. /// /// The path. - public string Path { get; set; } + public string? Path { get; set; } /// /// Gets or sets the container. /// /// The container. - public string Container { get; set; } + public string? Container { get; set; } /// /// Gets or sets the name. /// /// The name. - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the year. @@ -41,13 +41,13 @@ namespace Emby.Naming.Video /// Gets or sets the extra rule. /// /// The extra rule. - public ExtraRule ExtraRule { get; set; } + public ExtraRule? ExtraRule { get; set; } /// /// Gets or sets the format3 d. /// /// The format3 d. - public string Format3D { get; set; } + public string? Format3D { get; set; } /// /// Gets or sets a value indicating whether [is3 d]. @@ -65,7 +65,7 @@ namespace Emby.Naming.Video /// Gets or sets the type of the stub. /// /// The type of the stub. - public string StubType { get; set; } + public string? StubType { get; set; } /// /// Gets or sets a value indicating whether this instance is a directory. diff --git a/Emby.Naming/Video/VideoInfo.cs b/Emby.Naming/Video/VideoInfo.cs index ea74c40e2a..930fdb33f8 100644 --- a/Emby.Naming/Video/VideoInfo.cs +++ b/Emby.Naming/Video/VideoInfo.cs @@ -12,7 +12,7 @@ namespace Emby.Naming.Video /// Initializes a new instance of the class. /// /// The name. - public VideoInfo(string name) + public VideoInfo(string? name) { Name = name; @@ -25,7 +25,7 @@ namespace Emby.Naming.Video /// Gets or sets the name. /// /// The name. - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the year. diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 948fe037b5..601c6c0b6d 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -26,7 +26,8 @@ namespace Emby.Naming.Video var videoInfos = files .Select(i => videoResolver.Resolve(i.FullName, i.IsDirectory)) - .Where(i => i != null) + // .Where(i => i != null) + .OfType() .ToList(); // Filter out all extras, otherwise they could cause stacks to not be resolved @@ -39,7 +40,7 @@ namespace Emby.Naming.Video .Resolve(nonExtras).ToList(); var remainingFiles = videoInfos - .Where(i => !stackResult.Any(s => s.ContainsFile(i.Path, i.IsDirectory))) + .Where(i => !stackResult.Any(s => i.Path != null && s.ContainsFile(i.Path, i.IsDirectory))) .ToList(); var list = new List(); @@ -48,7 +49,9 @@ namespace Emby.Naming.Video { var info = new VideoInfo(stack.Name) { - Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)).ToList() + Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)) + .OfType() + .ToList() }; info.Year = info.Files[0].Year; @@ -203,7 +206,7 @@ namespace Emby.Naming.Video return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2; } - private bool IsEligibleForMultiVersion(string folderName, string testFilename) + private bool IsEligibleForMultiVersion(string folderName, string? testFilename) { testFilename = Path.GetFileNameWithoutExtension(testFilename) ?? string.Empty; diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index b4aee614b0..b9ff90179f 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -22,7 +22,7 @@ namespace Emby.Naming.Video /// /// The path. /// VideoFileInfo. - public VideoFileInfo? ResolveDirectory(string path) + public VideoFileInfo? ResolveDirectory(string? path) { return Resolve(path, true); } @@ -32,7 +32,7 @@ namespace Emby.Naming.Video /// /// The path. /// VideoFileInfo. - public VideoFileInfo? ResolveFile(string path) + public VideoFileInfo? ResolveFile(string? path) { return Resolve(path, false); } @@ -45,7 +45,7 @@ namespace Emby.Naming.Video /// Whether or not the name should be parsed for info. /// VideoFileInfo. /// path is null. - public VideoFileInfo? Resolve(string path, bool isDirectory, bool parseName = true) + public VideoFileInfo? Resolve(string? path, bool isDirectory, bool parseName = true) { if (string.IsNullOrEmpty(path)) { diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 00282b71a5..e121e9eaf1 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2470,9 +2470,10 @@ namespace Emby.Server.Implementations.Library var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd; + // TODO nullable - what are we trying to do there with empty episodeInfo? var episodeInfo = episode.IsFileProtocol - ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new Naming.TV.EpisodeInfo() - : new Naming.TV.EpisodeInfo(); + ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new Naming.TV.EpisodeInfo(episode.Path) + : new Naming.TV.EpisodeInfo(episode.Path); try { diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index e716a6610f..777136f8bf 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -1,4 +1,4 @@ - + @@ -20,7 +20,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs index a214bc57c4..cf21f964e2 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookFileInfoTests.cs @@ -1,4 +1,4 @@ -using Emby.Naming.AudioBook; +using Emby.Naming.AudioBook; using Xunit; namespace Jellyfin.Naming.Tests.AudioBook @@ -8,22 +8,22 @@ namespace Jellyfin.Naming.Tests.AudioBook [Fact] public void CompareTo_Same_Success() { - var info = new AudioBookFileInfo(); + var info = new AudioBookFileInfo(string.Empty, string.Empty); Assert.Equal(0, info.CompareTo(info)); } [Fact] public void CompareTo_Null_Success() { - var info = new AudioBookFileInfo(); + var info = new AudioBookFileInfo(string.Empty, string.Empty); Assert.Equal(1, info.CompareTo(null)); } [Fact] public void CompareTo_Empty_Success() { - var info1 = new AudioBookFileInfo(); - var info2 = new AudioBookFileInfo(); + var info1 = new AudioBookFileInfo(string.Empty, string.Empty); + var info2 = new AudioBookFileInfo(string.Empty, string.Empty); Assert.Equal(0, info1.CompareTo(info2)); } } diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index 673289436d..2708d80bb6 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Emby.Naming.AudioBook; using Emby.Naming.Common; @@ -14,30 +14,24 @@ namespace Jellyfin.Naming.Tests.AudioBook { yield return new object[] { - new AudioBookFileInfo() - { - Path = @"/server/AudioBooks/Larry Potter/Larry Potter.mp3", - Container = "mp3", - } + new AudioBookFileInfo( + @"/server/AudioBooks/Larry Potter/Larry Potter.mp3", + "mp3") }; yield return new object[] { - new AudioBookFileInfo() - { - Path = @"/server/AudioBooks/Berry Potter/Chapter 1 .ogg", - Container = "ogg", - ChapterNumber = 1 - } + new AudioBookFileInfo( + @"/server/AudioBooks/Berry Potter/Chapter 1 .ogg", + "ogg", + chapterNumber: 1) }; yield return new object[] { - new AudioBookFileInfo() - { - Path = @"/server/AudioBooks/Nerry Potter/Part 3 - Chapter 2.mp3", - Container = "mp3", - ChapterNumber = 2, - PartNumber = 3 - } + new AudioBookFileInfo( + @"/server/AudioBooks/Nerry Potter/Part 3 - Chapter 2.mp3", + "mp3", + chapterNumber: 2, + partNumber: 3) }; } From 60b49e67eafd356d1276f43de1a3f1f2fe52fe3f Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 11:19:22 +0100 Subject: [PATCH 0179/1930] Re-Sharper inspection issues --- .../AudioBook/AudioBookListResolver.cs | 1 - Emby.Naming/AudioBook/AudioBookResolver.cs | 2 +- Emby.Naming/Common/NamingOptions.cs | 12 +++++++----- Emby.Naming/Emby.Naming.csproj | 2 +- Emby.Naming/TV/EpisodeInfo.cs | 2 +- Emby.Naming/TV/EpisodePathParser.cs | 8 ++++---- Emby.Naming/TV/EpisodePathParserResult.cs | 2 +- Emby.Naming/TV/EpisodeResolver.cs | 2 +- Emby.Naming/TV/SeasonPathParser.cs | 12 ++++++------ Emby.Naming/Video/ExtraRuleType.cs | 2 +- Emby.Naming/Video/FlagParser.cs | 4 ++-- Emby.Naming/Video/Format3DParser.cs | 14 +++++++------- Emby.Naming/Video/Format3DRule.cs | 10 +++++----- Emby.Naming/Video/StubResult.cs | 19 ------------------- Emby.Naming/Video/VideoListResolver.cs | 2 +- .../Library/LibraryManager.cs | 4 ++-- .../TV/MultiEpisodeTests.cs | 2 +- 17 files changed, 41 insertions(+), 59 deletions(-) delete mode 100644 Emby.Naming/Video/StubResult.cs diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index f350e5a4ae..179a3bc073 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 -using System; using System.Collections.Generic; using System.Linq; using Emby.Naming.Common; diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index e76cfd744d..56442fc4ee 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -47,7 +47,7 @@ namespace Emby.Naming.AudioBook container, chapterNumber: parsingResult.ChapterNumber, partNumber: parsingResult.PartNumber, - isDirectory: isDirectory ); + isDirectory: isDirectory); } } } diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 78bb6242d6..537de63d55 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -6,6 +6,8 @@ using System.Text.RegularExpressions; using Emby.Naming.Video; using MediaBrowser.Model.Entities; +// ReSharper disable StringLiteralTypo + namespace Emby.Naming.Common { public class NamingOptions @@ -531,19 +533,19 @@ namespace Emby.Naming.Common { // Kodi rules: new Format3DRule( - preceedingToken: "3d", + precedingToken: "3d", token: "hsbs"), new Format3DRule( - preceedingToken: "3d", + precedingToken: "3d", token: "sbs"), new Format3DRule( - preceedingToken: "3d", + precedingToken: "3d", token: "htab"), new Format3DRule( - preceedingToken: "3d", + precedingToken: "3d", token: "tab"), // Media Browser rules: @@ -608,7 +610,7 @@ namespace Emby.Naming.Common ".mxf" }); - MultipleEpisodeExpressions = new string[] + MultipleEpisodeExpressions = new[] { @".*(\\|\/)[sS]?(?[0-9]{1,4})[xX](?[0-9]{1,3})((-| - )[0-9]{1,4}[eExX](?[0-9]{1,3}))+[^\\\/]*$", @".*(\\|\/)[sS]?(?[0-9]{1,4})[xX](?[0-9]{1,3})((-| - )[0-9]{1,4}[xX][eE](?[0-9]{1,3}))+[^\\\/]*$", diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 93770b1561..b7fd0c5455 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -39,7 +39,7 @@ - + diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs index a9ee82da36..e01c810628 100644 --- a/Emby.Naming/TV/EpisodeInfo.cs +++ b/Emby.Naming/TV/EpisodeInfo.cs @@ -55,7 +55,7 @@ namespace Emby.Naming.TV public int? EpisodeNumber { get; set; } - public int? EndingEpsiodeNumber { get; set; } + public int? EndingEpisodeNumber { get; set; } public int? Year { get; set; } diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index a6af689c72..866d8adc00 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -146,7 +146,7 @@ namespace Emby.Naming.TV { if (int.TryParse(endingNumberGroup.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out num)) { - result.EndingEpsiodeNumber = num; + result.EndingEpisodeNumber = num; } } } @@ -217,13 +217,13 @@ namespace Emby.Naming.TV info.SeriesName = result.SeriesName; } - if (!info.EndingEpsiodeNumber.HasValue && info.EpisodeNumber.HasValue) + if (!info.EndingEpisodeNumber.HasValue && info.EpisodeNumber.HasValue) { - info.EndingEpsiodeNumber = result.EndingEpsiodeNumber; + info.EndingEpisodeNumber = result.EndingEpisodeNumber; } if (!string.IsNullOrEmpty(info.SeriesName) - && (!info.EpisodeNumber.HasValue || info.EndingEpsiodeNumber.HasValue)) + && (!info.EpisodeNumber.HasValue || info.EndingEpisodeNumber.HasValue)) { break; } diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs index 9c48d07a3b..5fa0b6f0b4 100644 --- a/Emby.Naming/TV/EpisodePathParserResult.cs +++ b/Emby.Naming/TV/EpisodePathParserResult.cs @@ -8,7 +8,7 @@ namespace Emby.Naming.TV public int? EpisodeNumber { get; set; } - public int? EndingEpsiodeNumber { get; set; } + public int? EndingEpisodeNumber { get; set; } public string? SeriesName { get; set; } diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 002de21175..5f02c553de 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -58,7 +58,7 @@ namespace Emby.Naming.TV { Container = container, IsStub = isStub, - EndingEpsiodeNumber = parsingResult.EndingEpsiodeNumber, + EndingEpisodeNumber = parsingResult.EndingEpisodeNumber, EpisodeNumber = parsingResult.EpisodeNumber, SeasonNumber = parsingResult.SeasonNumber, SeriesName = parsingResult.SeriesName, diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index d2e324dda5..142680f0cd 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -101,9 +101,9 @@ namespace Emby.Naming.TV } var parts = filename.Split(new[] { '.', '_', ' ', '-' }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < parts.Length; i++) + foreach (var part in parts) { - if (TryGetSeasonNumberFromPart(parts[i], out int seasonNumber)) + if (TryGetSeasonNumberFromPart(part, out int seasonNumber)) { return (seasonNumber, true); } @@ -139,7 +139,7 @@ namespace Emby.Naming.TV var numericStart = -1; var length = 0; - var hasOpenParenth = false; + var hasOpenParenthesis = false; var isSeasonFolder = true; // Find out where the numbers start, and then keep going until they end @@ -147,7 +147,7 @@ namespace Emby.Naming.TV { if (char.IsNumber(path[i])) { - if (!hasOpenParenth) + if (!hasOpenParenthesis) { if (numericStart == -1) { @@ -167,11 +167,11 @@ namespace Emby.Naming.TV var currentChar = path[i]; if (currentChar == '(') { - hasOpenParenth = true; + hasOpenParenthesis = true; } else if (currentChar == ')') { - hasOpenParenth = false; + hasOpenParenthesis = false; } } diff --git a/Emby.Naming/Video/ExtraRuleType.cs b/Emby.Naming/Video/ExtraRuleType.cs index e89876f4ae..98114c7e8b 100644 --- a/Emby.Naming/Video/ExtraRuleType.cs +++ b/Emby.Naming/Video/ExtraRuleType.cs @@ -22,6 +22,6 @@ namespace Emby.Naming.Video /// /// Match against the name of the directory containing the file. /// - DirectoryName = 3, + DirectoryName = 3 } } diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs index a8bd9d5c5d..27ca1abf1a 100644 --- a/Emby.Naming/Video/FlagParser.cs +++ b/Emby.Naming/Video/FlagParser.cs @@ -20,7 +20,7 @@ namespace Emby.Naming.Video return GetFlags(path, _options.VideoFlagDelimiters); } - public string[] GetFlags(string path, char[] delimeters) + public string[] GetFlags(string path, char[] delimiters) { if (string.IsNullOrEmpty(path)) { @@ -31,7 +31,7 @@ namespace Emby.Naming.Video var file = Path.GetFileName(path); - return file.Split(delimeters, StringSplitOptions.RemoveEmptyEntries); + return file.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); } } } diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index 3a9eaa1a14..fb881f978f 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -18,11 +18,11 @@ namespace Emby.Naming.Video public Format3DResult Parse(string path) { int oldLen = _options.VideoFlagDelimiters.Length; - var delimeters = new char[oldLen + 1]; - _options.VideoFlagDelimiters.CopyTo(delimeters, 0); - delimeters[oldLen] = ' '; + var delimiters = new char[oldLen + 1]; + _options.VideoFlagDelimiters.CopyTo(delimiters, 0); + delimiters[oldLen] = ' '; - return Parse(new FlagParser(_options).GetFlags(path, delimeters)); + return Parse(new FlagParser(_options).GetFlags(path, delimiters)); } internal Format3DResult Parse(string[] videoFlags) @@ -44,7 +44,7 @@ namespace Emby.Naming.Video { var result = new Format3DResult(); - if (string.IsNullOrEmpty(rule.PreceedingToken)) + if (string.IsNullOrEmpty(rule.PrecedingToken)) { result.Format3D = new[] { rule.Token }.FirstOrDefault(i => videoFlags.Contains(i, StringComparer.OrdinalIgnoreCase)); result.Is3D = !string.IsNullOrEmpty(result.Format3D); @@ -63,7 +63,7 @@ namespace Emby.Naming.Video { if (foundPrefix) { - result.Tokens.Add(rule.PreceedingToken); + result.Tokens.Add(rule.PrecedingToken); if (string.Equals(rule.Token, flag, StringComparison.OrdinalIgnoreCase)) { @@ -74,7 +74,7 @@ namespace Emby.Naming.Video break; } - foundPrefix = string.Equals(flag, rule.PreceedingToken, StringComparison.OrdinalIgnoreCase); + foundPrefix = string.Equals(flag, rule.PrecedingToken, StringComparison.OrdinalIgnoreCase); } result.Is3D = foundPrefix && !string.IsNullOrEmpty(format); diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs index a35f0d9d97..7679164b30 100644 --- a/Emby.Naming/Video/Format3DRule.cs +++ b/Emby.Naming/Video/Format3DRule.cs @@ -4,10 +4,10 @@ namespace Emby.Naming.Video { public class Format3DRule { - public Format3DRule(string token, string? preceedingToken = null) + public Format3DRule(string token, string? precedingToken = null) { Token = token; - PreceedingToken = preceedingToken; + PrecedingToken = precedingToken; } /// @@ -17,9 +17,9 @@ namespace Emby.Naming.Video public string Token { get; set; } /// - /// Gets or sets the preceeding token. + /// Gets or sets the preceding token. /// - /// The preceeding token. - public string? PreceedingToken { get; set; } + /// The preceding token. + public string? PrecedingToken { get; set; } } } diff --git a/Emby.Naming/Video/StubResult.cs b/Emby.Naming/Video/StubResult.cs deleted file mode 100644 index 1b8e99b0dc..0000000000 --- a/Emby.Naming/Video/StubResult.cs +++ /dev/null @@ -1,19 +0,0 @@ -#pragma warning disable CS1591 - -namespace Emby.Naming.Video -{ - public struct StubResult - { - /// - /// Gets or sets a value indicating whether this instance is stub. - /// - /// true if this instance is stub; otherwise, false. - public bool IsStub { get; set; } - - /// - /// Gets or sets the type of the stub. - /// - /// The type of the stub. - public string StubType { get; set; } - } -} diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 601c6c0b6d..190562cfcd 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -136,7 +136,7 @@ namespace Emby.Naming.Video } // If there's only one video, accept all trailers - // Be lenient because people use all kinds of mish mash conventions with trailers + // Be lenient because people use all kinds of mishmash conventions with trailers if (list.Count == 1) { var trailers = remainingFiles diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index e121e9eaf1..6f85a24089 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2562,12 +2562,12 @@ namespace Emby.Server.Implementations.Library if (!episode.IndexNumberEnd.HasValue || forceRefresh) { - if (episode.IndexNumberEnd != episodeInfo.EndingEpsiodeNumber) + if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber) { changed = true; } - episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber; + episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber; } if (!episode.ParentIndexNumber.HasValue || forceRefresh) diff --git a/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs index 3513050b64..58ea0bec59 100644 --- a/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/MultiEpisodeTests.cs @@ -74,7 +74,7 @@ namespace Jellyfin.Naming.Tests.TV var result = new EpisodePathParser(options) .Parse(filename, false); - Assert.Equal(result.EndingEpsiodeNumber, endingEpisodeNumber); + Assert.Equal(result.EndingEpisodeNumber, endingEpisodeNumber); } } } From 599e20ab9b760e6cd8300e8d0e401e1856518db5 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Sun, 1 Nov 2020 18:45:42 +0800 Subject: [PATCH 0180/1930] fix music directplay on Gelli --- Jellyfin.Api/Controllers/UniversalAudioController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 70848aed6c..a219a74cf8 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -274,7 +274,7 @@ namespace Jellyfin.Api.Controllers foreach (var cont in containers) { - var parts = RequestHelpers.Split(cont, ',', true); + var parts = RequestHelpers.Split(cont, '|', true); var audioCodecs = parts.Length == 1 ? null : string.Join(",", parts.Skip(1).ToArray()); From 6437cf69508076bab2d62bbe887f12b72d02f7b3 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 13:28:43 +0100 Subject: [PATCH 0181/1930] Removed Success property from AudioBookFilePathParserResult, since it was unused and consider only audiobooks that have chapter/page number in name makes no sense --- Emby.Naming/AudioBook/AudioBookFilePathParser.cs | 2 -- Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs | 2 -- 2 files changed, 4 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs index 14edd64926..56580f194b 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs @@ -52,8 +52,6 @@ namespace Emby.Naming.AudioBook } } - result.Success = result.ChapterNumber.HasValue || result.PartNumber.HasValue; - return result; } } diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs index 7bfc4479d2..b65d231dfd 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs @@ -8,7 +8,5 @@ namespace Emby.Naming.AudioBook public int? PartNumber { get; set; } public int? ChapterNumber { get; set; } - - public bool Success { get; set; } } } From e7a37bedfca159ab6a305833395aead07ccd872f Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 13:42:56 +0100 Subject: [PATCH 0182/1930] Simplify AudioBookResolver since there is no option of passing directories into it (AudioResolver.cs:179) and handling directories were not implemented anyway --- Emby.Naming/AudioBook/AudioBookFileInfo.cs | 10 +--------- Emby.Naming/AudioBook/AudioBookListResolver.cs | 8 ++++---- Emby.Naming/AudioBook/AudioBookResolver.cs | 11 ++--------- Emby.Naming/Video/StackResolver.cs | 15 ++++----------- 4 files changed, 11 insertions(+), 33 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookFileInfo.cs b/Emby.Naming/AudioBook/AudioBookFileInfo.cs index e5200416ee..862e396677 100644 --- a/Emby.Naming/AudioBook/AudioBookFileInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookFileInfo.cs @@ -14,14 +14,12 @@ namespace Emby.Naming.AudioBook /// File type. /// Number of part this file represents. /// Number of chapter this file represents. - /// Indication if we are looking at file or directory. - public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default, bool isDirectory = default) + public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default) { Path = path; Container = container; PartNumber = partNumber; ChapterNumber = chapterNumber; - IsDirectory = isDirectory; } /// @@ -48,12 +46,6 @@ namespace Emby.Naming.AudioBook /// The chapter number. public int? ChapterNumber { get; set; } - /// - /// Gets or sets a value indicating whether this instance is a directory. - /// - /// The type. - public bool IsDirectory { get; set; } - /// public int CompareTo(AudioBookFileInfo? other) { diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 179a3bc073..0d190c172e 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -22,21 +22,21 @@ namespace Emby.Naming.AudioBook var audioBookResolver = new AudioBookResolver(_options); var audiobookFileInfos = files - .Select(i => audioBookResolver.Resolve(i.FullName, i.IsDirectory)) + .Select(i => audioBookResolver.Resolve(i.FullName)) .OfType() .ToList(); // Filter out all extras, otherwise they could cause stacks to not be resolved // See the unit test TestStackedWithTrailer var metadata = audiobookFileInfos - .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory }); + .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = false }); var stackResult = new StackResolver(_options) - .ResolveAudioBooks(metadata); + .ResolveAudioBooks(audiobookFileInfos); foreach (var stack in stackResult) { - var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i, stack.IsDirectoryStack)).OfType().ToList(); + var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i)).OfType().ToList(); stackFiles.Sort(); // TODO nullable discover if name can be empty var info = new AudioBookInfo(stack.Name ?? string.Empty) { Files = stackFiles }; diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index 56442fc4ee..c9e8c76cbc 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -17,19 +17,13 @@ namespace Emby.Naming.AudioBook _options = options; } - public AudioBookFileInfo? Resolve(string path, bool isDirectory = false) + public AudioBookFileInfo? Resolve(string path) { if (path.Length == 0) { throw new ArgumentException("String can't be empty.", nameof(path)); } - // TODO - if (isDirectory) - { - return null; - } - var extension = Path.GetExtension(path); // Check supported extensions @@ -46,8 +40,7 @@ namespace Emby.Naming.AudioBook path, container, chapterNumber: parsingResult.ChapterNumber, - partNumber: parsingResult.PartNumber, - isDirectory: isDirectory); + partNumber: parsingResult.PartNumber); } } } diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index f733cd2620..ce3152739b 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Emby.Naming.AudioBook; using Emby.Naming.Common; using MediaBrowser.Model.IO; @@ -29,24 +30,16 @@ namespace Emby.Naming.Video return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = false })); } - public IEnumerable ResolveAudioBooks(IEnumerable files) + public IEnumerable ResolveAudioBooks(IEnumerable files) { - var groupedDirectoryFiles = files.GroupBy(file => - file.IsDirectory - ? file.FullName - : Path.GetDirectoryName(file.FullName)); + var groupedDirectoryFiles = files.GroupBy(file => Path.GetDirectoryName(file.Path)); foreach (var directory in groupedDirectoryFiles) { var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false }; foreach (var file in directory) { - if (file.IsDirectory) - { - continue; - } - - stack.Files.Add(file.FullName); + stack.Files.Add(file.Path); } yield return stack; From f39775dc3a813609454655c31dd5c6a1413cc890 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 17:10:48 +0100 Subject: [PATCH 0183/1930] Written test to finish coverage for AudioBookListResolver & AudioBookResolver and corrected some logical erros / unhandled exception --- .../AudioBook/AudioBookListResolver.cs | 20 ++++++---- Emby.Naming/AudioBook/AudioBookResolver.cs | 3 +- .../AudioBook/AudioBookListResolverTests.cs | 38 ++++++++++++++++++- .../AudioBook/AudioBookResolverTests.cs | 21 ++++++++-- 4 files changed, 69 insertions(+), 13 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 0d190c172e..795065a6c9 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -1,6 +1,8 @@ #pragma warning disable CS1591 +using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Emby.Naming.Common; using Emby.Naming.Video; @@ -21,25 +23,27 @@ namespace Emby.Naming.AudioBook { var audioBookResolver = new AudioBookResolver(_options); + // File with empty fullname will be sorted out here var audiobookFileInfos = files .Select(i => audioBookResolver.Resolve(i.FullName)) .OfType() .ToList(); - // Filter out all extras, otherwise they could cause stacks to not be resolved - // See the unit test TestStackedWithTrailer - var metadata = audiobookFileInfos - .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = false }); - var stackResult = new StackResolver(_options) .ResolveAudioBooks(audiobookFileInfos); foreach (var stack in stackResult) { - var stackFiles = stack.Files.Select(i => audioBookResolver.Resolve(i)).OfType().ToList(); + var stackFiles = stack.Files + .Select(i => audioBookResolver.Resolve(i)) + .OfType() + .ToList(); + stackFiles.Sort(); - // TODO nullable discover if name can be empty - var info = new AudioBookInfo(stack.Name ?? string.Empty) { Files = stackFiles }; + + // stack.Name can be empty when we have file without folder, but always have some files + var name = string.IsNullOrEmpty(stack.Name) ? stack.Files[0] : stack.Name; + var info = new AudioBookInfo(name) { Files = stackFiles }; yield return info; } diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index c9e8c76cbc..542d6fee51 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -21,7 +21,8 @@ namespace Emby.Naming.AudioBook { if (path.Length == 0) { - throw new ArgumentException("String can't be empty.", nameof(path)); + // Return null to indicate this path will not be used, instead of stopping whole process with exception + return null; } var extension = Path.GetExtension(path); diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index 1084e20bda..d912b0e907 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Emby.Naming.AudioBook; using Emby.Naming.Common; using MediaBrowser.Model.IO; @@ -82,6 +83,41 @@ namespace Jellyfin.Naming.Tests.AudioBook Assert.Single(result); } + [Fact] + public void TestWithoutFolder() + { + var files = new[] + { + "Harry Potter and the Deathly Hallows trailer.mp3" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + })).ToList(); + + Assert.Single(result); + } + + [Fact] + public void TestEmpty() + { + var files = Array.Empty(); + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + })).ToList(); + + Assert.Empty(result); + } + private AudioBookListResolver GetResolver() { return new AudioBookListResolver(_namingOptions); diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index 2708d80bb6..282da2b93a 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -35,6 +35,11 @@ namespace Jellyfin.Naming.Tests.AudioBook }; } + public static IEnumerable GetPathsWithInvalidExtensions() + { + yield return new object[] { @"/server/AudioBooks/Larry Potter/Larry Potter.mp9" }; + } + [Theory] [MemberData(nameof(GetResolveFileTestData))] public void Resolve_ValidFileName_Success(AudioBookFileInfo expectedResult) @@ -46,13 +51,23 @@ namespace Jellyfin.Naming.Tests.AudioBook Assert.Equal(result!.Container, expectedResult.Container); Assert.Equal(result!.ChapterNumber, expectedResult.ChapterNumber); Assert.Equal(result!.PartNumber, expectedResult.PartNumber); - Assert.Equal(result!.IsDirectory, expectedResult.IsDirectory); + } + + [Theory] + [MemberData(nameof(GetPathsWithInvalidExtensions))] + public void Resolve_InvalidExtension(string path) + { + var result = new AudioBookResolver(_namingOptions).Resolve(path); + + Assert.Null(result); } [Fact] - public void Resolve_EmptyFileName_ArgumentException() + public void Resolve_EmptyFileName() { - Assert.Throws(() => new AudioBookResolver(_namingOptions).Resolve(string.Empty)); + var result = new AudioBookResolver(_namingOptions).Resolve(string.Empty); + + Assert.Null(result); } } } From 50a2ef9d8aaf92e8b69ced5ea2fcc8fa185fe675 Mon Sep 17 00:00:00 2001 From: Stepan Date: Sun, 1 Nov 2020 17:41:47 +0100 Subject: [PATCH 0184/1930] Simplify Resolve_InvalidExtension Test and created tests for Alternative Versions parsing & Year Extraction for audiobooks --- .../AudioBook/AudioBookListResolverTests.cs | 58 +++++++++++++++++++ .../AudioBook/AudioBookResolverTests.cs | 11 +--- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index d912b0e907..c4b061b4e9 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -43,6 +43,64 @@ namespace Jellyfin.Naming.Tests.AudioBook Assert.Equal("Batman", result[1].Name); } + [Fact] + public void TestAlternativeVersions() + { + var files = new[] + { + "Harry Potter and the Deathly Hallows/Chapter 1.ogg", + "Harry Potter and the Deathly Hallows/Chapter 1.mp3", + + "Deadpool.ogg", + "Deadpool.mp3", + + "Batman/Chapter 1.mp3" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + })).ToList(); + + Assert.Equal(3, result[0].Files.Count); + Assert.NotEmpty(result[0].AlternateVersions); + Assert.NotEmpty(result[1].AlternateVersions); + Assert.Empty(result[2].AlternateVersions); + } + + [Fact] + public void TestYearExtraction() + { + var files = new[] + { + "Harry Potter and the Deathly Hallows (2007)/Chapter 1.ogg", + "Harry Potter and the Deathly Hallows (2007)/Chapter 2.mp3", + + "Batman (2020).ogg", + + "Batman(2021).mp3", + + "Batman.mp3" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + })).ToList(); + + Assert.Equal(3, result[0].Files.Count); + Assert.Equal(2007, result[0].Year); + Assert.Equal(2020, result[1].Year); + Assert.Equal(2021, result[2].Year); + Assert.Null(result[2].Year); + } + [Fact] public void TestWithMetadata() { diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index 282da2b93a..5e9d12970a 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -35,10 +35,6 @@ namespace Jellyfin.Naming.Tests.AudioBook }; } - public static IEnumerable GetPathsWithInvalidExtensions() - { - yield return new object[] { @"/server/AudioBooks/Larry Potter/Larry Potter.mp9" }; - } [Theory] [MemberData(nameof(GetResolveFileTestData))] @@ -53,11 +49,10 @@ namespace Jellyfin.Naming.Tests.AudioBook Assert.Equal(result!.PartNumber, expectedResult.PartNumber); } - [Theory] - [MemberData(nameof(GetPathsWithInvalidExtensions))] - public void Resolve_InvalidExtension(string path) + [Fact] + public void Resolve_InvalidExtension() { - var result = new AudioBookResolver(_namingOptions).Resolve(path); + var result = new AudioBookResolver(_namingOptions).Resolve(@"/server/AudioBooks/Larry Potter/Larry Potter.mp9"); Assert.Null(result); } From e41e832495765ec057ed5cc86eb8b3019e3f71c8 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 10:52:32 -0700 Subject: [PATCH 0185/1930] Dependency catch up --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 6 +++--- .../Jellyfin.Server.Implementations.Tests.csproj | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 07f08ec72b..a64d2e1cdb 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -43,7 +43,7 @@ - + diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 24400eae53..9465fe42c2 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -19,7 +19,7 @@ - + diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index e7993d2e7c..0236f2ac1e 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -13,9 +13,9 @@ - - - + + + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 6e5a908022..05323490e2 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -14,8 +14,8 @@ - - + + From ceecc80bb3816ca41d470e3b537a1bf7b632e8e2 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 18:32:41 -0700 Subject: [PATCH 0186/1930] Allow configuration of ActivityLogRetention --- .../ScheduledTasks/Tasks/CleanActivityLogTask.cs | 16 +++++++++++++--- .../Configuration/ServerConfiguration.cs | 6 ++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs index 50bc091c83..4abbf784b2 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Activity; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Tasks; @@ -16,18 +17,22 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks { private readonly ILocalizationManager _localization; private readonly IActivityManager _activityManager; + private readonly IServerConfigurationManager _serverConfigurationManager; /// /// Initializes a new instance of the class. /// /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public CleanActivityLogTask( ILocalizationManager localization, - IActivityManager activityManager) + IActivityManager activityManager, + IServerConfigurationManager serverConfigurationManager) { _localization = localization; _activityManager = activityManager; + _serverConfigurationManager = serverConfigurationManager; } /// @@ -54,8 +59,13 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks /// public Task Execute(CancellationToken cancellationToken, IProgress progress) { - // TODO allow configure - var startDate = DateTime.UtcNow.AddDays(-30); + var retentionDays = _serverConfigurationManager.Configuration.ActivityLogRetentionDays; + if (!retentionDays.HasValue || retentionDays <= 0) + { + throw new Exception($"Activity Log Retention days must be at least 0. Currently: {retentionDays}"); + } + + var startDate = DateTime.UtcNow.AddDays(retentionDays.Value * -1); return _activityManager.CleanAsync(startDate); } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 8b78ad842e..23a5201f7a 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -271,6 +271,11 @@ namespace MediaBrowser.Model.Configuration /// public string[] KnownProxies { get; set; } + /// + /// Gets or sets the number of days we should retain activity logs. + /// + public int? ActivityLogRetentionDays { get; set; } + /// /// Initializes a new instance of the class. /// @@ -381,6 +386,7 @@ namespace MediaBrowser.Model.Configuration SlowResponseThresholdMs = 500; CorsHosts = new[] { "*" }; KnownProxies = Array.Empty(); + ActivityLogRetentionDays = 30; } } From 826c24142e43550bd8de114ae19e3789677cfdc3 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 18:53:02 -0700 Subject: [PATCH 0187/1930] Fix Genres separator --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/LiveTvController.cs | 4 ++-- Jellyfin.Api/Controllers/StudiosController.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 610c2aa646..24843c1844 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -148,7 +148,7 @@ namespace Jellyfin.Api.Controllers NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, ',', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), - Genres = RequestHelpers.Split(genres, ',', true), + Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), Person = person, @@ -357,7 +357,7 @@ namespace Jellyfin.Api.Controllers NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, ',', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), - Genres = RequestHelpers.Split(genres, ',', true), + Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), Person = person, diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 22f140ea62..f89c31e8b2 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -592,7 +592,7 @@ namespace Jellyfin.Api.Controllers IsKids = isKids, IsSports = isSports, SeriesTimerId = seriesTimerId, - Genres = RequestHelpers.Split(genres, ',', true), + Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds) }; @@ -648,7 +648,7 @@ namespace Jellyfin.Api.Controllers IsKids = body.IsKids, IsSports = body.IsSports, SeriesTimerId = body.SeriesTimerId, - Genres = RequestHelpers.Split(body.Genres, ',', true), + Genres = RequestHelpers.Split(body.Genres, '|', true), GenreIds = RequestHelpers.GetGuids(body.GenreIds) }; diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 1d2bf22551..831a9ab8fb 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -147,7 +147,7 @@ namespace Jellyfin.Api.Controllers NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, ',', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), - Genres = RequestHelpers.Split(genres, ',', true), + Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), Person = person, From c1ec46e92b2f5184ea0c7c1f84c19fc154fb15ad Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 18:53:27 -0700 Subject: [PATCH 0188/1930] Fix Tags separator --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/StudiosController.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 24843c1844..24ccdecb72 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -146,7 +146,7 @@ namespace Jellyfin.Api.Controllers NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, ',', true), + Tags = RequestHelpers.Split(tags, '|', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), @@ -355,7 +355,7 @@ namespace Jellyfin.Api.Controllers NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, ',', true), + Tags = RequestHelpers.Split(tags, '|', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 831a9ab8fb..45398dfd3c 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -145,7 +145,7 @@ namespace Jellyfin.Api.Controllers NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, ',', true), + Tags = RequestHelpers.Split(tags, '|', true), OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), From dd3507bbbfd656a4138ac9428bebaa67e11cb076 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 18:54:00 -0700 Subject: [PATCH 0189/1930] Fix OfficialRatings separator --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/StudiosController.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 24ccdecb72..59d3ae2e11 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -147,7 +147,7 @@ namespace Jellyfin.Api.Controllers NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), + OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), @@ -356,7 +356,7 @@ namespace Jellyfin.Api.Controllers NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), + OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 45398dfd3c..b3c345dd4b 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -146,7 +146,7 @@ namespace Jellyfin.Api.Controllers NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, ',', true), + OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), Genres = RequestHelpers.Split(genres, '|', true), GenreIds = RequestHelpers.GetGuids(genreIds), StudioIds = RequestHelpers.GetGuids(studioIds), From 6763d456fff57a08ebde3e1b68169a585c843d69 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 19:23:28 -0700 Subject: [PATCH 0190/1930] Set UserAgent when getting M3u playlist --- .../LiveTv/TunerHosts/M3UTunerHost.cs | 6 +++-- .../LiveTv/TunerHosts/M3uParser.cs | 26 +++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index 8107bc427b..4b170b2e4e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -65,7 +65,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { var channelIdPrefix = GetFullChannelIdPrefix(info); - return await new M3uParser(Logger, _httpClientFactory, _appHost).Parse(info.Url, channelIdPrefix, info.Id, cancellationToken).ConfigureAwait(false); + return await new M3uParser(Logger, _httpClientFactory, _appHost) + .Parse(info, channelIdPrefix, cancellationToken) + .ConfigureAwait(false); } public Task> GetTunerInfos(CancellationToken cancellationToken) @@ -126,7 +128,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts public async Task Validate(TunerHostInfo info) { - using (var stream = await new M3uParser(Logger, _httpClientFactory, _appHost).GetListingsStream(info.Url, CancellationToken.None).ConfigureAwait(false)) + using (var stream = await new M3uParser(Logger, _httpClientFactory, _appHost).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false)) { } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index f066a749e3..c064e2fe6c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -13,6 +13,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.LiveTv; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.TunerHosts @@ -30,12 +31,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts _appHost = appHost; } - public async Task> Parse(string url, string channelIdPrefix, string tunerHostId, CancellationToken cancellationToken) + public async Task> Parse(TunerHostInfo info, string channelIdPrefix, CancellationToken cancellationToken) { // Read the file and display it line by line. - using (var reader = new StreamReader(await GetListingsStream(url, cancellationToken).ConfigureAwait(false))) + using (var reader = new StreamReader(await GetListingsStream(info, cancellationToken).ConfigureAwait(false))) { - return GetChannels(reader, channelIdPrefix, tunerHostId); + return GetChannels(reader, channelIdPrefix, info.Id); } } @@ -48,15 +49,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } } - public Task GetListingsStream(string url, CancellationToken cancellationToken) + public async Task GetListingsStream(TunerHostInfo info, CancellationToken cancellationToken) { - if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + if (info.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { - return _httpClientFactory.CreateClient(NamedClient.Default) - .GetStreamAsync(url); + using var requestMessage = new HttpRequestMessage(HttpMethod.Get, info.Url); + if (!string.IsNullOrEmpty(info.UserAgent)) + { + requestMessage.Headers.UserAgent.TryParseAdd(info.UserAgent); + } + + var response = await _httpClientFactory.CreateClient(NamedClient.Default) + .SendAsync(requestMessage, cancellationToken) + .ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + return await response.Content.ReadAsStreamAsync().ConfigureAwait(false); } - return Task.FromResult((Stream)File.OpenRead(url)); + return File.OpenRead(info.Url); } private const string ExtInfPrefix = "#EXTINF:"; From 6a07e93ddd934420620297d510d4c4b9122463cb Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 1 Nov 2020 20:37:03 -0700 Subject: [PATCH 0191/1930] Fix endpoint auth --- Jellyfin.Api/Controllers/DevicesController.cs | 6 +----- Jellyfin.Api/Controllers/SuggestionsController.cs | 3 +++ 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/DevicesController.cs b/Jellyfin.Api/Controllers/DevicesController.cs index 74380c2eff..b3e3490c2a 100644 --- a/Jellyfin.Api/Controllers/DevicesController.cs +++ b/Jellyfin.Api/Controllers/DevicesController.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Api.Controllers /// /// Devices Controller. /// - [Authorize(Policy = Policies.DefaultAuthorization)] + [Authorize(Policy = Policies.RequiresElevation)] public class DevicesController : BaseJellyfinApiController { private readonly IDeviceManager _deviceManager; @@ -46,7 +46,6 @@ namespace Jellyfin.Api.Controllers /// Devices retrieved. /// An containing the list of devices. [HttpGet] - [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetDevices([FromQuery] bool? supportsSync, [FromQuery] Guid? userId) { @@ -62,7 +61,6 @@ namespace Jellyfin.Api.Controllers /// Device not found. /// An containing the device info on success, or a if the device could not be found. [HttpGet("Info")] - [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult GetDeviceInfo([FromQuery, Required] string id) @@ -84,7 +82,6 @@ namespace Jellyfin.Api.Controllers /// Device not found. /// An containing the device info on success, or a if the device could not be found. [HttpGet("Options")] - [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult GetDeviceOptions([FromQuery, Required] string id) @@ -107,7 +104,6 @@ namespace Jellyfin.Api.Controllers /// Device not found. /// A on success, or a if the device could not be found. [HttpPost("Options")] - [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult UpdateDeviceOptions( diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index d7c81a3ab6..ad64adfbad 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; using System.Linq; +using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; @@ -9,6 +10,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Querying; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -18,6 +20,7 @@ namespace Jellyfin.Api.Controllers /// The suggestions controller. /// [Route("")] + [Authorize(Policy = Policies.DefaultAuthorization)] public class SuggestionsController : BaseJellyfinApiController { private readonly IDtoService _dtoService; From 19d77c99ae77339e919090bfea1244e1eba26b0c Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 2 Nov 2020 09:23:29 +0100 Subject: [PATCH 0192/1930] Save new display preferences --- Jellyfin.Api/Controllers/DisplayPreferencesController.cs | 3 +++ MediaBrowser.Controller/IDisplayPreferencesManager.cs | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 874467c75b..76f5717e30 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -81,6 +81,9 @@ namespace Jellyfin.Api.Controllers dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture); dto.CustomPrefs["tvhome"] = displayPreferences.TvHome; + // This will essentially be a noop if no changes have been made, but new prefs must be saved at least. + _displayPreferencesManager.SaveChanges(); + return dto; } diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index b35f830960..6658269bdb 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -12,6 +12,9 @@ namespace MediaBrowser.Controller /// /// Gets the display preferences for the user and client. /// + /// + /// This will create the display preferences if it does not exist, but it will not save automatically. + /// /// The user's id. /// The client string. /// The associated display preferences. @@ -20,6 +23,9 @@ namespace MediaBrowser.Controller /// /// Gets the default item display preferences for the user and client. /// + /// + /// This will create the item display preferences if it does not exist, but it will not save automatically. + /// /// The user id. /// The item id. /// The client string. From de36c8433e6b64e15ffb8535c0e6d1ccb264c49e Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Mon, 2 Nov 2020 03:52:14 -0700 Subject: [PATCH 0193/1930] Update Emby.Server.Implementations/Localization/Core/en-US.json Co-authored-by: Claus Vium --- Emby.Server.Implementations/Localization/Core/en-US.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/en-US.json b/Emby.Server.Implementations/Localization/Core/en-US.json index bc973c9737..6d8b222b44 100644 --- a/Emby.Server.Implementations/Localization/Core/en-US.json +++ b/Emby.Server.Implementations/Localization/Core/en-US.json @@ -96,7 +96,7 @@ "TasksApplicationCategory": "Application", "TasksChannelsCategory": "Internet Channels", "TaskCleanActivityLog": "Clean Activity Log", - "TaskCleanActivityLogDescription": "Deletes activity log entries older then the configured age.", + "TaskCleanActivityLogDescription": "Deletes activity log entries older than the configured age.", "TaskCleanCache": "Clean Cache Directory", "TaskCleanCacheDescription": "Deletes cache files no longer needed by the system.", "TaskRefreshChapterImages": "Extract Chapter Images", From af56d5c2dc2a2aa2cce0513b906502a59056dfb2 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 2 Nov 2020 11:53:23 +0100 Subject: [PATCH 0194/1930] Rename itemIds to ids --- Jellyfin.Api/Controllers/CollectionController.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Api/Controllers/CollectionController.cs b/Jellyfin.Api/Controllers/CollectionController.cs index 2fc697a6aa..eae06b767c 100644 --- a/Jellyfin.Api/Controllers/CollectionController.cs +++ b/Jellyfin.Api/Controllers/CollectionController.cs @@ -83,14 +83,14 @@ namespace Jellyfin.Api.Controllers /// Adds items to a collection. /// /// The collection id. - /// Item ids, comma delimited. + /// Item ids, comma delimited. /// Items added to collection. /// A indicating success. [HttpPost("{collectionId}/Items")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task AddToCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string itemIds) + public async Task AddToCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids) { - await _collectionManager.AddToCollectionAsync(collectionId, RequestHelpers.GetGuids(itemIds)).ConfigureAwait(true); + await _collectionManager.AddToCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(true); return NoContent(); } @@ -98,14 +98,14 @@ namespace Jellyfin.Api.Controllers /// Removes items from a collection. /// /// The collection id. - /// Item ids, comma delimited. + /// Item ids, comma delimited. /// Items removed from collection. /// A indicating success. [HttpDelete("{collectionId}/Items")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task RemoveFromCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string itemIds) + public async Task RemoveFromCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids) { - await _collectionManager.RemoveFromCollectionAsync(collectionId, RequestHelpers.GetGuids(itemIds)).ConfigureAwait(false); + await _collectionManager.RemoveFromCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(false); return NoContent(); } } From 1e7177568887d0f808660454e5eb7ca7ebcd6998 Mon Sep 17 00:00:00 2001 From: Stepan Date: Mon, 2 Nov 2020 20:03:12 +0100 Subject: [PATCH 0195/1930] Add Name and Year parsing for audiobooks --- Emby.Naming/AudioBook/AudioBookInfo.cs | 4 +- .../AudioBook/AudioBookListResolver.cs | 6 +- Emby.Naming/AudioBook/AudioBookNameParser.cs | 59 ++++++++++++++ .../AudioBook/AudioBookNameParserResult.cs | 12 +++ Emby.Naming/Common/NamingOptions.cs | 9 +++ Emby.Naming/Video/StackResolver.cs | 20 ++++- .../AudioBook/AudioBookListResolverTests.cs | 78 +++++++++++++++---- .../AudioBook/AudioBookResolverTests.cs | 1 - 8 files changed, 163 insertions(+), 26 deletions(-) create mode 100644 Emby.Naming/AudioBook/AudioBookNameParser.cs create mode 100644 Emby.Naming/AudioBook/AudioBookNameParserResult.cs diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index fba11ea726..353a0f4a01 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -11,12 +11,14 @@ namespace Emby.Naming.AudioBook /// Initializes a new instance of the class. /// /// Name of audiobook. - public AudioBookInfo(string name) + /// Year of audiobook release. + public AudioBookInfo(string name, int? year) { Files = new List(); Extras = new List(); AlternateVersions = new List(); Name = name; + Year = year; } /// diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 795065a6c9..86ba2eeeaf 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -41,9 +41,9 @@ namespace Emby.Naming.AudioBook stackFiles.Sort(); - // stack.Name can be empty when we have file without folder, but always have some files - var name = string.IsNullOrEmpty(stack.Name) ? stack.Files[0] : stack.Name; - var info = new AudioBookInfo(name) { Files = stackFiles }; + var result = new AudioBookNameParser(_options).Parse(stack.Name); + + var info = new AudioBookInfo(result.Name, result.Year) { Files = stackFiles }; yield return info; } diff --git a/Emby.Naming/AudioBook/AudioBookNameParser.cs b/Emby.Naming/AudioBook/AudioBookNameParser.cs new file mode 100644 index 0000000000..c48db93b37 --- /dev/null +++ b/Emby.Naming/AudioBook/AudioBookNameParser.cs @@ -0,0 +1,59 @@ +#nullable enable +#pragma warning disable CS1591 + +using System.Globalization; +using System.IO; +using System.Text.RegularExpressions; +using Emby.Naming.Common; + +namespace Emby.Naming.AudioBook +{ + public class AudioBookNameParser + { + private readonly NamingOptions _options; + + public AudioBookNameParser(NamingOptions options) + { + _options = options; + } + + public AudioBookNameParserResult Parse(string name) + { + AudioBookNameParserResult result = default; + foreach (var expression in _options.AudioBookNamesExpressions) + { + var match = new Regex(expression, RegexOptions.IgnoreCase).Match(name); + if (match.Success) + { + if (result.Name == null) + { + var value = match.Groups["name"]; + if (value.Success) + { + result.Name = value.Value; + } + } + + if (!result.Year.HasValue) + { + var value = match.Groups["year"]; + if (value.Success) + { + if (int.TryParse(value.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue)) + { + result.Year = intValue; + } + } + } + } + } + + if (string.IsNullOrEmpty(result.Name)) + { + result.Name = name; + } + + return result; + } + } +} diff --git a/Emby.Naming/AudioBook/AudioBookNameParserResult.cs b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs new file mode 100644 index 0000000000..b28e259dda --- /dev/null +++ b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs @@ -0,0 +1,12 @@ +#nullable enable +#pragma warning disable CS1591 + +namespace Emby.Naming.AudioBook +{ + public struct AudioBookNameParserResult + { + public string Name { get; set; } + + public int? Year { get; set; } + } +} diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 537de63d55..5bf232451b 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -575,6 +575,13 @@ namespace Emby.Naming.Common @"dis(?:c|k)[\s_-]?(?[0-9]+)" }; + AudioBookNamesExpressions = new[] + { + // Detect year usually in brackets after name Batman (2020) + @"^(?.+?)\s*\(\s*(?\d{4})\s*\)\s*$", + @"^\s*(?.+?)\s*$" + }; + var extensions = VideoFileExtensions.ToList(); extensions.AddRange(new[] @@ -658,6 +665,8 @@ namespace Emby.Naming.Common public string[] AudioBookPartsExpressions { get; set; } + public string[] AudioBookNamesExpressions { get; set; } + public StubTypeRule[] StubTypes { get; set; } public char[] VideoFlagDelimiters { get; set; } diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index ce3152739b..e11b4063ce 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -36,13 +36,25 @@ namespace Emby.Naming.Video foreach (var directory in groupedDirectoryFiles) { - var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false }; - foreach (var file in directory) + if (string.IsNullOrEmpty(directory.Key)) { - stack.Files.Add(file.Path); + foreach (var file in directory) + { + var stack = new FileStack { Name = Path.GetFileNameWithoutExtension(file.Path), IsDirectoryStack = false }; + stack.Files.Add(file.Path); + yield return stack; + } } + else + { + var stack = new FileStack { Name = Path.GetFileName(directory.Key), IsDirectoryStack = false }; + foreach (var file in directory) + { + stack.Files.Add(file.Path); + } - yield return stack; + yield return stack; + } } } diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index c4b061b4e9..91492d46c9 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Emby.Naming.AudioBook; using Emby.Naming.Common; @@ -72,33 +73,69 @@ namespace Jellyfin.Naming.Tests.AudioBook } [Fact] - public void TestYearExtraction() + public void TestNameYearExtraction() { - var files = new[] + var data = new[] { - "Harry Potter and the Deathly Hallows (2007)/Chapter 1.ogg", - "Harry Potter and the Deathly Hallows (2007)/Chapter 2.mp3", - - "Batman (2020).ogg", - - "Batman(2021).mp3", - - "Batman.mp3" + new NameYearPath + { + Name = "Harry Potter and the Deathly Hallows", + Path = "Harry Potter and the Deathly Hallows (2007)/Chapter 1.ogg", + Year = 2007 + }, + new NameYearPath + { + Name = "Batman", + Path = "Batman (2020).ogg", + Year = 2020 + }, + new NameYearPath + { + Name = "Batman", + Path = "Batman( 2021 ).mp3", + Year = 2021 + }, + new NameYearPath + { + Name = "Batman(*2021*)", + Path = "Batman(*2021*).mp3", + Year = null + }, + new NameYearPath + { + Name = "Batman", + Path = "Batman.mp3", + Year = null + }, + new NameYearPath + { + Name = "+ Batman .", + Path = " + Batman . .mp3", + Year = null + }, + new NameYearPath + { + Name = " ", + Path = " .mp3", + Year = null + } }; var resolver = GetResolver(); - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = resolver.Resolve(data.Select(i => new FileSystemMetadata { IsDirectory = false, - FullName = i + FullName = i.Path })).ToList(); - Assert.Equal(3, result[0].Files.Count); - Assert.Equal(2007, result[0].Year); - Assert.Equal(2020, result[1].Year); - Assert.Equal(2021, result[2].Year); - Assert.Null(result[2].Year); + Assert.Equal(data.Length, result.Count); + + for (int i = 0; i < data.Length; i++) + { + Assert.Equal(data[i].Name, result[i].Name); + Assert.Equal(data[i].Year, result[i].Year); + } } [Fact] @@ -180,5 +217,12 @@ namespace Jellyfin.Naming.Tests.AudioBook { return new AudioBookListResolver(_namingOptions); } + + internal struct NameYearPath + { + public string Name; + public string Path; + public int? Year; + } } } diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index 5e9d12970a..b3257ace3b 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -35,7 +35,6 @@ namespace Jellyfin.Naming.Tests.AudioBook }; } - [Theory] [MemberData(nameof(GetResolveFileTestData))] public void Resolve_ValidFileName_Success(AudioBookFileInfo expectedResult) From 7b6363b09a3aabba3dcd285fd70d2eda8f1ea889 Mon Sep 17 00:00:00 2001 From: Stepan Date: Mon, 2 Nov 2020 23:07:46 +0100 Subject: [PATCH 0196/1930] Update test for detecting audiobooks extras and alternative files --- .../AudioBook/AudioBookListResolverTests.cs | 61 ++++++++++++++++--- 1 file changed, 52 insertions(+), 9 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index 91492d46c9..a246999628 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -20,11 +20,20 @@ namespace Jellyfin.Naming.Tests.AudioBook { "Harry Potter and the Deathly Hallows/Part 1.mp3", "Harry Potter and the Deathly Hallows/Part 2.mp3", - "Harry Potter and the Deathly Hallows/book.nfo", + "Harry Potter and the Deathly Hallows/Extra.mp3", "Batman/Chapter 1.mp3", "Batman/Chapter 2.mp3", "Batman/Chapter 3.mp3", + + "Ready Player One (2020)/Ready Player One.mp3", + "Ready Player One (2020)/extra.mp3", + + "Badman/audiobook.mp3", + "Badman/extra.mp3", + + "Superman (2020)/book.mp3", + "Superman (2020)/extra.mp3" }; var resolver = GetResolver(); @@ -35,13 +44,21 @@ namespace Jellyfin.Naming.Tests.AudioBook FullName = i })).ToList(); - Assert.Equal(2, result[0].Files.Count); - // Assert.Empty(result[0].Extras); FIXME: AudioBookListResolver should resolve extra files properly + Assert.Equal(4, result[0].Files.Count); + Assert.Single(result[0].Extras); Assert.Equal("Harry Potter and the Deathly Hallows", result[0].Name); Assert.Equal(3, result[1].Files.Count); Assert.Empty(result[1].Extras); Assert.Equal("Batman", result[1].Name); + + Assert.Equal(2, result[2].Files.Count); + Assert.Single(result[2].Extras); + Assert.Equal("Badman", result[2].Name); + + Assert.Equal(2, result[3].Files.Count); + Assert.Single(result[3].Extras); + Assert.Equal("Superman", result[3].Name); } [Fact] @@ -52,10 +69,19 @@ namespace Jellyfin.Naming.Tests.AudioBook "Harry Potter and the Deathly Hallows/Chapter 1.ogg", "Harry Potter and the Deathly Hallows/Chapter 1.mp3", - "Deadpool.ogg", - "Deadpool.mp3", + "Aqua-man/book.mp3", - "Batman/Chapter 1.mp3" + "Deadpool.mp3", + "Deadpool [HQ].mp3", + + "Superman/book.mp3", + "Superman/audiobook.mp3", + "Superman/Superman.mp3", + "Superman/Superman [HQ].mp3", + "Superman/extra.mp3", + + "Batman/ Chapter 1 .mp3", + "Batman/Chapter 1[loss-less].mp3" }; var resolver = GetResolver(); @@ -66,10 +92,27 @@ namespace Jellyfin.Naming.Tests.AudioBook FullName = i })).ToList(); - Assert.Equal(3, result[0].Files.Count); - Assert.NotEmpty(result[0].AlternateVersions); - Assert.NotEmpty(result[1].AlternateVersions); + Assert.Equal(6, result[0].Files.Count); + // HP - Same name so we don't care which file is alternative + Assert.Single(result[0].AlternateVersions); + // Aqua-man + Assert.Empty(result[1].AlternateVersions); + // DP Assert.Empty(result[2].AlternateVersions); + // DP HQ (directory missing so we do not group deadpools together) + Assert.Empty(result[3].AlternateVersions); + // Superman + // Priority: + // 1. Name + // 2. audiobook + // 3. book + // 4. Names with modifiers + Assert.Equal(3, result[4].AlternateVersions.Count); + Assert.Equal("Superman/audiobook.mp3", result[4].AlternateVersions[0].Path); + Assert.Equal("Superman/book.mp3", result[4].AlternateVersions[1].Path); + Assert.Equal("Superman/Superman [HQ].mp3", result[4].AlternateVersions[2].Path); + // Batman + Assert.Single(result[5].AlternateVersions); } [Fact] From 25f93a9af4ee3caa3bbb42996e5c65f0c3adb1de Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 3 Nov 2020 23:18:30 +0900 Subject: [PATCH 0197/1930] disable compatibility checks until they work again --- .ci/azure-pipelines-abi.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml index 4d38a906e6..52abdd0ea5 100644 --- a/.ci/azure-pipelines-abi.yml +++ b/.ci/azure-pipelines-abi.yml @@ -83,6 +83,7 @@ jobs: - task: DotNetCoreCLI@2 displayName: 'Execute ABI Compatibility Check Tool' + enabled: false inputs: command: custom custom: compat From c060ed1a1853eaa28ae2f88f6b301c23cf326725 Mon Sep 17 00:00:00 2001 From: Stepan Date: Tue, 3 Nov 2020 16:24:04 +0100 Subject: [PATCH 0198/1930] Added resolving of alternative files and extras for audibooks. --- Emby.Naming/AudioBook/AudioBookInfo.cs | 11 ++- .../AudioBook/AudioBookListResolver.cs | 93 ++++++++++++++++++- Emby.Naming/AudioBook/AudioBookNameParser.cs | 1 - Emby.Naming/AudioBook/AudioBookResolver.cs | 2 +- Emby.Naming/Common/NamingOptions.cs | 4 +- .../AudioBook/AudioBookListResolverTests.cs | 48 +++++----- 6 files changed, 126 insertions(+), 33 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index 353a0f4a01..adf403ab6d 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -12,13 +12,16 @@ namespace Emby.Naming.AudioBook /// /// Name of audiobook. /// Year of audiobook release. - public AudioBookInfo(string name, int? year) + /// List of files composing the actual audiobook. + /// List of extra files. + /// Alternative version of files. + public AudioBookInfo(string name, int? year, List? files, List? extras, List? alternateVersions) { - Files = new List(); - Extras = new List(); - AlternateVersions = new List(); Name = name; Year = year; + Files = files ?? new List(); + Extras = extras ?? new List(); + AlternateVersions = alternateVersions ?? new List(); } /// diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 86ba2eeeaf..e8908aa37c 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -41,12 +41,101 @@ namespace Emby.Naming.AudioBook stackFiles.Sort(); - var result = new AudioBookNameParser(_options).Parse(stack.Name); + var nameParserResult = new AudioBookNameParser(_options).Parse(stack.Name); - var info = new AudioBookInfo(result.Name, result.Year) { Files = stackFiles }; + FindExtraAndAlternativeFiles(ref stackFiles, out var extras, out var alternativeVersions, nameParserResult); + + var info = new AudioBookInfo( + nameParserResult.Name, + nameParserResult.Year, + stackFiles, + extras, + alternativeVersions); yield return info; } } + + private void FindExtraAndAlternativeFiles(ref List stackFiles, out List extras, out List alternativeVersions, AudioBookNameParserResult nameParserResult) + { + extras = new List(); + alternativeVersions = new List(); + + var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber != null || x.PartNumber != null); + var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber }); + + foreach (var group in groupedBy) + { + if (group.Key.ChapterNumber == null && group.Key.PartNumber == null) + { + if (group.Count() > 1 || haveChaptersOrPages) + { + var ex = new List(); + var alt = new List(); + + foreach (var audioFile in group) + { + var name = Path.GetFileNameWithoutExtension(audioFile.Path); + if (name == "audiobook" || + name.Contains(nameParserResult.Name, StringComparison.OrdinalIgnoreCase) || + name.Contains(nameParserResult.Name.Replace(" ", "."), StringComparison.OrdinalIgnoreCase)) + { + alt.Add(audioFile); + } + else + { + ex.Add(audioFile); + } + } + + if (ex.Count > 0) + { + var extra = ex + .OrderBy(x => x.Container) + .ThenBy(x => x.Path) + .ToList(); + + stackFiles = stackFiles.Except(extra).ToList(); + extras.AddRange(extra); + } + + if (alt.Count > 0) + { + var alternatives = alt + .OrderBy(x => x.Container) + .ThenBy(x => x.Path) + .ToList(); + + var main = FindMainAudioBookFile(alternatives, nameParserResult.Name); + alternatives.Remove(main); + stackFiles = stackFiles.Except(alternatives).ToList(); + alternativeVersions.AddRange(alternatives); + } + } + } + else if (group.Count() > 1) + { + var alternatives = group + .OrderBy(x => x.Container) + .ThenBy(x => x.Path) + .Skip(1) + .ToList(); + + stackFiles = stackFiles.Except(alternatives).ToList(); + alternativeVersions.AddRange(alternatives); + } + } + } + + private AudioBookFileInfo FindMainAudioBookFile(List files, string name) + { + var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path) == name); + main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path) == "audiobook"); + main ??= files.OrderBy(x => x.Container) + .ThenBy(x => x.Path) + .First(); + + return main; + } } } diff --git a/Emby.Naming/AudioBook/AudioBookNameParser.cs b/Emby.Naming/AudioBook/AudioBookNameParser.cs index c48db93b37..7c86161241 100644 --- a/Emby.Naming/AudioBook/AudioBookNameParser.cs +++ b/Emby.Naming/AudioBook/AudioBookNameParser.cs @@ -2,7 +2,6 @@ #pragma warning disable CS1591 using System.Globalization; -using System.IO; using System.Text.RegularExpressions; using Emby.Naming.Common; diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index 542d6fee51..c7b3b2d2d1 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -19,7 +19,7 @@ namespace Emby.Naming.AudioBook public AudioBookFileInfo? Resolve(string path) { - if (path.Length == 0) + if (path.Length == 0 || Path.GetFileNameWithoutExtension(path).Length == 0) { // Return null to indicate this path will not be used, instead of stopping whole process with exception return null; diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 5bf232451b..d2f07817a6 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -568,7 +568,7 @@ namespace Emby.Naming.Common // Chapter is often beginning of filename "^(?[0-9]+)", // Part if often ending of filename - "(?[0-9]+)$", + @"(?[0-9]+)$", // Sometimes named as 0001_005 (chapter_part) "(?[0-9]+)_(?[0-9]+)", // Some audiobooks are ripped from cd's, and will be named by disk number. @@ -579,7 +579,7 @@ namespace Emby.Naming.Common { // Detect year usually in brackets after name Batman (2020) @"^(?.+?)\s*\(\s*(?\d{4})\s*\)\s*$", - @"^\s*(?.+?)\s*$" + @"^\s*(?[^ ].*?)\s*$" }; var extensions = VideoFileExtensions.ToList(); diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index a246999628..e5768b6209 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -26,14 +26,16 @@ namespace Jellyfin.Naming.Tests.AudioBook "Batman/Chapter 2.mp3", "Batman/Chapter 3.mp3", - "Ready Player One (2020)/Ready Player One.mp3", - "Ready Player One (2020)/extra.mp3", - "Badman/audiobook.mp3", "Badman/extra.mp3", - "Superman (2020)/book.mp3", - "Superman (2020)/extra.mp3" + "Superman (2020)/Part 1.mp3", + "Superman (2020)/extra.mp3", + + "Ready Player One (2020)/audiobook.mp3", + "Ready Player One (2020)/extra.mp3", + + ".mp3" }; var resolver = GetResolver(); @@ -44,7 +46,9 @@ namespace Jellyfin.Naming.Tests.AudioBook FullName = i })).ToList(); - Assert.Equal(4, result[0].Files.Count); + Assert.Equal(5, result.Count); + + Assert.Equal(2, result[0].Files.Count); Assert.Single(result[0].Extras); Assert.Equal("Harry Potter and the Deathly Hallows", result[0].Name); @@ -52,13 +56,17 @@ namespace Jellyfin.Naming.Tests.AudioBook Assert.Empty(result[1].Extras); Assert.Equal("Batman", result[1].Name); - Assert.Equal(2, result[2].Files.Count); + Assert.Single(result[2].Files); Assert.Single(result[2].Extras); Assert.Equal("Badman", result[2].Name); - Assert.Equal(2, result[3].Files.Count); + Assert.Single(result[3].Files); Assert.Single(result[3].Extras); Assert.Equal("Superman", result[3].Name); + + Assert.Single(result[4].Files); + Assert.Single(result[4].Extras); + Assert.Equal("Ready Player One", result[4].Name); } [Fact] @@ -69,12 +77,9 @@ namespace Jellyfin.Naming.Tests.AudioBook "Harry Potter and the Deathly Hallows/Chapter 1.ogg", "Harry Potter and the Deathly Hallows/Chapter 1.mp3", - "Aqua-man/book.mp3", - "Deadpool.mp3", "Deadpool [HQ].mp3", - "Superman/book.mp3", "Superman/audiobook.mp3", "Superman/Superman.mp3", "Superman/Superman [HQ].mp3", @@ -92,27 +97,24 @@ namespace Jellyfin.Naming.Tests.AudioBook FullName = i })).ToList(); - Assert.Equal(6, result[0].Files.Count); + Assert.Equal(5, result.Count); // HP - Same name so we don't care which file is alternative Assert.Single(result[0].AlternateVersions); - // Aqua-man - Assert.Empty(result[1].AlternateVersions); // DP - Assert.Empty(result[2].AlternateVersions); + Assert.Empty(result[1].AlternateVersions); // DP HQ (directory missing so we do not group deadpools together) - Assert.Empty(result[3].AlternateVersions); + Assert.Empty(result[2].AlternateVersions); // Superman // Priority: // 1. Name // 2. audiobook - // 3. book - // 4. Names with modifiers - Assert.Equal(3, result[4].AlternateVersions.Count); - Assert.Equal("Superman/audiobook.mp3", result[4].AlternateVersions[0].Path); - Assert.Equal("Superman/book.mp3", result[4].AlternateVersions[1].Path); - Assert.Equal("Superman/Superman [HQ].mp3", result[4].AlternateVersions[2].Path); + // 3. Names with modifiers + Assert.Equal(2, result[3].AlternateVersions.Count); + var paths = result[3].AlternateVersions.Select(x => x.Path).ToList(); + Assert.Contains("Superman/audiobook.mp3", paths); + Assert.Contains("Superman/Superman [HQ].mp3", paths); // Batman - Assert.Single(result[5].AlternateVersions); + Assert.Single(result[4].AlternateVersions); } [Fact] From aef1fe62c216612f3f42b2e19496730b56b155ce Mon Sep 17 00:00:00 2001 From: Stepan Date: Tue, 3 Nov 2020 16:25:33 +0100 Subject: [PATCH 0199/1930] Complete test coverage for Emby.Naming.Subtitles --- tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs index d11809de11..5152098908 100644 --- a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using Emby.Naming.Common; using Emby.Naming.Subtitles; using Xunit; @@ -26,6 +26,7 @@ namespace Jellyfin.Naming.Tests.Subtitles Assert.Equal(language, result?.Language, true); Assert.Equal(isDefault, result?.IsDefault); Assert.Equal(isForced, result?.IsForced); + Assert.Equal(input, result?.Path); } [Theory] From b4d52d8009d8e4a6836dc431ac5f336910a07d6c Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 3 Nov 2020 16:38:47 -0700 Subject: [PATCH 0200/1930] Apply patch --- .../TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 5 +++++ .../LiveTv/TunerHosts/SharedHttpStream.cs | 5 +++++ Jellyfin.Api/Controllers/LiveTvController.cs | 7 ++----- Jellyfin.Api/Helpers/ProgressiveFileStream.cs | 12 ++++++++---- .../Library/IMediaSourceManager.cs | 2 ++ 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 6730751d50..858c10030d 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -131,6 +131,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun await taskCompletionSource.Task.ConfigureAwait(false); } + public string GetFilePath() + { + return TempFilePath; + } + private Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource openTaskCompletionSource, CancellationToken cancellationToken) { return Task.Run(async () => diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 10e5eab73c..2e1b895096 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -122,6 +122,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts } } + public string GetFilePath() + { + return TempFilePath; + } + private Task StartStreaming(HttpResponseMessage response, TaskCompletionSource openTaskCompletionSource, CancellationToken cancellationToken) { return Task.Run(async () => diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 58c7473c23..88a7542cee 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1220,11 +1220,8 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - await new ProgressiveFileCopier(liveStreamInfo, null, _transcodingJobHelper, CancellationToken.None) - .WriteToAsync(Response.Body, CancellationToken.None) - .ConfigureAwait(false); - Response.ContentType = MimeTypes.GetMimeType("file." + container); - return Ok(); + var liveStream = new ProgressiveFileStream(liveStreamInfo.GetFilePath(), null, _transcodingJobHelper); + return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file." + container)); } private void AssertUserCanManageLiveTv() diff --git a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs index b3566b6f80..824870c7ef 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileStream.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileStream.cs @@ -82,20 +82,23 @@ namespace Jellyfin.Api.Helpers int totalBytesRead = 0; int remainingBytesToRead = count; + int newOffset = offset; while (remainingBytesToRead > 0) { cancellationToken.ThrowIfCancellationRequested(); int bytesRead; if (_allowAsyncFileRead) { - bytesRead = await _fileStream.ReadAsync(buffer, offset, remainingBytesToRead, cancellationToken).ConfigureAwait(false); + bytesRead = await _fileStream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false); } else { - bytesRead = _fileStream.Read(buffer, offset, remainingBytesToRead); + bytesRead = _fileStream.Read(buffer, newOffset, remainingBytesToRead); } remainingBytesToRead -= bytesRead; + newOffset += bytesRead; + if (bytesRead > 0) { _bytesWritten += bytesRead; @@ -108,12 +111,13 @@ namespace Jellyfin.Api.Helpers } else { - if (_job == null || _job.HasExited) + // If the job is null it's a live stream and will require user action to close + if (_job?.HasExited ?? false) { break; } - await Task.Delay(100, cancellationToken).ConfigureAwait(false); + await Task.Delay(50, cancellationToken).ConfigureAwait(false); } } diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs index 22bf9488f7..21c6ef2af1 100644 --- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs +++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs @@ -115,5 +115,7 @@ namespace MediaBrowser.Controller.Library public interface IDirectStreamProvider { Task CopyToAsync(Stream stream, CancellationToken cancellationToken); + + string GetFilePath(); } } From d9ea1ac12d03b2d299c162f9d9d33c840eeb9a78 Mon Sep 17 00:00:00 2001 From: dkanada Date: Wed, 4 Nov 2020 13:49:49 +0900 Subject: [PATCH 0201/1930] disable two more tasks to fix the failures --- .ci/azure-pipelines-abi.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml index 52abdd0ea5..b558d2a6f0 100644 --- a/.ci/azure-pipelines-abi.yml +++ b/.ci/azure-pipelines-abi.yml @@ -62,6 +62,7 @@ jobs: - task: DownloadPipelineArtifact@2 displayName: 'Download Reference Assembly Build Artifact' + enabled: false inputs: source: "specific" artifact: "$(NugetPackageName)" @@ -73,6 +74,7 @@ jobs: - task: CopyFiles@2 displayName: 'Copy Reference Assembly Build Artifact' + enabled: false inputs: sourceFolder: $(System.ArtifactsDirectory)/current-artifacts contents: '**/*.dll' From 3e62557959b1233311ab5d4e8f578f84438580d9 Mon Sep 17 00:00:00 2001 From: Greenback Date: Wed, 4 Nov 2020 20:29:55 +0000 Subject: [PATCH 0202/1930] amended testing unit. --- Jellyfin.Networking/Manager/NetworkManager.cs | 14 ++++++++------ MediaBrowser.Common/Net/NetworkExtensions.cs | 2 +- .../NetworkTesting/UnitTesting.cs | 14 +++++++------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 2ec2a0ba52..289b1dc720 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -19,6 +19,8 @@ namespace Jellyfin.Networking.Manager { /// /// Class to take care of network interface management. + /// + /// Note: The normal collection methods and properties will not work with NetCollection. . /// public class NetworkManager : INetworkManager, IDisposable { @@ -925,8 +927,8 @@ namespace Jellyfin.Networking.Manager // Read and parse bind addresses and exclusions, removing ones that don't exist. _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); + _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); + _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } private void InitialiseRemote(NetworkConfiguration config) @@ -997,9 +999,9 @@ namespace Jellyfin.Networking.Manager _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); } - _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets); - _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets); - _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks()); + _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); + _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString()); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks().AsString()); } } @@ -1090,7 +1092,7 @@ namespace Jellyfin.Networking.Manager } _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses); + _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); // If for some reason we don't have an interface info, resolve our DNS name. if (_interfaceAddresses.Count == 0) diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 39499460ea..e801de5eb8 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -45,7 +45,7 @@ namespace MediaBrowser.Common.Net /// /// The . /// Returns a string representation of this object. - public static string Readable(this NetCollection source) + public static string AsString(this NetCollection source) { var sb = new StringBuilder(); string output = "["; diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index fe64d1cfce..c96c7defd7 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -71,7 +71,7 @@ namespace NetworkTesting var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.True(string.Equals(nm.GetInternalBindAddresses().Readable(), value, StringComparison.Ordinal)); + Assert.True(string.Equals(nm.GetInternalBindAddresses().AsString(), value, StringComparison.Ordinal)); } [Theory] @@ -163,22 +163,22 @@ namespace NetworkTesting // Test included, IP6. NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc.Readable(), result1, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.AsString(), result1, System.StringComparison.OrdinalIgnoreCase)); // Text excluded, non IP6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc?.Readable(), result3, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.AsString(), result3, System.StringComparison.OrdinalIgnoreCase)); conf.EnableIPV6 = false; nm.UpdateSettings(conf); // Test included, non IP6. nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc.Readable(), result2, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.AsString(), result2, System.StringComparison.OrdinalIgnoreCase)); // Test excluded, including IPv6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc.Readable(), result4, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.AsString(), result4, System.StringComparison.OrdinalIgnoreCase)); conf.EnableIPV6 = true; nm.UpdateSettings(conf); @@ -186,7 +186,7 @@ namespace NetworkTesting // Test network addresses of collection. nc = nm.CreateIPCollection(settings.Split(","), false); nc = nc.AsNetworks(); - Assert.True(string.Equals(nc.Readable(), result5, System.StringComparison.OrdinalIgnoreCase)); + Assert.True(string.Equals(nc?.AsString(), result5, System.StringComparison.OrdinalIgnoreCase)); } [Theory] @@ -205,7 +205,7 @@ namespace NetworkTesting NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false); NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false); - Assert.True(nc1.Union(nc2).Readable() == result); + Assert.True(nc1.Union(nc2).AsString() == result); } [Theory] From e2769671a79dfd73ec2796bcc0cbe97584ee4023 Mon Sep 17 00:00:00 2001 From: Greenback Date: Wed, 4 Nov 2020 20:38:47 +0000 Subject: [PATCH 0203/1930] removed github merge introduced spaces. --- Jellyfin.Server/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 2e9def9af7..db67f64708 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -281,8 +281,8 @@ namespace Jellyfin.Server if (appHost.ListenWithHttps) { options.Listen( - netAdd.Address, - appHost.HttpsPort, + netAdd.Address, + appHost.HttpsPort, listenOptions => listenOptions.UseHttps(appHost.Certificate)); } else if (builderContext.HostingEnvironment.IsDevelopment()) @@ -292,7 +292,7 @@ namespace Jellyfin.Server options.Listen( netAdd.Address, appHost.HttpsPort, - listenOptions => listenOptions.UseHttps()); + listenOptions => listenOptions.UseHttps()); } catch (InvalidOperationException) { From 584b4fa41f4a19a7df2a78b408e3763ca0ff4027 Mon Sep 17 00:00:00 2001 From: cvium Date: Thu, 5 Nov 2020 12:27:22 +0100 Subject: [PATCH 0204/1930] Fix Persons, Genres and Studios endpoints --- .../Data/SqliteItemRepository.cs | 63 +++--- .../Library/LibraryManager.cs | 15 ++ Jellyfin.Api/Controllers/GenresController.cs | 145 ++------------ Jellyfin.Api/Controllers/PersonsController.cs | 185 +++--------------- Jellyfin.Api/Controllers/StudiosController.cs | 134 +------------ Jellyfin.Api/Helpers/RequestHelpers.cs | 41 +++- .../Entities/InternalPeopleQuery.cs | 5 + .../Library/ILibraryManager.cs | 2 + 8 files changed, 135 insertions(+), 455 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 81e8e38b33..acb75e9b89 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -5002,26 +5002,33 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type CheckDisposed(); - var commandText = "select Distinct Name from People"; + var commandText = new StringBuilder("select Distinct p.Name from People p"); + + if (query.User != null && query.IsFavorite.HasValue) + { + commandText.Append(" LEFT JOIN TypedBaseItems tbi ON tbi.Name=p.Name AND tbi.Type='"); + commandText.Append(typeof(Person).FullName); + commandText.Append("' LEFT JOIN UserDatas ON tbi.UserDataKey=key AND userId=@UserId"); + } var whereClauses = GetPeopleWhereClauses(query, null); if (whereClauses.Count != 0) { - commandText += " where " + string.Join(" AND ", whereClauses); + commandText.Append(" where ").Append(string.Join(" AND ", whereClauses)); } - commandText += " order by ListOrder"; + commandText.Append(" order by ListOrder"); if (query.Limit > 0) { - commandText += " LIMIT " + query.Limit; + commandText.Append(" LIMIT ").Append(query.Limit); } using (var connection = GetConnection(true)) { var list = new List(); - using (var statement = PrepareStatement(connection, commandText)) + using (var statement = PrepareStatement(connection, commandText.ToString())) { // Run this again to bind the params GetPeopleWhereClauses(query, statement); @@ -5087,19 +5094,13 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (!query.ItemId.Equals(Guid.Empty)) { whereClauses.Add("ItemId=@ItemId"); - if (statement != null) - { - statement.TryBind("@ItemId", query.ItemId.ToByteArray()); - } + statement?.TryBind("@ItemId", query.ItemId.ToByteArray()); } if (!query.AppearsInItemId.Equals(Guid.Empty)) { - whereClauses.Add("Name in (Select Name from People where ItemId=@AppearsInItemId)"); - if (statement != null) - { - statement.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray()); - } + whereClauses.Add("p.Name in (Select Name from People where ItemId=@AppearsInItemId)"); + statement?.TryBind("@AppearsInItemId", query.AppearsInItemId.ToByteArray()); } var queryPersonTypes = query.PersonTypes.Where(IsValidPersonType).ToList(); @@ -5107,10 +5108,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (queryPersonTypes.Count == 1) { whereClauses.Add("PersonType=@PersonType"); - if (statement != null) - { - statement.TryBind("@PersonType", queryPersonTypes[0]); - } + statement?.TryBind("@PersonType", queryPersonTypes[0]); } else if (queryPersonTypes.Count > 1) { @@ -5124,10 +5122,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (queryExcludePersonTypes.Count == 1) { whereClauses.Add("PersonType<>@PersonType"); - if (statement != null) - { - statement.TryBind("@PersonType", queryExcludePersonTypes[0]); - } + statement?.TryBind("@PersonType", queryExcludePersonTypes[0]); } else if (queryExcludePersonTypes.Count > 1) { @@ -5139,19 +5134,24 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (query.MaxListOrder.HasValue) { whereClauses.Add("ListOrder<=@MaxListOrder"); - if (statement != null) - { - statement.TryBind("@MaxListOrder", query.MaxListOrder.Value); - } + statement?.TryBind("@MaxListOrder", query.MaxListOrder.Value); } if (!string.IsNullOrWhiteSpace(query.NameContains)) { - whereClauses.Add("Name like @NameContains"); - if (statement != null) - { - statement.TryBind("@NameContains", "%" + query.NameContains + "%"); - } + whereClauses.Add("p.Name like @NameContains"); + statement?.TryBind("@NameContains", "%" + query.NameContains + "%"); + } + + if (query.IsFavorite.HasValue) + { + whereClauses.Add("isFavorite=@IsFavorite"); + statement?.TryBind("@IsFavorite", query.IsFavorite.Value); + } + + if (query.User != null) + { + statement?.TryBind("@UserId", query.User.InternalId); } return whereClauses; @@ -5420,6 +5420,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type NameStartsWithOrGreater = query.NameStartsWithOrGreater, Tags = query.Tags, OfficialRatings = query.OfficialRatings, + StudioIds = query.StudioIds, GenreIds = query.GenreIds, Genres = query.Genres, Years = query.Years, diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 00282b71a5..f16eda1ec2 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2440,6 +2440,21 @@ namespace Emby.Server.Implementations.Library new SubtitleResolver(BaseItem.LocalizationManager).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files); } + public BaseItem GetParentItem(string parentId, Guid? userId) + { + if (!string.IsNullOrEmpty(parentId)) + { + return GetItemById(new Guid(parentId)); + } + + if (userId.HasValue && userId != Guid.Empty) + { + return GetUserRootFolder(); + } + + return RootFolder; + } + /// public bool IsVideoFile(string path) { diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index aa7d02de00..a174d9239b 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -1,11 +1,9 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; -using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -49,7 +47,6 @@ namespace Jellyfin.Api.Controllers /// /// Gets all genres from a given item, folder, or the entire library. /// - /// Optional filter by minimum community rating. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. /// The search term. @@ -57,22 +54,9 @@ namespace Jellyfin.Api.Controllers /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. - /// Optional. Specify additional filters to apply. /// Optional filter by items that are marked as favorite, or not. - /// Optional filter by MediaType. Allows multiple, comma delimited. - /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited. - /// Optional, include user data. /// Optional, the max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. If specified, results will be filtered to include only those containing the specified person. - /// Optional. If specified, results will be filtered to include only those containing the specified person id. - /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited. - /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited. /// User id. /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. @@ -84,7 +68,6 @@ namespace Jellyfin.Api.Controllers [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetGenres( - [FromQuery] double? minCommunityRating, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, @@ -92,22 +75,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, - [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, - [FromQuery] string? studios, - [FromQuery] string? studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, @@ -118,42 +88,22 @@ namespace Jellyfin.Api.Controllers var dtoOptions = new DtoOptions() .AddItemFields(fields) .AddClientFields(Request) - .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); + .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes); - User? user = null; - BaseItem parentItem; + User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null; - if (userId.HasValue && !userId.Equals(Guid.Empty)) - { - user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); - } - else - { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); - } + var parentItem = _libraryManager.GetParentItem(parentId, userId); var query = new InternalItemsQuery(user) { ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), - Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(), - MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, EnableTotalRecordCount = enableTotalRecordCount @@ -171,87 +121,20 @@ namespace Jellyfin.Api.Controllers } } - // Studios - if (!string.IsNullOrEmpty(studios)) + QueryResult<(BaseItem, ItemCounts)> result; + if (parentItem is ICollectionFolder parentCollectionFolder + && (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music) + || string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos))) { - query.StudioIds = studios.Split('|') - .Select(i => - { - try - { - return _libraryManager.GetStudio(i); - } - catch - { - return null; - } - }).Where(i => i != null) - .Select(i => i!.Id) - .ToArray(); + result = _libraryManager.GetMusicGenres(query); + } + else + { + result = _libraryManager.GetGenres(query); } - foreach (var filter in filters) - { - switch (filter) - { - case ItemFilter.Dislikes: - query.IsLiked = false; - break; - case ItemFilter.IsFavorite: - query.IsFavorite = true; - break; - case ItemFilter.IsFavoriteOrLikes: - query.IsFavoriteOrLiked = true; - break; - case ItemFilter.IsFolder: - query.IsFolder = true; - break; - case ItemFilter.IsNotFolder: - query.IsFolder = false; - break; - case ItemFilter.IsPlayed: - query.IsPlayed = true; - break; - case ItemFilter.IsResumable: - query.IsResumable = true; - break; - case ItemFilter.IsUnplayed: - query.IsPlayed = false; - break; - case ItemFilter.Likes: - query.IsLiked = true; - break; - } - } - - var result = new QueryResult<(BaseItem, ItemCounts)>(); - - var dtos = result.Items.Select(i => - { - var (baseItem, counts) = i; - var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - - if (!string.IsNullOrWhiteSpace(includeItemTypes)) - { - dto.ChildCount = counts.ItemCount; - dto.ProgramCount = counts.ProgramCount; - dto.SeriesCount = counts.SeriesCount; - dto.EpisodeCount = counts.EpisodeCount; - dto.MovieCount = counts.MovieCount; - dto.TrailerCount = counts.TrailerCount; - dto.AlbumCount = counts.AlbumCount; - dto.SongCount = counts.SongCount; - dto.ArtistCount = counts.ArtistCount; - } - - return dto; - }); - - return new QueryResult - { - Items = dtos.ToArray(), - TotalRecordCount = result.TotalRecordCount - }; + var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes); + return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } /// diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index f173f75ba3..1e0bdb6bc7 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; @@ -28,6 +27,7 @@ namespace Jellyfin.Api.Controllers private readonly ILibraryManager _libraryManager; private readonly IDtoService _dtoService; private readonly IUserManager _userManager; + private readonly IUserDataManager _userDataManager; /// /// Initializes a new instance of the class. @@ -35,84 +35,53 @@ namespace Jellyfin.Api.Controllers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public PersonsController( ILibraryManager libraryManager, IDtoService dtoService, - IUserManager userManager) + IUserManager userManager, + IUserDataManager userDataManager) { _libraryManager = libraryManager; _dtoService = dtoService; _userManager = userManager; + _userDataManager = userDataManager; } /// - /// Gets all persons from a given item, folder, or the entire library. + /// Gets all persons. /// - /// Optional filter by minimum community rating. - /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. /// The search term. - /// Specify this to localize the search to a specific item or folder. Omit to use the root. /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. - /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. - /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. /// Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes. - /// Optional filter by items that are marked as favorite, or not. - /// Optional filter by MediaType. Allows multiple, comma delimited. - /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited. + /// Optional filter by items that are marked as favorite, or not. userId is required. /// Optional, include user data. /// Optional, the max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. If specified, results will be filtered to include only those containing the specified person. - /// Optional. If specified, results will be filtered to include only those containing the specified person id. - /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited. - /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited. + /// Optional. If specified results will be filtered to exclude those containing the specified PersonType. Allows multiple, comma-delimited. + /// Optional. If specified results will be filtered to include only those containing the specified PersonType. Allows multiple, comma-delimited. + /// Optional. If specified, person results will be filtered on items related to said persons. /// User id. - /// Optional filter by items whose name is sorted equally or greater than a given input string. - /// Optional filter by items whose name is sorted equally than a given input string. - /// Optional filter by items whose name is equally or lesser than a given input string. /// Optional, include image information in output. - /// Optional. Include total record count. /// Persons returned. /// An containing the queryresult of persons. [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetPersons( - [FromQuery] double? minCommunityRating, - [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, [FromQuery] string? fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] string? person, - [FromQuery] string? personIds, + [FromQuery] string? excludePersonTypes, [FromQuery] string? personTypes, - [FromQuery] string? studios, - [FromQuery] string? studioIds, + [FromQuery] string? appearsInItemId, [FromQuery] Guid? userId, - [FromQuery] string? nameStartsWithOrGreater, - [FromQuery] string? nameStartsWith, - [FromQuery] string? nameLessThan, - [FromQuery] bool? enableImages = true, - [FromQuery] bool enableTotalRecordCount = true) + [FromQuery] bool? enableImages = true) { var dtoOptions = new DtoOptions() .AddItemFields(fields) @@ -120,136 +89,28 @@ namespace Jellyfin.Api.Controllers .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); User? user = null; - BaseItem parentItem; if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); - } - else - { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); } - var query = new InternalItemsQuery(user) + var isFavoriteInFilters = filters.Any(f => f == ItemFilter.IsFavorite); + var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery { - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), - StartIndex = startIndex, - Limit = limit, - IsFavorite = isFavorite, - NameLessThan = nameLessThan, - NameStartsWith = nameStartsWith, - NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), - Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(), - MinCommunityRating = minCommunityRating, - DtoOptions = dtoOptions, - SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount - }; - - if (!string.IsNullOrWhiteSpace(parentId)) - { - if (parentItem is Folder) - { - query.AncestorIds = new[] { new Guid(parentId) }; - } - else - { - query.ItemIds = new[] { new Guid(parentId) }; - } - } - - // Studios - if (!string.IsNullOrEmpty(studios)) - { - query.StudioIds = studios.Split('|') - .Select(i => - { - try - { - return _libraryManager.GetStudio(i); - } - catch - { - return null; - } - }).Where(i => i != null) - .Select(i => i!.Id) - .ToArray(); - } - - foreach (var filter in filters) - { - switch (filter) - { - case ItemFilter.Dislikes: - query.IsLiked = false; - break; - case ItemFilter.IsFavorite: - query.IsFavorite = true; - break; - case ItemFilter.IsFavoriteOrLikes: - query.IsFavoriteOrLiked = true; - break; - case ItemFilter.IsFolder: - query.IsFolder = true; - break; - case ItemFilter.IsNotFolder: - query.IsFolder = false; - break; - case ItemFilter.IsPlayed: - query.IsPlayed = true; - break; - case ItemFilter.IsResumable: - query.IsResumable = true; - break; - case ItemFilter.IsUnplayed: - query.IsPlayed = false; - break; - case ItemFilter.Likes: - query.IsLiked = true; - break; - } - } - - var result = new QueryResult<(BaseItem, ItemCounts)>(); - - var dtos = result.Items.Select(i => - { - var (baseItem, counts) = i; - var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - - if (!string.IsNullOrWhiteSpace(includeItemTypes)) - { - dto.ChildCount = counts.ItemCount; - dto.ProgramCount = counts.ProgramCount; - dto.SeriesCount = counts.SeriesCount; - dto.EpisodeCount = counts.EpisodeCount; - dto.MovieCount = counts.MovieCount; - dto.TrailerCount = counts.TrailerCount; - dto.AlbumCount = counts.AlbumCount; - dto.SongCount = counts.SongCount; - dto.ArtistCount = counts.ArtistCount; - } - - return dto; + ExcludePersonTypes = RequestHelpers.Split(excludePersonTypes, ',', true), + NameContains = searchTerm, + User = user, + IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite, + AppearsInItemId = string.IsNullOrEmpty(appearsInItemId) ? Guid.Empty : Guid.Parse(appearsInItemId), + Limit = limit ?? 0 }); return new QueryResult { - Items = dtos.ToArray(), - TotalRecordCount = result.TotalRecordCount + Items = peopleItems.Select(person => _dtoService.GetItemByNameDto(person, dtoOptions, null, user)).ToArray(), + TotalRecordCount = peopleItems.Count }; } diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 94eb3f7faa..c5fcfb3569 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -1,10 +1,8 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; -using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -47,7 +45,6 @@ namespace Jellyfin.Api.Controllers /// /// Gets all studios from a given item, folder, or the entire library. /// - /// Optional filter by minimum community rating. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. /// Optional. Search term. @@ -55,22 +52,10 @@ namespace Jellyfin.Api.Controllers /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited. - /// Optional. Specify additional filters to apply. /// Optional filter by items that are marked as favorite, or not. - /// Optional filter by MediaType. Allows multiple, comma delimited. - /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited. /// Optional, include user data. /// Optional, the max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. If specified, results will be filtered to include only those containing the specified person. - /// Optional. If specified, results will be filtered to include only those containing the specified person ids. - /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited. - /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited. /// User id. /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. @@ -82,7 +67,6 @@ namespace Jellyfin.Api.Controllers [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetStudios( - [FromQuery] double? minCommunityRating, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, @@ -90,22 +74,10 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, - [FromQuery] string? studios, - [FromQuery] string? studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, @@ -118,44 +90,23 @@ namespace Jellyfin.Api.Controllers .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); - User? user = null; - BaseItem parentItem; + User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null; - if (userId.HasValue && !userId.Equals(Guid.Empty)) - { - user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); - } - else - { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); - } + var parentItem = _libraryManager.GetParentItem(parentId, userId); var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true); var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true); - var mediaTypesArr = RequestHelpers.Split(mediaTypes, ',', true); var query = new InternalItemsQuery(user) { ExcludeItemTypes = excludeItemTypesArr, IncludeItemTypes = includeItemTypesArr, - MediaTypes = mediaTypesArr, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), - Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(), - MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, EnableTotalRecordCount = enableTotalRecordCount @@ -173,84 +124,9 @@ namespace Jellyfin.Api.Controllers } } - // Studios - if (!string.IsNullOrEmpty(studios)) - { - query.StudioIds = studios.Split('|').Select(i => - { - try - { - return _libraryManager.GetStudio(i); - } - catch - { - return null; - } - }).Where(i => i != null).Select(i => i!.Id) - .ToArray(); - } - - foreach (var filter in filters) - { - switch (filter) - { - case ItemFilter.Dislikes: - query.IsLiked = false; - break; - case ItemFilter.IsFavorite: - query.IsFavorite = true; - break; - case ItemFilter.IsFavoriteOrLikes: - query.IsFavoriteOrLiked = true; - break; - case ItemFilter.IsFolder: - query.IsFolder = true; - break; - case ItemFilter.IsNotFolder: - query.IsFolder = false; - break; - case ItemFilter.IsPlayed: - query.IsPlayed = true; - break; - case ItemFilter.IsResumable: - query.IsResumable = true; - break; - case ItemFilter.IsUnplayed: - query.IsPlayed = false; - break; - case ItemFilter.Likes: - query.IsLiked = true; - break; - } - } - - var result = new QueryResult<(BaseItem, ItemCounts)>(); - var dtos = result.Items.Select(i => - { - var (baseItem, itemCounts) = i; - var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - - if (!string.IsNullOrWhiteSpace(includeItemTypes)) - { - dto.ChildCount = itemCounts.ItemCount; - dto.ProgramCount = itemCounts.ProgramCount; - dto.SeriesCount = itemCounts.SeriesCount; - dto.EpisodeCount = itemCounts.EpisodeCount; - dto.MovieCount = itemCounts.MovieCount; - dto.TrailerCount = itemCounts.TrailerCount; - dto.AlbumCount = itemCounts.AlbumCount; - dto.SongCount = itemCounts.SongCount; - dto.ArtistCount = itemCounts.ArtistCount; - } - - return dto; - }); - - return new QueryResult - { - Items = dtos.ToArray(), - TotalRecordCount = result.TotalRecordCount - }; + var result = _libraryManager.GetStudios(query); + var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes); + return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } /// diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 78d2b831c8..49632dd01a 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -1,11 +1,13 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Net; +using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Http; @@ -189,5 +191,40 @@ namespace Jellyfin.Api.Helpers .Select(i => i!.Value) .ToArray(); } + + internal static QueryResult CreateQueryResult( + QueryResult<(BaseItem, ItemCounts)> result, + DtoOptions dtoOptions, + IDtoService dtoService, + bool includeItemTypes, + User? user) + { + var dtos = result.Items.Select(i => + { + var (baseItem, counts) = i; + var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); + + if (includeItemTypes) + { + dto.ChildCount = counts.ItemCount; + dto.ProgramCount = counts.ProgramCount; + dto.SeriesCount = counts.SeriesCount; + dto.EpisodeCount = counts.EpisodeCount; + dto.MovieCount = counts.MovieCount; + dto.TrailerCount = counts.TrailerCount; + dto.AlbumCount = counts.AlbumCount; + dto.SongCount = counts.SongCount; + dto.ArtistCount = counts.ArtistCount; + } + + return dto; + }); + + return new QueryResult + { + Items = dtos.ToArray(), + TotalRecordCount = result.TotalRecordCount + }; + } } } diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs index 4e09ee5736..5b96a5af65 100644 --- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using Jellyfin.Data.Entities; namespace MediaBrowser.Controller.Entities { @@ -23,6 +24,10 @@ namespace MediaBrowser.Controller.Entities public string NameContains { get; set; } + public User User { get; set; } + + public bool? IsFavorite { get; set; } + public InternalPeopleQuery() { PersonTypes = Array.Empty(); diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 32703c2fd1..c7c79df76d 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -570,5 +570,7 @@ namespace MediaBrowser.Controller.Library List streams, string videoPath, string[] files); + + BaseItem GetParentItem(string parentId, Guid? userId); } } From 6fdcd1205314653b4b7a454ac86134842e225356 Mon Sep 17 00:00:00 2001 From: cvium Date: Thu, 5 Nov 2020 12:53:23 +0100 Subject: [PATCH 0205/1930] Fix build and clean up MusicGenres --- Jellyfin.Api/Controllers/GenresController.cs | 4 +- .../Controllers/MusicGenresController.cs | 137 +----------------- 2 files changed, 7 insertions(+), 134 deletions(-) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index a174d9239b..4e47658b06 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -123,8 +123,8 @@ namespace Jellyfin.Api.Controllers QueryResult<(BaseItem, ItemCounts)> result; if (parentItem is ICollectionFolder parentCollectionFolder - && (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music) - || string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos))) + && (string.Equals(parentCollectionFolder.CollectionType, CollectionType.Music, StringComparison.Ordinal) + || string.Equals(parentCollectionFolder.CollectionType, CollectionType.MusicVideos, StringComparison.Ordinal))) { result = _libraryManager.GetMusicGenres(query); } diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 4de7ef8c88..24075b9052 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -1,11 +1,9 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; -using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -49,7 +47,6 @@ namespace Jellyfin.Api.Controllers /// /// Gets all music genres from a given item, folder, or the entire library. /// - /// Optional filter by minimum community rating. /// Optional. The record index to start at. All items with a lower index will be dropped from the results. /// Optional. The maximum number of records to return. /// The search term. @@ -57,22 +54,9 @@ namespace Jellyfin.Api.Controllers /// Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines. /// Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited. /// Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited. - /// Optional. Specify additional filters to apply. /// Optional filter by items that are marked as favorite, or not. - /// Optional filter by MediaType. Allows multiple, comma delimited. - /// Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited. - /// Optional, include user data. /// Optional, the max number of images to return, per image type. /// Optional. The image types to include in the output. - /// Optional. If specified, results will be filtered to include only those containing the specified person. - /// Optional. If specified, results will be filtered to include only those containing the specified person id. - /// Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited. - /// Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited. - /// Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited. /// User id. /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. @@ -83,7 +67,6 @@ namespace Jellyfin.Api.Controllers /// An containing the queryresult of music genres. [HttpGet] public ActionResult> GetMusicGenres( - [FromQuery] double? minCommunityRating, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, @@ -91,22 +74,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, - [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, - [FromQuery] string? studios, - [FromQuery] string? studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, @@ -117,42 +87,22 @@ namespace Jellyfin.Api.Controllers var dtoOptions = new DtoOptions() .AddItemFields(fields) .AddClientFields(Request) - .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); + .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes); - User? user = null; - BaseItem parentItem; + User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null; - if (userId.HasValue && !userId.Equals(Guid.Empty)) - { - user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); - } - else - { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); - } + var parentItem = _libraryManager.GetParentItem(parentId, userId); var query = new InternalItemsQuery(user) { ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), - Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(y => Convert.ToInt32(y, CultureInfo.InvariantCulture)).ToArray(), - MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, EnableTotalRecordCount = enableTotalRecordCount @@ -170,87 +120,10 @@ namespace Jellyfin.Api.Controllers } } - // Studios - if (!string.IsNullOrEmpty(studios)) - { - query.StudioIds = studios.Split('|') - .Select(i => - { - try - { - return _libraryManager.GetStudio(i); - } - catch - { - return null; - } - }).Where(i => i != null) - .Select(i => i!.Id) - .ToArray(); - } - - foreach (var filter in filters) - { - switch (filter) - { - case ItemFilter.Dislikes: - query.IsLiked = false; - break; - case ItemFilter.IsFavorite: - query.IsFavorite = true; - break; - case ItemFilter.IsFavoriteOrLikes: - query.IsFavoriteOrLiked = true; - break; - case ItemFilter.IsFolder: - query.IsFolder = true; - break; - case ItemFilter.IsNotFolder: - query.IsFolder = false; - break; - case ItemFilter.IsPlayed: - query.IsPlayed = true; - break; - case ItemFilter.IsResumable: - query.IsResumable = true; - break; - case ItemFilter.IsUnplayed: - query.IsPlayed = false; - break; - case ItemFilter.Likes: - query.IsLiked = true; - break; - } - } - var result = _libraryManager.GetMusicGenres(query); - var dtos = result.Items.Select(i => - { - var (baseItem, counts) = i; - var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - - if (!string.IsNullOrWhiteSpace(includeItemTypes)) - { - dto.ChildCount = counts.ItemCount; - dto.ProgramCount = counts.ProgramCount; - dto.SeriesCount = counts.SeriesCount; - dto.EpisodeCount = counts.EpisodeCount; - dto.MovieCount = counts.MovieCount; - dto.TrailerCount = counts.TrailerCount; - dto.AlbumCount = counts.AlbumCount; - dto.SongCount = counts.SongCount; - dto.ArtistCount = counts.ArtistCount; - } - - return dto; - }); - - return new QueryResult - { - Items = dtos.ToArray(), - TotalRecordCount = result.TotalRecordCount - }; + var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes); + return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } /// From c96aa0551db48063dba74196816ffe51a839b44d Mon Sep 17 00:00:00 2001 From: Stepan Date: Thu, 5 Nov 2020 13:25:29 +0100 Subject: [PATCH 0206/1930] Added NamingOptions tests --- .../Common/NamingOptionsTest.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs diff --git a/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs b/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs new file mode 100644 index 0000000000..3892d00f61 --- /dev/null +++ b/tests/Jellyfin.Naming.Tests/Common/NamingOptionsTest.cs @@ -0,0 +1,36 @@ +using Emby.Naming.Common; +using Xunit; + +namespace Jellyfin.Naming.Tests.Common +{ + public class NamingOptionsTest + { + [Fact] + public void TestNamingOptionsCompile() + { + var options = new NamingOptions(); + + Assert.NotEmpty(options.VideoFileStackingRegexes); + Assert.NotEmpty(options.CleanDateTimeRegexes); + Assert.NotEmpty(options.CleanStringRegexes); + Assert.NotEmpty(options.EpisodeWithoutSeasonRegexes); + Assert.NotEmpty(options.EpisodeMultiPartRegexes); + } + + [Fact] + public void TestNamingOptionsEpisodeExpressions() + { + var exp = new EpisodeExpression(string.Empty); + + Assert.False(exp.IsOptimistic); + exp.IsOptimistic = true; + Assert.True(exp.IsOptimistic); + + Assert.Equal(string.Empty, exp.Expression); + Assert.NotNull(exp.Regex); + exp.Expression = "test"; + Assert.Equal("test", exp.Expression); + Assert.NotNull(exp.Regex); + } + } +} From 57411503673c07f4130b73c578c06ccfecc4c612 Mon Sep 17 00:00:00 2001 From: Stepan Date: Thu, 5 Nov 2020 14:51:27 +0100 Subject: [PATCH 0207/1930] Enable MultiVersion video tests and added support for naming based on tests 11 & 8 --- Emby.Naming/Common/NamingOptions.cs | 2 +- Emby.Naming/Video/VideoListResolver.cs | 6 ++ .../Video/MultiVersionTests.cs | 79 ++++++++++--------- 3 files changed, 47 insertions(+), 40 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index d2f07817a6..3a7bcb7d72 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -133,7 +133,7 @@ namespace Emby.Naming.Common CleanStrings = new[] { - @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|xvidvd|xxx|www.www|\[.*\])([ _\,\.\(\)\[\]\-]|$)", + @"[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multisubs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r3|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|blu-ray|x264|x265|h264|xvid|xvidvd|xxx|www.www|AAC|DTS|\[.*\])([ _\,\.\(\)\[\]\-]|$)", @"(\[.*\])" }; diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 190562cfcd..be9b4959a7 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -212,9 +212,15 @@ namespace Emby.Naming.Video if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) { + if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName)) + { + testFilename = cleanName.ToString(); + } + testFilename = testFilename.Substring(folderName.Length).Trim(); return string.IsNullOrEmpty(testFilename) || testFilename[0] == '-' + || testFilename[0] == '_' || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); } diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index 4198d69ff8..9df6904ef6 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Collections.Generic; +using System.Linq; using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Model.IO; @@ -11,8 +12,8 @@ namespace Jellyfin.Naming.Tests.Video private readonly NamingOptions _namingOptions = new NamingOptions(); // FIXME - // [Fact] - private void TestMultiEdition1() + [Fact] + public void TestMultiEdition1() { var files = new[] { @@ -35,8 +36,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiEdition2() + [Fact] + public void TestMultiEdition2() { var files = new[] { @@ -81,8 +82,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestLetterFolders() + [Fact] + public void TestLetterFolders() { var files = new[] { @@ -109,8 +110,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiVersionLimit() + [Fact] + public void TestMultiVersionLimit() { var files = new[] { @@ -138,8 +139,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiVersionLimit2() + [Fact] + public void TestMultiVersionLimit2() { var files = new[] { @@ -168,8 +169,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiVersion3() + [Fact] + public void TestMultiVersion3() { var files = new[] { @@ -194,8 +195,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiVersion4() + [Fact] + public void TestMultiVersion4() { // Test for false positive @@ -221,9 +222,8 @@ namespace Jellyfin.Naming.Tests.Video Assert.Empty(result[0].AlternateVersions); } - // FIXME - // [Fact] - private void TestMultiVersion5() + [Fact] + public void TestMultiVersion5() { var files = new[] { @@ -254,8 +254,8 @@ namespace Jellyfin.Naming.Tests.Video } // FIXME - // [Fact] - private void TestMultiVersion6() + [Fact] + public void TestMultiVersion6() { var files = new[] { @@ -285,9 +285,8 @@ namespace Jellyfin.Naming.Tests.Video Assert.True(result[0].AlternateVersions[5].Is3D); } - // FIXME - // [Fact] - private void TestMultiVersion7() + [Fact] + public void TestMultiVersion7() { var files = new[] { @@ -306,12 +305,9 @@ namespace Jellyfin.Naming.Tests.Video Assert.Equal(2, result.Count); } - // FIXME - // [Fact] - private void TestMultiVersion8() + [Fact] + public void TestMultiVersion8() { - // This is not actually supported yet - var files = new[] { @"/movies/Iron Man/Iron Man.mkv", @@ -339,9 +335,8 @@ namespace Jellyfin.Naming.Tests.Video Assert.True(result[0].AlternateVersions[4].Is3D); } - // FIXME - // [Fact] - private void TestMultiVersion9() + [Fact] + public void TestMultiVersion9() { // Test for false positive @@ -367,9 +362,8 @@ namespace Jellyfin.Naming.Tests.Video Assert.Empty(result[0].AlternateVersions); } - // FIXME - // [Fact] - private void TestMultiVersion10() + [Fact] + public void TestMultiVersion10() { var files = new[] { @@ -390,12 +384,9 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result[0].AlternateVersions); } - // FIXME - // [Fact] - private void TestMultiVersion11() + [Fact] + public void TestMultiVersion11() { - // Currently not supported but we should probably handle this. - var files = new[] { @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [1080p] Blu-ray.x264.DTS.mkv", @@ -415,6 +406,16 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result[0].AlternateVersions); } + [Fact] + public void TestEmptyList() + { + var resolver = GetResolver(); + + var result = resolver.Resolve(new List()).ToList(); + + Assert.Empty(result); + } + private VideoListResolver GetResolver() { return new VideoListResolver(_namingOptions); From 8c461aff097d2521faed4d56e5822c8f4817bb49 Mon Sep 17 00:00:00 2001 From: SaddFox Date: Thu, 5 Nov 2020 12:53:24 +0000 Subject: [PATCH 0208/1930] Translated using Weblate (Slovenian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sl/ --- .../Localization/Core/sl-SI.json | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sl-SI.json b/Emby.Server.Implementations/Localization/Core/sl-SI.json index ff4b9e84fd..66681f0251 100644 --- a/Emby.Server.Implementations/Localization/Core/sl-SI.json +++ b/Emby.Server.Implementations/Localization/Core/sl-SI.json @@ -3,20 +3,20 @@ "AppDeviceValues": "Aplikacija: {0}, Naprava: {1}", "Application": "Aplikacija", "Artists": "Izvajalci", - "AuthenticationSucceededWithUserName": "{0} preverjanje pristnosti uspešno", + "AuthenticationSucceededWithUserName": "{0} se je uspešno prijavil", "Books": "Knjige", - "CameraImageUploadedFrom": "Nova fotografija je bila naložena z {0}", + "CameraImageUploadedFrom": "Nova fotografija je bila naložena iz {0}", "Channels": "Kanali", "ChapterNameValue": "Poglavje {0}", "Collections": "Zbirke", "DeviceOfflineWithName": "{0} je prekinil povezavo", "DeviceOnlineWithName": "{0} je povezan", - "FailedLoginAttemptWithUserName": "Neuspešen poskus prijave z {0}", + "FailedLoginAttemptWithUserName": "Neuspešen poskus prijave iz {0}", "Favorites": "Priljubljeno", "Folders": "Mape", "Genres": "Zvrsti", "HeaderAlbumArtists": "Izvajalci albuma", - "HeaderContinueWatching": "Nadaljuj gledanje", + "HeaderContinueWatching": "Nadaljuj z ogledom", "HeaderFavoriteAlbums": "Priljubljeni albumi", "HeaderFavoriteArtists": "Priljubljeni izvajalci", "HeaderFavoriteEpisodes": "Priljubljene epizode", @@ -32,23 +32,23 @@ "LabelIpAddressValue": "IP naslov: {0}", "LabelRunningTimeValue": "Čas trajanja: {0}", "Latest": "Najnovejše", - "MessageApplicationUpdated": "Jellyfin Server je bil posodobljen", - "MessageApplicationUpdatedTo": "Jellyfin Server je bil posodobljen na {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Oddelek nastavitve strežnika {0} je bil posodobljen", + "MessageApplicationUpdated": "Jellyfin strežnik je bil posodobljen", + "MessageApplicationUpdatedTo": "Jellyfin strežnik je bil posodobljen na {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Oddelek nastavitev {0} je bil posodobljen", "MessageServerConfigurationUpdated": "Nastavitve strežnika so bile posodobljene", - "MixedContent": "Razne vsebine", + "MixedContent": "Mešane vsebine", "Movies": "Filmi", "Music": "Glasba", "MusicVideos": "Glasbeni videi", "NameInstallFailed": "{0} namestitev neuspešna", "NameSeasonNumber": "Sezona {0}", - "NameSeasonUnknown": "Season neznana", + "NameSeasonUnknown": "Neznana sezona", "NewVersionIsAvailable": "Nova različica Jellyfin strežnika je na voljo za prenos.", "NotificationOptionApplicationUpdateAvailable": "Posodobitev aplikacije je na voljo", "NotificationOptionApplicationUpdateInstalled": "Posodobitev aplikacije je bila nameščena", - "NotificationOptionAudioPlayback": "Predvajanje zvoka začeto", - "NotificationOptionAudioPlaybackStopped": "Predvajanje zvoka zaustavljeno", - "NotificationOptionCameraImageUploaded": "Posnetek kamere naložen", + "NotificationOptionAudioPlayback": "Predvajanje zvoka se je začelo", + "NotificationOptionAudioPlaybackStopped": "Predvajanje zvoka se je ustavilo", + "NotificationOptionCameraImageUploaded": "Fotografija naložena", "NotificationOptionInstallationFailed": "Namestitev neuspešna", "NotificationOptionNewLibraryContent": "Nove vsebine dodane", "NotificationOptionPluginError": "Napaka dodatka", @@ -56,41 +56,41 @@ "NotificationOptionPluginUninstalled": "Dodatek odstranjen", "NotificationOptionPluginUpdateInstalled": "Posodobitev dodatka nameščena", "NotificationOptionServerRestartRequired": "Potreben je ponovni zagon strežnika", - "NotificationOptionTaskFailed": "Razporejena naloga neuspešna", + "NotificationOptionTaskFailed": "Načrtovano opravilo neuspešno", "NotificationOptionUserLockedOut": "Uporabnik zaklenjen", "NotificationOptionVideoPlayback": "Predvajanje videa se je začelo", "NotificationOptionVideoPlaybackStopped": "Predvajanje videa se je ustavilo", "Photos": "Fotografije", "Playlists": "Seznami predvajanja", - "Plugin": "Plugin", + "Plugin": "Dodatek", "PluginInstalledWithName": "{0} je bil nameščen", "PluginUninstalledWithName": "{0} je bil odstranjen", "PluginUpdatedWithName": "{0} je bil posodobljen", - "ProviderValue": "Provider: {0}", + "ProviderValue": "Ponudnik: {0}", "ScheduledTaskFailedWithName": "{0} ni uspelo", "ScheduledTaskStartedWithName": "{0} začeto", "ServerNameNeedsToBeRestarted": "{0} mora biti ponovno zagnan", "Shows": "Serije", "Songs": "Pesmi", - "StartupEmbyServerIsLoading": "Jellyfin Server se nalaga. Poskusi ponovno kasneje.", + "StartupEmbyServerIsLoading": "Jellyfin strežnik se zaganja. Poskusite ponovno kasneje.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Neuspešen prenos podnapisov iz {0} za {1}", "Sync": "Sinhroniziraj", - "System": "System", + "System": "Sistem", "TvShows": "TV serije", - "User": "User", + "User": "Uporabnik", "UserCreatedWithName": "Uporabnik {0} je bil ustvarjen", "UserDeletedWithName": "Uporabnik {0} je bil izbrisan", "UserDownloadingItemWithValues": "{0} prenaša {1}", "UserLockedOutWithName": "Uporabnik {0} je bil zaklenjen", "UserOfflineFromDevice": "{0} je prekinil povezavo z {1}", - "UserOnlineFromDevice": "{0} je aktiven iz {1}", + "UserOnlineFromDevice": "{0} je aktiven na {1}", "UserPasswordChangedWithName": "Geslo za uporabnika {0} je bilo spremenjeno", "UserPolicyUpdatedWithName": "Pravilnik uporabe je bil posodobljen za uporabnika {0}", "UserStartedPlayingItemWithValues": "{0} predvaja {1} na {2}", "UserStoppedPlayingItemWithValues": "{0} je nehal predvajati {1} na {2}", "ValueHasBeenAddedToLibrary": "{0} je bil dodan vaši knjižnici", - "ValueSpecialEpisodeName": "Poseben - {0}", + "ValueSpecialEpisodeName": "Posebna - {0}", "VersionNumber": "Različica {0}", "TaskDownloadMissingSubtitles": "Prenesi manjkajoče podnapise", "TaskRefreshChannelsDescription": "Osveži podatke spletnih kanalov.", @@ -102,7 +102,7 @@ "TaskRefreshPeopleDescription": "Osveži metapodatke za igralce in režiserje v vaši knjižnici.", "TaskRefreshPeople": "Osveži osebe", "TaskCleanLogsDescription": "Izbriše dnevniške datoteke starejše od {0} dni.", - "TaskCleanLogs": "Počisti mapo dnevnika", + "TaskCleanLogs": "Počisti mapo dnevnikov", "TaskRefreshLibraryDescription": "Preišče vašo knjižnico za nove datoteke in osveži metapodatke.", "TaskRefreshLibrary": "Preišči knjižnico predstavnosti", "TaskRefreshChapterImagesDescription": "Ustvari sličice za poglavja videoposnetkov.", From 3466dc558186f435eafae9b9d3fd80621fdbd79f Mon Sep 17 00:00:00 2001 From: Stepan Date: Thu, 5 Nov 2020 16:59:15 +0100 Subject: [PATCH 0209/1930] Finish coverage for Emby.Naming.Video --- Emby.Naming/Common/NamingOptions.cs | 6 +- Emby.Naming/Video/ExtraResolver.cs | 7 +- Emby.Naming/Video/FlagParser.cs | 2 +- Emby.Naming/Video/StackResolver.cs | 8 +- Emby.Naming/Video/StubResolver.cs | 2 +- Emby.Naming/Video/VideoFileInfo.cs | 34 ++- Emby.Naming/Video/VideoResolver.cs | 28 +-- .../Jellyfin.Naming.Tests/Video/ExtraTests.cs | 25 +- .../Jellyfin.Naming.Tests/Video/StubTests.cs | 3 +- .../Video/VideoListResolverTests.cs | 29 ++- .../Video/VideoResolverTests.cs | 235 +++++++++--------- 11 files changed, 230 insertions(+), 149 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 3a7bcb7d72..a1b95954ec 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -120,9 +120,9 @@ namespace Emby.Naming.Common VideoFileStackingExpressions = new[] { - "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(.*?)(\\.[^.]+)$", - "(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(.*?)(\\.[^.]+)$", - "(.*?)([ ._-]*[a-d])(.*?)(\\.[^.]+)$" + "(?.*?)(?<volume>[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[0-9]+)(?<ignore>.*?)(?<extension>\\.[^.]+)$", + "(?<title>.*?)(?<volume>[ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck])[ _.-]*[a-d])(?<ignore>.*?)(?<extension>\\.[^.]+)$", + "(?<title>.*?)(?<volume>[ ._-]*[a-d])(?<ignore>.*?)(?<extension>\\.[^.]+)$" }; CleanDateTimes = new[] diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index fc0424faab..bd78299dcd 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -45,7 +45,8 @@ namespace Emby.Naming.Video } else { - return result; + // Currently unreachable code if new rule.MediaType is desired add if clause with proper tests + throw new InvalidOperationException(); } if (rule.RuleType == ExtraRuleType.Filename) @@ -70,6 +71,9 @@ namespace Emby.Naming.Video } else if (rule.RuleType == ExtraRuleType.Regex) { + // Currently unreachable code if new rule.MediaType is desired add if clause with proper tests + throw new InvalidOperationException(); + /* var filename = Path.GetFileName(path); var regex = new Regex(rule.Token, RegexOptions.IgnoreCase); @@ -79,6 +83,7 @@ namespace Emby.Naming.Video result.ExtraType = rule.ExtraType; result.Rule = rule; } + */ } else if (rule.RuleType == ExtraRuleType.DirectoryName) { diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs index 27ca1abf1a..6015c41a0c 100644 --- a/Emby.Naming/Video/FlagParser.cs +++ b/Emby.Naming/Video/FlagParser.cs @@ -24,7 +24,7 @@ namespace Emby.Naming.Video { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException(nameof(path)); + return Array.Empty<string>(); } // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _. diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index e11b4063ce..30b812e21d 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -86,10 +86,10 @@ namespace Emby.Naming.Video if (match1.Success) { - var title1 = match1.Groups[1].Value; - var volume1 = match1.Groups[2].Value; - var ignore1 = match1.Groups[3].Value; - var extension1 = match1.Groups[4].Value; + var title1 = match1.Groups["title"].Value; + var volume1 = match1.Groups["volume"].Value; + var ignore1 = match1.Groups["ignore"].Value; + var extension1 = match1.Groups["extension"].Value; var j = i + 1; while (j < list.Count) diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index f1b5d7bcca..b0eb92e53e 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -14,7 +14,7 @@ namespace Emby.Naming.Video { stubType = default; - if (path == null) + if (string.IsNullOrEmpty(path)) { return false; } diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 12bd8c4364..7d7411a563 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -7,6 +7,35 @@ namespace Emby.Naming.Video /// </summary> public class VideoFileInfo { + /// <summary> + /// Initializes a new instance of the <see cref="VideoFileInfo"/> class. + /// </summary> + /// <param name="name">Name of file.</param> + /// <param name="path">Path to the file.</param> + /// <param name="container">Container type.</param> + /// <param name="year">Year of release.</param> + /// <param name="extraType">Extra type.</param> + /// <param name="extraRule">Extra rule.</param> + /// <param name="format3D">Format 3D.</param> + /// <param name="is3D">Is 3D.</param> + /// <param name="isStub">Is Stub.</param> + /// <param name="stubType">Stub type.</param> + /// <param name="isDirectory">Is directory.</param> + public VideoFileInfo(string name, string? path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default) + { + Path = path; + Container = container; + Name = name; + Year = year; + ExtraType = extraType; + ExtraRule = extraRule; + Format3D = format3D; + Is3D = is3D; + IsStub = isStub; + StubType = stubType; + IsDirectory = isDirectory; + } + /// <summary> /// Gets or sets the path. /// </summary> @@ -23,7 +52,7 @@ namespace Emby.Naming.Video /// Gets or sets the name. /// </summary> /// <value>The name.</value> - public string? Name { get; set; } + public string Name { get; set; } /// <summary> /// Gets or sets the year. @@ -84,8 +113,7 @@ namespace Emby.Naming.Video /// <inheritdoc /> public override string ToString() { - // Makes debugging easier - return Name ?? base.ToString(); + return "VideoFileInfo(Name: '" + Name + "')"; } } } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index b9ff90179f..fed567d03d 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -49,7 +49,7 @@ namespace Emby.Naming.Video { if (string.IsNullOrEmpty(path)) { - throw new ArgumentNullException(nameof(path)); + return null; } bool isStub = false; @@ -99,20 +99,18 @@ namespace Emby.Naming.Video } } - return new VideoFileInfo - { - Path = path, - Container = container, - IsStub = isStub, - Name = name, - Year = year, - StubType = stubType, - Is3D = format3DResult.Is3D, - Format3D = format3DResult.Format3D, - ExtraType = extraResult.ExtraType, - IsDirectory = isDirectory, - ExtraRule = extraResult.Rule - }; + return new VideoFileInfo( + path: path, + container: container, + isStub: isStub, + name: name, + year: year, + stubType: stubType, + is3D: format3DResult.Is3D, + format3D: format3DResult.Format3D, + extraType: extraResult.ExtraType, + isDirectory: isDirectory, + extraRule: extraResult.Rule); } public bool IsVideoFile(string path) diff --git a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs index 8dfb8f8591..12a9b023bf 100644 --- a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs @@ -1,7 +1,9 @@ -using Emby.Naming.Common; +using System; +using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Model.Entities; using Xunit; +using MediaType = Emby.Naming.Common.MediaType; namespace Jellyfin.Naming.Tests.Video { @@ -93,6 +95,27 @@ namespace Jellyfin.Naming.Tests.Video } } + [Fact] + public void TestExtraInfo_InvalidRuleMediaType() + { + var options = new NamingOptions { VideoExtraRules = new[] { new ExtraRule(ExtraType.Unknown, ExtraRuleType.DirectoryName, " ", MediaType.Photo) } }; + Assert.Throws<InvalidOperationException>(() => GetExtraTypeParser(options).GetExtraInfo("sample.jpg")); + } + + [Fact] + public void TestExtraInfo_InvalidRuleType() + { + var options = new NamingOptions { VideoExtraRules = new[] { new ExtraRule(ExtraType.Unknown, ExtraRuleType.Regex, " ", MediaType.Video) } }; + Assert.Throws<InvalidOperationException>(() => GetExtraTypeParser(options).GetExtraInfo("sample.mp4")); + } + + [Fact] + public void TestFlagsParser() + { + var flags = new FlagParser(_videoOptions).GetFlags(string.Empty); + Assert.Empty(flags); + } + private ExtraResolver GetExtraTypeParser(NamingOptions videoOptions) { return new ExtraResolver(videoOptions); diff --git a/tests/Jellyfin.Naming.Tests/Video/StubTests.cs b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs index 30ba941365..6e759c6d6b 100644 --- a/tests/Jellyfin.Naming.Tests/Video/StubTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/StubTests.cs @@ -1,4 +1,4 @@ -using Emby.Naming.Common; +using Emby.Naming.Common; using Emby.Naming.Video; using Xunit; @@ -23,6 +23,7 @@ namespace Jellyfin.Naming.Tests.Video Test("video.hdtv.disc", true, "tv"); Test("video.pdtv.disc", true, "tv"); Test("video.dsr.disc", true, "tv"); + Test(string.Empty, false, "tv"); } [Fact] diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs index 12c4a50fe3..215c7e5405 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoListResolverTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Model.IO; @@ -369,6 +369,26 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result); } + [Fact] + public void TestFourRooms() + { + var files = new[] + { + @"Four Rooms - A.avi", + @"Four Rooms - A.mp4" + }; + + var resolver = GetResolver(); + + var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + }).ToList()).ToList(); + + Assert.Equal(2, result.Count); + } + [Fact] public void TestMovieTrailer() { @@ -431,6 +451,13 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result); } + [Fact] + public void TestDirectoryStack() + { + var stack = new FileStack(); + Assert.False(stack.ContainsFile("XX", true)); + } + private VideoListResolver GetResolver() { return new VideoListResolver(_namingOptions); diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index 99828b2eb7..3bdafa84d9 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Model.Entities; @@ -14,165 +15,135 @@ namespace Jellyfin.Naming.Tests.Video { yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/7 Psychos.mkv/7 Psychos.mkv", - Container = "mkv", - Name = "7 Psychos" - } + new VideoFileInfo( + path: @"/server/Movies/7 Psychos.mkv/7 Psychos.mkv", + container: "mkv", + name: "7 Psychos") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/3 days to kill (2005)/3 days to kill (2005).mkv", - Container = "mkv", - Name = "3 days to kill", - Year = 2005 - } + new VideoFileInfo( + path: @"/server/Movies/3 days to kill (2005)/3 days to kill (2005).mkv", + container: "mkv", + name: "3 days to kill", + year: 2005) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/American Psycho/American.Psycho.mkv", - Container = "mkv", - Name = "American.Psycho", - } + new VideoFileInfo( + path: @"/server/Movies/American Psycho/American.Psycho.mkv", + container: "mkv", + name: "American.Psycho") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/brave (2007)/brave (2006).3d.sbs.mkv", - Container = "mkv", - Name = "brave", - Year = 2006, - Is3D = true, - Format3D = "sbs", - } + new VideoFileInfo( + path: @"/server/Movies/brave (2007)/brave (2006).3d.sbs.mkv", + container: "mkv", + name: "brave", + year: 2006, + is3D: true, + format3D: "sbs") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006).3d1.sbas.mkv", - Container = "mkv", - Name = "300", - Year = 2006 - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006).3d1.sbas.mkv", + container: "mkv", + name: "300", + year: 2006) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006).3d.sbs.mkv", - Container = "mkv", - Name = "300", - Year = 2006, - Is3D = true, - Format3D = "sbs", - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006).3d.sbs.mkv", + container: "mkv", + name: "300", + year: 2006, + is3D: true, + format3D: "sbs") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/brave (2007)/brave (2006)-trailer.bluray.disc", - Container = "disc", - Name = "brave", - Year = 2006, - IsStub = true, - StubType = "bluray", - } + new VideoFileInfo( + path: @"/server/Movies/brave (2007)/brave (2006)-trailer.bluray.disc", + container: "disc", + name: "brave", + year: 2006, + isStub: true, + stubType: "bluray") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006)-trailer.bluray.disc", - Container = "disc", - Name = "300", - Year = 2006, - IsStub = true, - StubType = "bluray", - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006)-trailer.bluray.disc", + container: "disc", + name: "300", + year: 2006, + isStub: true, + stubType: "bluray") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/Brave (2007)/Brave (2006).bluray.disc", - Container = "disc", - Name = "Brave", - Year = 2006, - IsStub = true, - StubType = "bluray", - } + new VideoFileInfo( + path: @"/server/Movies/Brave (2007)/Brave (2006).bluray.disc", + container: "disc", + name: "Brave", + year: 2006, + isStub: true, + stubType: "bluray") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006).bluray.disc", - Container = "disc", - Name = "300", - Year = 2006, - IsStub = true, - StubType = "bluray", - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006).bluray.disc", + container: "disc", + name: "300", + year: 2006, + isStub: true, + stubType: "bluray") }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006)-trailer.mkv", - Container = "mkv", - Name = "300", - Year = 2006, - ExtraType = ExtraType.Trailer, - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006)-trailer.mkv", + container: "mkv", + name: "300", + year: 2006, + extraType: ExtraType.Trailer) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/Brave (2007)/Brave (2006)-trailer.mkv", - Container = "mkv", - Name = "Brave", - Year = 2006, - ExtraType = ExtraType.Trailer, - } + new VideoFileInfo( + path: @"/server/Movies/Brave (2007)/Brave (2006)-trailer.mkv", + container: "mkv", + name: "Brave", + year: 2006, + extraType: ExtraType.Trailer) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/300 (2007)/300 (2006).mkv", - Container = "mkv", - Name = "300", - Year = 2006 - } + new VideoFileInfo( + path: @"/server/Movies/300 (2007)/300 (2006).mkv", + container: "mkv", + name: "300", + year: 2006) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/Bad Boys (1995)/Bad Boys (1995).mkv", - Container = "mkv", - Name = "Bad Boys", - Year = 1995, - } + new VideoFileInfo( + path: @"/server/Movies/Bad Boys (1995)/Bad Boys (1995).mkv", + container: "mkv", + name: "Bad Boys", + year: 1995) }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/Brave (2007)/Brave (2006).mkv", - Container = "mkv", - Name = "Brave", - Year = 2006, - } + new VideoFileInfo( + path: @"/server/Movies/Brave (2007)/Brave (2006).mkv", + container: "mkv", + name: "Brave", + year: 2006) }; } @@ -194,6 +165,34 @@ namespace Jellyfin.Naming.Tests.Video Assert.Equal(result?.StubType, expectedResult.StubType); Assert.Equal(result?.IsDirectory, expectedResult.IsDirectory); Assert.Equal(result?.FileNameWithoutExtension, expectedResult.FileNameWithoutExtension); + Assert.Equal(result?.ToString(), expectedResult.ToString()); + } + + [Fact] + public void ResolveFile_EmptyPath() + { + var result = new VideoResolver(_namingOptions).ResolveFile(string.Empty); + + Assert.Null(result); + } + + [Fact] + public void ResolveDirectoryTest() + { + var paths = new[] + { + @"/Server/Iron Man", + @"Batman", + string.Empty + }; + + var resolver = new VideoResolver(_namingOptions); + var results = paths.Select(path => resolver.ResolveDirectory(path)).ToList(); + + Assert.Equal(3, results.Count); + Assert.NotNull(results[0]); + Assert.NotNull(results[1]); + Assert.Null(results[2]); } } } From 3c6cbb6161eaa504df9fea28830b026a3a9001cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= <lukas@kucharczyk.xyz> Date: Thu, 5 Nov 2020 15:00:18 +0000 Subject: [PATCH 0210/1930] Translated using Weblate (Czech) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/cs/ --- Emby.Server.Implementations/Localization/Core/cs.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index b34fad066a..fb31b01ff8 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Internetové kanály", "TasksApplicationCategory": "Aplikace", "TasksLibraryCategory": "Knihovna", - "TasksMaintenanceCategory": "Údržba" + "TasksMaintenanceCategory": "Údržba", + "TaskCleanActivityLogDescription": "Smazat záznamy o aktivitě, které jsou starší než zadaná doba.", + "TaskCleanActivityLog": "Smazat záznam aktivity" } From 3756611d0155b77d1a17be63e71a3181904d4bc3 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 5 Nov 2020 13:23:22 -0700 Subject: [PATCH 0211/1930] Add /Users/Me endpoint --- Jellyfin.Api/Controllers/UserController.cs | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 7b0897bfb9..0f7c25d0e4 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -530,6 +530,33 @@ namespace Jellyfin.Api.Controllers return result; } + /// <summary> + /// Gets the user based on auth token. + /// </summary> + /// <response code="200">User returned.</response> + /// <response code="400">Token is not owned by a user.</response> + /// <returns>A <see cref="UserDto"/> for the authenticated user.</returns> + [HttpGet("Me")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public ActionResult<UserDto> GetCurrentUser() + { + var userId = ClaimHelpers.GetUserId(Request.HttpContext.User); + if (userId == null) + { + return BadRequest(); + } + + var user = _userManager.GetUserById(userId.Value); + if (user == null) + { + return BadRequest(); + } + + return _userManager.GetUserDto(user); + } + private IEnumerable<UserDto> Get(bool? isHidden, bool? isDisabled, bool filterByDevice, bool filterByNetwork) { var users = _userManager.Users; From eeb3177cc3d8911b0d06dadb6f7d03600d11dac1 Mon Sep 17 00:00:00 2001 From: public_yusuke <townstock@ksf.biglobe.ne.jp> Date: Fri, 6 Nov 2020 02:49:23 +0000 Subject: [PATCH 0212/1930] Translated using Weblate (Japanese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ja/ --- Emby.Server.Implementations/Localization/Core/ja.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ja.json b/Emby.Server.Implementations/Localization/Core/ja.json index 35004f0eb4..02bf8496ff 100644 --- a/Emby.Server.Implementations/Localization/Core/ja.json +++ b/Emby.Server.Implementations/Localization/Core/ja.json @@ -96,7 +96,7 @@ "TaskRefreshLibraryDescription": "メディアライブラリをスキャンして新しいファイルを探し、メタデータをリフレッシュします。", "TaskRefreshLibrary": "メディアライブラリのスキャン", "TaskCleanCacheDescription": "不要なキャッシュを消去します。", - "TaskCleanCache": "キャッシュの掃除", + "TaskCleanCache": "キャッシュを消去", "TasksChannelsCategory": "ネットチャンネル", "TasksApplicationCategory": "アプリケーション", "TasksLibraryCategory": "ライブラリ", @@ -112,5 +112,7 @@ "TaskDownloadMissingSubtitlesDescription": "メタデータ構成に基づいて、欠落している字幕をインターネットで検索します。", "TaskRefreshChapterImagesDescription": "チャプターのあるビデオのサムネイルを作成します。", "TaskRefreshChapterImages": "チャプター画像を抽出する", - "TaskDownloadMissingSubtitles": "不足している字幕をダウンロードする" + "TaskDownloadMissingSubtitles": "不足している字幕をダウンロードする", + "TaskCleanActivityLogDescription": "設定された期間よりも古いアクティビティの履歴を削除します。", + "TaskCleanActivityLog": "アクティビティの履歴を消去" } From 6e6ecbc988286108c691578a526f1f29aef4a229 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Fri, 6 Nov 2020 08:34:20 +0100 Subject: [PATCH 0213/1930] Make /MusicGenres obsolete --- Jellyfin.Api/Controllers/GenresController.cs | 1 + .../Controllers/MusicGenresController.cs | 82 ------------------- .../ApiServiceCollectionExtensions.cs | 1 + .../Filters/ObsoleteRoutesFilter.cs | 22 +++++ 4 files changed, 24 insertions(+), 82 deletions(-) create mode 100644 Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 4e47658b06..94c1b4b9ee 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -66,6 +66,7 @@ namespace Jellyfin.Api.Controllers /// <response code="200">Genres returned.</response> /// <returns>An <see cref="OkResult"/> containing the queryresult of genres.</returns> [HttpGet] + [HttpGet("/MusicGenres", Name = "GetMusicGenres-Deprecated")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetGenres( [FromQuery] int? startIndex, diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 24075b9052..28295f0cbf 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -44,88 +44,6 @@ namespace Jellyfin.Api.Controllers _dtoService = dtoService; } - /// <summary> - /// Gets all music genres from a given item, folder, or the entire library. - /// </summary> - /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> - /// <param name="limit">Optional. The maximum number of records to return.</param> - /// <param name="searchTerm">The search term.</param> - /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> - /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param> - /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.</param> - /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param> - /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> - /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> - /// <param name="userId">User id.</param> - /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param> - /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param> - /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param> - /// <param name="enableImages">Optional, include image information in output.</param> - /// <param name="enableTotalRecordCount">Optional. Include total record count.</param> - /// <response code="200">Music genres returned.</response> - /// <returns>An <see cref="OkResult"/> containing the queryresult of music genres.</returns> - [HttpGet] - public ActionResult<QueryResult<BaseItemDto>> GetMusicGenres( - [FromQuery] int? startIndex, - [FromQuery] int? limit, - [FromQuery] string? searchTerm, - [FromQuery] string? parentId, - [FromQuery] string? fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, - [FromQuery] bool? isFavorite, - [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, - [FromQuery] Guid? userId, - [FromQuery] string? nameStartsWithOrGreater, - [FromQuery] string? nameStartsWith, - [FromQuery] string? nameLessThan, - [FromQuery] bool? enableImages = true, - [FromQuery] bool enableTotalRecordCount = true) - { - var dtoOptions = new DtoOptions() - .AddItemFields(fields) - .AddClientFields(Request) - .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes); - - User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null; - - var parentItem = _libraryManager.GetParentItem(parentId, userId); - - var query = new InternalItemsQuery(user) - { - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - StartIndex = startIndex, - Limit = limit, - IsFavorite = isFavorite, - NameLessThan = nameLessThan, - NameStartsWith = nameStartsWith, - NameStartsWithOrGreater = nameStartsWithOrGreater, - DtoOptions = dtoOptions, - SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount - }; - - if (!string.IsNullOrWhiteSpace(parentId)) - { - if (parentItem is Folder) - { - query.AncestorIds = new[] { new Guid(parentId) }; - } - else - { - query.ItemIds = new[] { new Guid(parentId) }; - } - } - - var result = _libraryManager.GetMusicGenres(query); - - var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes); - return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); - } - /// <summary> /// Gets a music genre, by name. /// </summary> diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index e180d0cd7a..f0270e9935 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -260,6 +260,7 @@ namespace Jellyfin.Server.Extensions c.AddSwaggerTypeMappings(); c.OperationFilter<FileResponseFilter>(); + c.OperationFilter<ObsoleteRoutesFilter>(); c.DocumentFilter<WebsocketModelFilter>(); }); } diff --git a/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs b/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs new file mode 100644 index 0000000000..34cd72752a --- /dev/null +++ b/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs @@ -0,0 +1,22 @@ +using System; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Jellyfin.Server.Filters +{ + /// <inheritdoc /> + public class ObsoleteRoutesFilter : IOperationFilter + { + /// <inheritdoc /> + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor actionDescriptor + && !string.IsNullOrEmpty(actionDescriptor.AttributeRouteInfo.Name) + && actionDescriptor.AttributeRouteInfo.Name.EndsWith("deprecated", StringComparison.OrdinalIgnoreCase)) + { + operation.Deprecated = true; + } + } + } +} From de52c8a497c288b8f7a807df806530a099b5ab0e Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Fri, 6 Nov 2020 09:35:23 +0100 Subject: [PATCH 0214/1930] Revert "Make /MusicGenres obsolete" --- Jellyfin.Api/Controllers/GenresController.cs | 1 - .../Controllers/MusicGenresController.cs | 82 +++++++++++++++++++ .../ApiServiceCollectionExtensions.cs | 1 - .../Filters/ObsoleteRoutesFilter.cs | 22 ----- 4 files changed, 82 insertions(+), 24 deletions(-) delete mode 100644 Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 94c1b4b9ee..4e47658b06 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -66,7 +66,6 @@ namespace Jellyfin.Api.Controllers /// <response code="200">Genres returned.</response> /// <returns>An <see cref="OkResult"/> containing the queryresult of genres.</returns> [HttpGet] - [HttpGet("/MusicGenres", Name = "GetMusicGenres-Deprecated")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetGenres( [FromQuery] int? startIndex, diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 28295f0cbf..24075b9052 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -44,6 +44,88 @@ namespace Jellyfin.Api.Controllers _dtoService = dtoService; } + /// <summary> + /// Gets all music genres from a given item, folder, or the entire library. + /// </summary> + /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> + /// <param name="limit">Optional. The maximum number of records to return.</param> + /// <param name="searchTerm">The search term.</param> + /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> + /// <param name="excludeItemTypes">Optional. If specified, results will be filtered out based on item type. This allows multiple, comma delimited.</param> + /// <param name="includeItemTypes">Optional. If specified, results will be filtered in based on item type. This allows multiple, comma delimited.</param> + /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param> + /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> + /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> + /// <param name="userId">User id.</param> + /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param> + /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param> + /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param> + /// <param name="enableImages">Optional, include image information in output.</param> + /// <param name="enableTotalRecordCount">Optional. Include total record count.</param> + /// <response code="200">Music genres returned.</response> + /// <returns>An <see cref="OkResult"/> containing the queryresult of music genres.</returns> + [HttpGet] + public ActionResult<QueryResult<BaseItemDto>> GetMusicGenres( + [FromQuery] int? startIndex, + [FromQuery] int? limit, + [FromQuery] string? searchTerm, + [FromQuery] string? parentId, + [FromQuery] string? fields, + [FromQuery] string? excludeItemTypes, + [FromQuery] string? includeItemTypes, + [FromQuery] bool? isFavorite, + [FromQuery] int? imageTypeLimit, + [FromQuery] ImageType[] enableImageTypes, + [FromQuery] Guid? userId, + [FromQuery] string? nameStartsWithOrGreater, + [FromQuery] string? nameStartsWith, + [FromQuery] string? nameLessThan, + [FromQuery] bool? enableImages = true, + [FromQuery] bool enableTotalRecordCount = true) + { + var dtoOptions = new DtoOptions() + .AddItemFields(fields) + .AddClientFields(Request) + .AddAdditionalDtoOptions(enableImages, false, imageTypeLimit, enableImageTypes); + + User? user = userId.HasValue && userId != Guid.Empty ? _userManager.GetUserById(userId.Value) : null; + + var parentItem = _libraryManager.GetParentItem(parentId, userId); + + var query = new InternalItemsQuery(user) + { + ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), + IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), + StartIndex = startIndex, + Limit = limit, + IsFavorite = isFavorite, + NameLessThan = nameLessThan, + NameStartsWith = nameStartsWith, + NameStartsWithOrGreater = nameStartsWithOrGreater, + DtoOptions = dtoOptions, + SearchTerm = searchTerm, + EnableTotalRecordCount = enableTotalRecordCount + }; + + if (!string.IsNullOrWhiteSpace(parentId)) + { + if (parentItem is Folder) + { + query.AncestorIds = new[] { new Guid(parentId) }; + } + else + { + query.ItemIds = new[] { new Guid(parentId) }; + } + } + + var result = _libraryManager.GetMusicGenres(query); + + var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes); + return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); + } + /// <summary> /// Gets a music genre, by name. /// </summary> diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index f0270e9935..e180d0cd7a 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -260,7 +260,6 @@ namespace Jellyfin.Server.Extensions c.AddSwaggerTypeMappings(); c.OperationFilter<FileResponseFilter>(); - c.OperationFilter<ObsoleteRoutesFilter>(); c.DocumentFilter<WebsocketModelFilter>(); }); } diff --git a/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs b/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs deleted file mode 100644 index 34cd72752a..0000000000 --- a/Jellyfin.Server/Filters/ObsoleteRoutesFilter.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Jellyfin.Server.Filters -{ - /// <inheritdoc /> - public class ObsoleteRoutesFilter : IOperationFilter - { - /// <inheritdoc /> - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor actionDescriptor - && !string.IsNullOrEmpty(actionDescriptor.AttributeRouteInfo.Name) - && actionDescriptor.AttributeRouteInfo.Name.EndsWith("deprecated", StringComparison.OrdinalIgnoreCase)) - { - operation.Deprecated = true; - } - } - } -} From b693c52fe7f2fda6ea009c3ee8c032189369d896 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Fri, 6 Nov 2020 09:42:59 +0100 Subject: [PATCH 0215/1930] Make /MusicGenres obsolete --- Jellyfin.Api/Controllers/MusicGenresController.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 24075b9052..e105befe8e 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -66,6 +66,7 @@ namespace Jellyfin.Api.Controllers /// <response code="200">Music genres returned.</response> /// <returns>An <see cref="OkResult"/> containing the queryresult of music genres.</returns> [HttpGet] + [Obsolete("Use GetGenres instead")] public ActionResult<QueryResult<BaseItemDto>> GetMusicGenres( [FromQuery] int? startIndex, [FromQuery] int? limit, From e96e480f01632ef785e7ead3cde908e57aba738c Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Fri, 6 Nov 2020 15:52:01 +0100 Subject: [PATCH 0216/1930] Add comment with match cases for weir EpisodeExpression and named group for some date EpisodeExpressions --- Emby.Naming/Common/NamingOptions.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index a1b95954ec..4325cf2369 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -246,7 +246,7 @@ namespace Emby.Naming.Common }, // <!-- foo.ep01, foo.EP_01 --> new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"), - new EpisodeExpression("([0-9]{4})[\\.-]([0-9]{2})[\\.-]([0-9]{2})", true) + new EpisodeExpression("(?<year>[0-9]{4})[\\.-](?<month>[0-9]{2})[\\.-](?<day>[0-9]{2})", true) { DateTimeFormats = new[] { @@ -255,7 +255,7 @@ namespace Emby.Naming.Common "yyyy_MM_dd" } }, - new EpisodeExpression("([0-9]{2})[\\.-]([0-9]{2})[\\.-]([0-9]{4})", true) + new EpisodeExpression(@"(?<day>[0-9]{2})[.-](?<month>[0-9]{2})[.-](?<year>[0-9]{4})", true) { DateTimeFormats = new[] { @@ -277,6 +277,11 @@ namespace Emby.Naming.Common { SupportsAbsoluteEpisodeNumbers = true }, + + // Case Closed (1996-2007)/Case Closed - 317.mkv + // /server/anything_102.mp4 + // /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv + // /server/anything_1996.11.14.mp4 new EpisodeExpression(@"[\\\\/\\._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/])*)[\\\\/\\._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([\\._ -][^\\\\/]*)$") { IsOptimistic = true, From b21919c7f40770c909a0fc217bf2a326397f84f7 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Fri, 6 Nov 2020 16:15:30 +0100 Subject: [PATCH 0217/1930] Minor perf improvements --- Emby.Dlna/ContentDirectory/ControlHandler.cs | 4 ++-- Emby.Dlna/Didl/DidlBuilder.cs | 2 +- Emby.Dlna/DlnaManager.cs | 6 +++--- Emby.Dlna/Eventing/DlnaEventManager.cs | 2 +- Emby.Dlna/Main/DlnaEntryPoint.cs | 4 ++-- Emby.Dlna/PlayTo/PlayToController.cs | 4 ++-- Emby.Notifications/NotificationEntryPoint.cs | 5 ++++- .../Channels/ChannelManager.cs | 17 ++++++---------- .../Controllers/InstantMixController.cs | 4 ++-- .../Controllers/UniversalAudioController.cs | 20 +++++++++++-------- Jellyfin.Api/Helpers/SimilarItemsHelper.cs | 4 ++-- .../IServerApplicationHost.cs | 9 +++++---- 12 files changed, 42 insertions(+), 39 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 2991861129..5f25b8cdc0 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1346,8 +1346,8 @@ namespace Emby.Dlna.ContentDirectory { if (id.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase)) { - stubType = (StubType)Enum.Parse(typeof(StubType), name, true); - id = id.Split(new[] { '_' }, 2)[1]; + stubType = Enum.Parse<StubType>(name, true); + id = id.Split('_', 2)[1]; break; } diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 5b8a89d8f3..abaf522bca 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -123,7 +123,7 @@ namespace Emby.Dlna.Didl { foreach (var att in profile.XmlRootAttributes) { - var parts = att.Name.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); + var parts = att.Name.Split(':', StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { writer.WriteAttributeString(parts[0], parts[1], null, att.Value); diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 1807ac6a13..069400833e 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -383,9 +383,9 @@ namespace Emby.Dlna continue; } - var filename = Path.GetFileName(name).Substring(namespaceName.Length); - - var path = Path.Combine(systemProfilesPath, filename); + var path = Path.Join( + systemProfilesPath, + Path.GetFileName(name.AsSpan()).Slice(namespaceName.Length)); using (var stream = _assembly.GetManifestResourceStream(name)) { diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs index 7d8da86ef9..770d56c30f 100644 --- a/Emby.Dlna/Eventing/DlnaEventManager.cs +++ b/Emby.Dlna/Eventing/DlnaEventManager.cs @@ -168,7 +168,7 @@ namespace Emby.Dlna.Eventing builder.Append("</e:propertyset>"); - using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl); + using var options = new HttpRequestMessage(new HttpMethod("NOTIFY"), subscription.CallbackUrl); options.Content = new StringContent(builder.ToString(), Encoding.UTF8, MediaTypeNames.Text.Xml); options.Headers.TryAddWithoutValidation("NT", subscription.NotificationType); options.Headers.TryAddWithoutValidation("NTS", "upnp:propchange"); diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 40c2cc0e0a..f8a00efaca 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -257,9 +257,10 @@ namespace Emby.Dlna.Main private async Task RegisterServerEndpoints() { - var addresses = await _appHost.GetLocalIpAddresses(CancellationToken.None).ConfigureAwait(false); + var addresses = await _appHost.GetLocalIpAddresses().ConfigureAwait(false); var udn = CreateUuid(_appHost.SystemId); + var descriptorUri = "/dlna/" + udn + "/description.xml"; foreach (var address in addresses) { @@ -279,7 +280,6 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); - var descriptorUri = "/dlna/" + udn + "/description.xml"; var uri = new Uri(_appHost.GetLocalApiUrl(address) + descriptorUri); var device = new SsdpRootDevice diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index a5b8e2b3ce..c07c8aefa6 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -326,7 +326,7 @@ namespace Emby.Dlna.PlayTo public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken) { - _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); + _logger.LogDebug("{0} - Received PlayRequest: {1}", _session.DeviceName, command.PlayCommand); var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId); @@ -339,7 +339,7 @@ namespace Emby.Dlna.PlayTo var startIndex = command.StartIndex ?? 0; if (startIndex > 0) { - items = items.Skip(startIndex).ToList(); + items = items.GetRange(startIndex, items.Count - startIndex); } var playlist = new List<PlaylistItem>(); diff --git a/Emby.Notifications/NotificationEntryPoint.cs b/Emby.Notifications/NotificationEntryPoint.cs index ded22d26cc..7116d52b11 100644 --- a/Emby.Notifications/NotificationEntryPoint.cs +++ b/Emby.Notifications/NotificationEntryPoint.cs @@ -209,7 +209,10 @@ namespace Emby.Notifications _libraryUpdateTimer = null; } - items = items.Take(10).ToList(); + if (items.Count > 10) + { + items = items.GetRange(0, 10); + } foreach (var item in items) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index db44bf4898..19045b72b4 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -250,21 +250,16 @@ namespace Emby.Server.Implementations.Channels var all = channels; var totalCount = all.Count; - if (query.StartIndex.HasValue) + if (query.StartIndex.HasValue || query.Limit.HasValue) { - all = all.Skip(query.StartIndex.Value).ToList(); + int startIndex = query.StartIndex ?? 0; + int count = query.Limit == null ? totalCount - startIndex : Math.Min(query.Limit.Value, totalCount - startIndex); + all = all.GetRange(startIndex, count); } - if (query.Limit.HasValue) - { - all = all.Take(query.Limit.Value).ToList(); - } - - var returnItems = all.ToArray(); - if (query.RefreshLatestChannelItems) { - foreach (var item in returnItems) + foreach (var item in all) { RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).GetAwaiter().GetResult(); } @@ -272,7 +267,7 @@ namespace Emby.Server.Implementations.Channels return new QueryResult<Channel> { - Items = returnItems, + Items = all, TotalRecordCount = totalCount }; } diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index e6e6b3e70e..7682ceff3e 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -316,9 +316,9 @@ namespace Jellyfin.Api.Controllers TotalRecordCount = list.Count }; - if (limit.HasValue) + if (limit.HasValue && limit > list.Count) { - list = list.Take(limit.Value).ToList(); + list = list.GetRange(0, limit.Value); } var returnList = _dtoService.GetBaseItemDtos(list, dtoOptions, user); diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index a219a74cf8..924ae04778 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -268,20 +268,24 @@ namespace Jellyfin.Api.Controllers { var deviceProfile = new DeviceProfile(); - var directPlayProfiles = new List<DirectPlayProfile>(); - var containers = RequestHelpers.Split(container, ',', true); - - foreach (var cont in containers) + int len = containers.Length; + var directPlayProfiles = new DirectPlayProfile[len]; + for (int i = 0; i < len; i++) { - var parts = RequestHelpers.Split(cont, '|', true); + var parts = RequestHelpers.Split(containers[i], '|', true); - var audioCodecs = parts.Length == 1 ? null : string.Join(",", parts.Skip(1).ToArray()); + var audioCodecs = parts.Length == 1 ? null : string.Join(',', parts.Skip(1)); - directPlayProfiles.Add(new DirectPlayProfile { Type = DlnaProfileType.Audio, Container = parts[0], AudioCodec = audioCodecs }); + directPlayProfiles[i] = new DirectPlayProfile + { + Type = DlnaProfileType.Audio, + Container = parts[0], + AudioCodec = audioCodecs + }; } - deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray(); + deviceProfile.DirectPlayProfiles = directPlayProfiles; deviceProfile.TranscodingProfiles = new[] { diff --git a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs index b922e76cfd..f4b654ef01 100644 --- a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs +++ b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs @@ -50,9 +50,9 @@ namespace Jellyfin.Api.Helpers var returnItems = items; - if (limit.HasValue) + if (limit.HasValue && limit > returnItems.Count) { - returnItems = returnItems.Take(limit.Value).ToList(); + returnItems = returnItems.GetRange(0, limit.Value); } var dtos = dtoService.GetBaseItemDtos(returnItems, dtoOptions, user); diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index cfad17fb72..649b0eaec8 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -56,10 +56,11 @@ namespace MediaBrowser.Controller /// <summary> /// Gets the system info. /// </summary> + /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param> /// <returns>SystemInfo.</returns> - Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken); + Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken = default); - Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken); + Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken = default); /// <summary> /// Gets all the local IP addresses of this API instance. Each address is validated by sending a 'ping' request @@ -67,7 +68,7 @@ namespace MediaBrowser.Controller /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param> /// <returns>A list containing all the local IP addresses of the server.</returns> - Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken); + Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken = default); /// <summary> /// Gets a local (LAN) URL that can be used to access the API. The hostname used is the first valid configured @@ -75,7 +76,7 @@ namespace MediaBrowser.Controller /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to cancel the task.</param> /// <returns>The server URL.</returns> - Task<string> GetLocalApiUrl(CancellationToken cancellationToken); + Task<string> GetLocalApiUrl(CancellationToken cancellationToken = default); /// <summary> /// Gets a localhost URL that can be used to access the API using the loop-back IP address (127.0.0.1) From e6480066b13d5c1aed73bcec291c3f2f35f26506 Mon Sep 17 00:00:00 2001 From: lelamamalgache <kevnicolwynbay@gmail.com> Date: Fri, 6 Nov 2020 14:43:37 +0000 Subject: [PATCH 0218/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index f4ca8575a1..cc9243f37b 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -113,5 +113,7 @@ "TaskCleanCache": "Vider le répertoire cache", "TasksApplicationCategory": "Application", "TasksLibraryCategory": "Bibliothèque", - "TasksMaintenanceCategory": "Maintenance" + "TasksMaintenanceCategory": "Maintenance", + "TaskCleanActivityLogDescription": "Supprime les entrées du journal d'activité antérieures à l'âge configuré.", + "TaskCleanActivityLog": "Nettoyer le journal d'activité" } From 134fd0d9604ab2108e5008205ede3444aa1a7610 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Fri, 6 Nov 2020 16:39:41 +0100 Subject: [PATCH 0219/1930] > -> < --- Jellyfin.Api/Controllers/InstantMixController.cs | 2 +- Jellyfin.Api/Helpers/SimilarItemsHelper.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index 7682ceff3e..7f8a2be12e 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -316,7 +316,7 @@ namespace Jellyfin.Api.Controllers TotalRecordCount = list.Count }; - if (limit.HasValue && limit > list.Count) + if (limit.HasValue && limit < list.Count) { list = list.GetRange(0, limit.Value); } diff --git a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs index f4b654ef01..6b06f87cd7 100644 --- a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs +++ b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs @@ -50,7 +50,7 @@ namespace Jellyfin.Api.Helpers var returnItems = items; - if (limit.HasValue && limit > returnItems.Count) + if (limit.HasValue && limit < returnItems.Count) { returnItems = returnItems.GetRange(0, limit.Value); } From ca40eff83dd9b7e186574e70f05775f744b821df Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 6 Nov 2020 12:00:00 -0500 Subject: [PATCH 0220/1930] Restore missing targetFolder --- .ci/azure-pipelines-package.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 67aac45c9d..852594e67c 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -63,6 +63,7 @@ jobs: sshEndpoint: repository sourceFolder: '$(Build.SourcesDirectory)/deployment/dist' contents: '**' + targetFolder: '/srv/repository/incoming/azure/$(Build.BuildNumber)/$(BuildConfiguration)' - job: OpenAPISpec dependsOn: Test From e2ab7af0336db05474e1ef2279299763a20a4362 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 6 Nov 2020 12:32:06 -0500 Subject: [PATCH 0221/1930] Remove spurious argument to nohup --- .ci/azure-pipelines-package.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 67aac45c9d..259d71e4ce 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -166,7 +166,7 @@ jobs: inputs: sshEndpoint: repository runOptions: 'commands' - commands: sudo nohup -n /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable & + commands: sudo nohup /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable & - task: SSH@0 displayName: 'Update Stable Repository' @@ -175,7 +175,7 @@ jobs: inputs: sshEndpoint: repository runOptions: 'commands' - commands: sudo nohup -n /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) & + commands: sudo nohup /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) & - job: PublishNuget displayName: 'Publish NuGet packages' From a4e67dac80e932f5f80b3044081e0c18ca8b6d1d Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 6 Nov 2020 13:00:59 -0500 Subject: [PATCH 0222/1930] Reverse order of sudo and nohup Otherwise I'm forced to allow `sudo nohup` globally which is bad news bears. --- .ci/azure-pipelines-package.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 259d71e4ce..326f15b14b 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -166,7 +166,7 @@ jobs: inputs: sshEndpoint: repository runOptions: 'commands' - commands: sudo nohup /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable & + commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) unstable & - task: SSH@0 displayName: 'Update Stable Repository' @@ -175,7 +175,7 @@ jobs: inputs: sshEndpoint: repository runOptions: 'commands' - commands: sudo nohup /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) & + commands: nohup sudo /srv/repository/collect-server.azure.sh /srv/repository/incoming/azure $(Build.BuildNumber) & - job: PublishNuget displayName: 'Publish NuGet packages' From 4a5651e5b2fb8e483cabae4443f327f1cdf70b92 Mon Sep 17 00:00:00 2001 From: JB <ttb0318@nate.com> Date: Fri, 6 Nov 2020 18:52:12 +0000 Subject: [PATCH 0223/1930] Translated using Weblate (Korean) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ko/ --- Emby.Server.Implementations/Localization/Core/ko.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ko.json b/Emby.Server.Implementations/Localization/Core/ko.json index fb01e46451..2857461794 100644 --- a/Emby.Server.Implementations/Localization/Core/ko.json +++ b/Emby.Server.Implementations/Localization/Core/ko.json @@ -113,5 +113,7 @@ "TaskCleanCacheDescription": "시스템에서 더 이상 필요하지 않은 캐시 파일을 삭제합니다.", "TaskCleanCache": "캐시 폴더 청소", "TasksChannelsCategory": "인터넷 채널", - "TasksLibraryCategory": "라이브러리" + "TasksLibraryCategory": "라이브러리", + "TaskCleanActivityLogDescription": "구성된 기간보다 오래된 활동내역 삭제", + "TaskCleanActivityLog": "활동내역청소" } From fed37630db75327eee3ded3b200f105017e6de6c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 6 Nov 2020 13:00:14 -0700 Subject: [PATCH 0224/1930] Add x-jellyfin-version to openapi spec --- .../ApiServiceCollectionExtensions.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index e180d0cd7a..cc98955df7 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Net; using System.Reflection; +using Emby.Server.Implementations; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.DefaultAuthorizationPolicy; using Jellyfin.Api.Auth.DownloadPolicy; @@ -27,6 +28,8 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; @@ -209,7 +212,19 @@ namespace Jellyfin.Server.Extensions { return serviceCollection.AddSwaggerGen(c => { - c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", Version = "v1" }); + c.SwaggerDoc("api-docs", new OpenApiInfo + { + Title = "Jellyfin API", + Version = "v1", + Extensions = new Dictionary<string, IOpenApiExtension> + { + { + "x-jellyfin-version", + new OpenApiString(typeof(ApplicationHost).Assembly.GetName().Version?.ToString()) + } + } + }); + c.AddSecurityDefinition(AuthenticationSchemes.CustomAuthentication, new OpenApiSecurityScheme { Type = SecuritySchemeType.ApiKey, From 68f8ff678a08c4efcf125932962f130f2e9235b8 Mon Sep 17 00:00:00 2001 From: JB <ttb0318@nate.com> Date: Fri, 6 Nov 2020 20:01:39 +0000 Subject: [PATCH 0225/1930] Translated using Weblate (Korean) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ko/ --- Emby.Server.Implementations/Localization/Core/ko.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ko.json b/Emby.Server.Implementations/Localization/Core/ko.json index 2857461794..b8b39833c8 100644 --- a/Emby.Server.Implementations/Localization/Core/ko.json +++ b/Emby.Server.Implementations/Localization/Core/ko.json @@ -27,7 +27,7 @@ "HeaderRecordingGroups": "녹화 그룹", "HomeVideos": "홈 비디오", "Inherit": "상속", - "ItemAddedWithName": "{0}가 라이브러리에 추가됨", + "ItemAddedWithName": "{0}가 라이브러리에 추가되었습니다", "ItemRemovedWithName": "{0}가 라이브러리에서 제거됨", "LabelIpAddressValue": "IP 주소: {0}", "LabelRunningTimeValue": "상영 시간: {0}", @@ -114,6 +114,6 @@ "TaskCleanCache": "캐시 폴더 청소", "TasksChannelsCategory": "인터넷 채널", "TasksLibraryCategory": "라이브러리", - "TaskCleanActivityLogDescription": "구성된 기간보다 오래된 활동내역 삭제", + "TaskCleanActivityLogDescription": "구성된 기간보다 오래된 활동내역 삭제.", "TaskCleanActivityLog": "활동내역청소" } From a0699b686851db4fe9865d11eb4c58e72592883e Mon Sep 17 00:00:00 2001 From: Ludovico Besana <ludovicobesanaguide@gmail.com> Date: Sat, 7 Nov 2020 01:15:53 +0000 Subject: [PATCH 0226/1930] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 0a6238578d..9e37ddc27c 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Canali su Internet", "TasksApplicationCategory": "Applicazione", "TasksLibraryCategory": "Libreria", - "TasksMaintenanceCategory": "Manutenzione" + "TasksMaintenanceCategory": "Manutenzione", + "TaskCleanActivityLog": "Attività di Registro Completate", + "TaskCleanActivityLogDescription": "Elimina gli inserimenti nel registro delle attività più vecchie dell’età configurata." } From 03d5a3d8e76154b2368a0e08c4a89b807eb05b8f Mon Sep 17 00:00:00 2001 From: tomwaits00 <bgns.5@hotmail.com> Date: Sat, 7 Nov 2020 01:46:48 +0000 Subject: [PATCH 0227/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 1e5f2cf198..818b57c7f6 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -8,7 +8,7 @@ "CameraImageUploadedFrom": "{0} 'den yeni bir kamera resmi yüklendi", "Channels": "Kanallar", "ChapterNameValue": "Bölüm {0}", - "Collections": "Koleksiyonlar", + "Collections": "Koleksiyon", "DeviceOfflineWithName": "{0} bağlantısı kesildi", "DeviceOnlineWithName": "{0} bağlı", "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu", @@ -23,7 +23,7 @@ "HeaderFavoriteShows": "Favori Diziler", "HeaderFavoriteSongs": "Favori Şarkılar", "HeaderLiveTV": "Canlı TV", - "HeaderNextUp": "Sonraki hafta", + "HeaderNextUp": "Gelecek Hafta", "HeaderRecordingGroups": "Kayıt Grupları", "HomeVideos": "Ev videoları", "Inherit": "Devral", @@ -113,5 +113,6 @@ "TaskRefreshLibrary": "Medya Kütüphanesini Tara", "TaskRefreshChapterImagesDescription": "Sahnelere ayrılmış videolar için küçük resimler oluştur.", "TaskRefreshChapterImages": "Bölüm Resimlerini Çıkar", - "TaskCleanCacheDescription": "Sistem tarafından artık ihtiyaç duyulmayan önbellek dosyalarını siler." + "TaskCleanCacheDescription": "Sistem tarafından artık ihtiyaç duyulmayan önbellek dosyalarını siler.", + "TaskCleanActivityLog": "İşlem Günlüğünü Temizle" } From 549d0bc27b4194a0508d29ee5c81ff551cd069a5 Mon Sep 17 00:00:00 2001 From: Florian Schmidt <florianschmidt@gmx.net> Date: Sat, 7 Nov 2020 07:53:50 +0000 Subject: [PATCH 0228/1930] Translated using Weblate (German) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/de/ --- Emby.Server.Implementations/Localization/Core/de.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json index 97ad1694a6..c81de8218f 100644 --- a/Emby.Server.Implementations/Localization/Core/de.json +++ b/Emby.Server.Implementations/Localization/Core/de.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Internet Kanäle", "TasksApplicationCategory": "Anwendung", "TasksLibraryCategory": "Bibliothek", - "TasksMaintenanceCategory": "Wartung" + "TasksMaintenanceCategory": "Wartung", + "TaskCleanActivityLogDescription": "Löscht Aktivitätsprotokolleinträge, die älter als das konfigurierte Alter sind.", + "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen" } From 6b5ba0f64ad20f7395afdb4504a8284c7a214550 Mon Sep 17 00:00:00 2001 From: Nikita Epifanov <nikgreens@protonmail.com> Date: Sat, 7 Nov 2020 07:23:08 +0000 Subject: [PATCH 0229/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index 95b93afb82..c0db2cf7f5 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -113,5 +113,7 @@ "TaskCleanLogsDescription": "Удаляются файлы журнала, возраст которых превышает {0} дн(я/ей).", "TaskRefreshLibraryDescription": "Сканируется медиатека на новые файлы и обновляются метаданные.", "TaskRefreshChapterImagesDescription": "Создаются эскизы для видео, которые содержат сцены.", - "TaskCleanCacheDescription": "Удаляются файлы кэша, которые больше не нужны системе." + "TaskCleanCacheDescription": "Удаляются файлы кэша, которые больше не нужны системе.", + "TaskCleanActivityLogDescription": "Удаляет записи журнала активности старше установленного возраста.", + "TaskCleanActivityLog": "Очистить журнал активности" } From f22e0800e272b9f0aac198243a44196421af5dff Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Sat, 7 Nov 2020 11:02:12 +0100 Subject: [PATCH 0230/1930] Episode parsing coverage --- Emby.Naming/Common/NamingOptions.cs | 2 +- Emby.Naming/TV/EpisodePathParser.cs | 7 +- .../TV/EpisodePathParserTest.cs | 99 ++++++++++++++----- 3 files changed, 77 insertions(+), 31 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 4325cf2369..471491d22c 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -282,7 +282,7 @@ namespace Emby.Naming.Common // /server/anything_102.mp4 // /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv // /server/anything_1996.11.14.mp4 - new EpisodeExpression(@"[\\\\/\\._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/])*)[\\\\/\\._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\\.[1-9])(?![0-9]))?)([\\._ -][^\\\\/]*)$") + new EpisodeExpression(@"[\\/._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/_])*)[\\\/._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\.[1-9])(?![0-9]))?)([._ -][^\\\/]*)$") { IsOptimistic = true, IsNamed = true, diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index 866d8adc00..d9cc8172bd 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -186,7 +186,7 @@ namespace Emby.Naming.TV private void FillAdditional(string path, EpisodePathParserResult info) { - var expressions = _options.MultipleEpisodeExpressions.ToList(); + var expressions = _options.MultipleEpisodeExpressions.Where(i => i.IsNamed).ToList(); if (string.IsNullOrEmpty(info.SeriesName)) { @@ -200,11 +200,6 @@ namespace Emby.Naming.TV { foreach (var i in expressions) { - if (!i.IsNamed) - { - continue; - } - var result = Parse(path, i); if (!result.Success) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs index 03aeb7f76b..57f382b382 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs @@ -1,4 +1,4 @@ -using Emby.Naming.Common; +using Emby.Naming.Common; using Emby.Naming.TV; using Xunit; @@ -7,43 +7,94 @@ namespace Jellyfin.Naming.Tests.TV public class EpisodePathParserTest { [Theory] - [InlineData("/media/Foo/Foo-S01E01", "Foo", 1, 1)] - [InlineData("/media/Foo - S04E011", "Foo", 4, 11)] - [InlineData("/media/Foo/Foo s01x01", "Foo", 1, 1)] - [InlineData("/media/Foo (2019)/Season 4/Foo (2019).S04E03", "Foo (2019)", 4, 3)] - [InlineData("D:\\media\\Foo\\Foo-S01E01", "Foo", 1, 1)] - [InlineData("D:\\media\\Foo - S04E011", "Foo", 4, 11)] - [InlineData("D:\\media\\Foo\\Foo s01x01", "Foo", 1, 1)] - [InlineData("D:\\media\\Foo (2019)\\Season 4\\Foo (2019).S04E03", "Foo (2019)", 4, 3)] - [InlineData("/Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", "Elementary", 2, 3)] - [InlineData("/Season 1/seriesname S01E02 blah.avi", "seriesname", 1, 2)] - [InlineData("/Running Man/Running Man S2017E368.mkv", "Running Man", 2017, 368)] - [InlineData("/Season 1/seriesname 01x02 blah.avi", "seriesname", 1, 2)] - [InlineData("/Season 25/The Simpsons.S25E09.Steal this episode.mp4", "The Simpsons", 25, 9)] - [InlineData("/Season 1/seriesname S01x02 blah.avi", "seriesname", 1, 2)] - [InlineData("/Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", "Elementary", 2, 3)] - [InlineData("/Season 1/seriesname S01xE02 blah.avi", "seriesname", 1, 2)] - [InlineData("/Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", "Elementary", 2, 3)] - [InlineData("/Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", "Elementary", 2, 3)] - [InlineData("/Season 02/Elementary - 02x03-E15 - Ep Name.mp4", "Elementary", 2, 3)] - [InlineData("/Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", "Elementary", 1, 23)] - [InlineData("/The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", "The Wonder Years", 4, 7)] + [InlineData("/media/Foo/Foo-S01E01", true, "Foo", 1, 1)] + [InlineData("/media/Foo - S04E011", true, "Foo", 4, 11)] + [InlineData("/media/Foo/Foo s01x01", true, "Foo", 1, 1)] + [InlineData("/media/Foo (2019)/Season 4/Foo (2019).S04E03", true, "Foo (2019)", 4, 3)] + [InlineData("D:\\media\\Foo\\Foo-S01E01", true, "Foo", 1, 1)] + [InlineData("D:\\media\\Foo - S04E011", true, "Foo", 4, 11)] + [InlineData("D:\\media\\Foo\\Foo s01x01", true, "Foo", 1, 1)] + [InlineData("D:\\media\\Foo (2019)\\Season 4\\Foo (2019).S04E03", true, "Foo (2019)", 4, 3)] + [InlineData("/Season 2/Elementary - 02x03-04-15 - Ep Name.mp4", false, "Elementary", 2, 3)] + [InlineData("/Season 1/seriesname S01E02 blah.avi", false, "seriesname", 1, 2)] + [InlineData("/Running Man/Running Man S2017E368.mkv", false, "Running Man", 2017, 368)] + [InlineData("/Season 1/seriesname 01x02 blah.avi", false, "seriesname", 1, 2)] + [InlineData("/Season 25/The Simpsons.S25E09.Steal this episode.mp4", false, "The Simpsons", 25, 9)] + [InlineData("/Season 1/seriesname S01x02 blah.avi", false, "seriesname", 1, 2)] + [InlineData("/Season 2/Elementary - 02x03 - 02x04 - 02x15 - Ep Name.mp4", false, "Elementary", 2, 3)] + [InlineData("/Season 1/seriesname S01xE02 blah.avi", false, "seriesname", 1, 2)] + [InlineData("/Season 02/Elementary - 02x03 - x04 - x15 - Ep Name.mp4", false, "Elementary", 2, 3)] + [InlineData("/Season 02/Elementary - 02x03x04x15 - Ep Name.mp4", false, "Elementary", 2, 3)] + [InlineData("/Season 02/Elementary - 02x03-E15 - Ep Name.mp4", false, "Elementary", 2, 3)] + [InlineData("/Season 1/Elementary - S01E23-E24-E26 - The Woman.mp4", false, "Elementary", 1, 23)] + [InlineData("/The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", false, "The Wonder Years", 4, 7)] // TODO: [InlineData("/Castle Rock 2x01 Que el rio siga su curso [WEB-DL HULU 1080p h264 Dual DD5.1 Subs].mkv", "Castle Rock", 2, 1)] // TODO: [InlineData("/After Life 1x06 Episodio 6 [WEB-DL NF 1080p h264 Dual DD 5.1 Sub].mkv", "After Life", 1, 6)] // TODO: [InlineData("/Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", "Uchuu Senkan Yamoto 2199", 4, 3)] // TODO: [InlineData("The Daily Show/The Daily Show 25x22 - [WEBDL-720p][AAC 2.0][x264] Noah Baumbach-TBS.mkv", "The Daily Show", 25, 22)] // TODO: [InlineData("Watchmen (2019)/Watchmen 1x03 [WEBDL-720p][EAC3 5.1][h264][-TBS] - She Was Killed by Space Junk.mkv", "Watchmen (2019)", 1, 3)] // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", "The Legend of Condor Heroes 2017", 1, 7)] - public void ParseEpisodesCorrectly(string path, string name, int season, int episode) + public void ParseEpisodesCorrectly(string path, bool isDirectory, string name, int season, int episode) { NamingOptions o = new NamingOptions(); EpisodePathParser p = new EpisodePathParser(o); - var res = p.Parse(path, false); + var res = p.Parse(path, isDirectory); Assert.True(res.Success); Assert.Equal(name, res.SeriesName); Assert.Equal(season, res.SeasonNumber); Assert.Equal(episode, res.EpisodeNumber); } + + [Theory] + [InlineData("/test/01-03.avi", true, true)] + public void EpisodePathParserTest_DifferentExpressionsParameters(string path, bool? isNamed, bool? isOptimistic) + { + NamingOptions o = new NamingOptions(); + EpisodePathParser p = new EpisodePathParser(o); + var res = p.Parse(path, false, isNamed, isOptimistic); + + Assert.True(res.Success); + } + + [Fact] + public void EpisodePathParserTest_FalsePositivePixelRate() + { + NamingOptions o = new NamingOptions(); + EpisodePathParser p = new EpisodePathParser(o); + var res = p.Parse("Series Special (1920x1080).mkv", false); + + Assert.False(res.Success); + } + + [Fact] + public void EpisodeResolverTest_WrongExtension() + { + var res = new EpisodeResolver(new NamingOptions()).Resolve("test.mp3", false); + Assert.Null(res); + } + + [Fact] + public void EpisodeResolverTest_WrongExtensionStub() + { + var res = new EpisodeResolver(new NamingOptions()).Resolve("dvd.disc", false); + Assert.NotNull(res); + Assert.True(res!.IsStub); + } + + [Fact] + public void EpisodePathParserTest_EmptyDateParsers() + { + NamingOptions o = new NamingOptions() + { + EpisodeExpressions = new[] { new EpisodeExpression("(([0-9]{4})-([0-9]{2})-([0-9]{2}) [0-9]{2}:[0-9]{2}:[0-9]{2})", true) } + }; + o.Compile(); + + EpisodePathParser p = new EpisodePathParser(o); + var res = p.Parse("ABC_2019_10_21 11:00:00", false); + + Assert.True(res.Success); + } } } From 3d1076ae42433314835f4277ff42cd5ef1e6c016 Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Sat, 7 Nov 2020 12:30:22 +0100 Subject: [PATCH 0231/1930] Rest of tests for Emby.Naming code coverage --- .../TV/SeasonFolderTests.cs | 38 ++++++++++--------- .../TV/SimpleEpisodeTests.cs | 27 +++++++++++-- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs index 078f940b29..b7b5b54ec8 100644 --- a/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/SeasonFolderTests.cs @@ -1,4 +1,4 @@ -using Emby.Naming.TV; +using Emby.Naming.TV; using Xunit; namespace Jellyfin.Naming.Tests.TV @@ -6,26 +6,30 @@ namespace Jellyfin.Naming.Tests.TV public class SeasonFolderTests { [Theory] - [InlineData(@"/Drive/Season 1", 1)] - [InlineData(@"/Drive/Season 2", 2)] - [InlineData(@"/Drive/Season 02", 2)] - [InlineData(@"/Drive/Seinfeld/S02", 2)] - [InlineData(@"/Drive/Seinfeld/2", 2)] - [InlineData(@"/Drive/Season 2009", 2009)] - [InlineData(@"/Drive/Season1", 1)] - [InlineData(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH", 4)] - [InlineData(@"/Drive/Season 7 (2016)", 7)] - [InlineData(@"/Drive/Staffel 7 (2016)", 7)] - [InlineData(@"/Drive/Stagione 7 (2016)", 7)] - [InlineData(@"/Drive/Season (8)", null)] - [InlineData(@"/Drive/3.Staffel", 3)] - [InlineData(@"/Drive/s06e05", null)] - [InlineData(@"/Drive/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv", null)] - public void GetSeasonNumberFromPathTest(string path, int? seasonNumber) + [InlineData(@"/Drive/Season 1", 1, true)] + [InlineData(@"/Drive/Season 2", 2, true)] + [InlineData(@"/Drive/Season 02", 2, true)] + [InlineData(@"/Drive/Seinfeld/S02", 2, true)] + [InlineData(@"/Drive/Seinfeld/2", 2, true)] + [InlineData(@"/Drive/Season 2009", 2009, true)] + [InlineData(@"/Drive/Season1", 1, true)] + [InlineData(@"The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH", 4, true)] + [InlineData(@"/Drive/Season 7 (2016)", 7, false)] + [InlineData(@"/Drive/Staffel 7 (2016)", 7, false)] + [InlineData(@"/Drive/Stagione 7 (2016)", 7, false)] + [InlineData(@"/Drive/Season (8)", null, false)] + [InlineData(@"/Drive/3.Staffel", 3, false)] + [InlineData(@"/Drive/s06e05", null, false)] + [InlineData(@"/Drive/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv", null, false)] + [InlineData(@"/Drive/extras", 0, true)] + [InlineData(@"/Drive/specials", 0, true)] + public void GetSeasonNumberFromPathTest(string path, int? seasonNumber, bool isSeasonDirectory) { var result = SeasonPathParser.Parse(path, true, true); + Assert.Equal(result.SeasonNumber != null, result.Success); Assert.Equal(result.SeasonNumber, seasonNumber); + Assert.Equal(isSeasonDirectory, result.IsSeasonFolder); } } } diff --git a/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs index 40b41b9f3d..89579c0376 100644 --- a/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/SimpleEpisodeTests.cs @@ -1,4 +1,5 @@ -using Emby.Naming.Common; +using System.IO; +using Emby.Naming.Common; using Emby.Naming.TV; using Xunit; @@ -15,7 +16,6 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("/server/The Walking Dead 4x01.mp4", "The Walking Dead", 4, 1)] [InlineData("/server/the_simpsons-s02e01_18536.mp4", "the_simpsons", 2, 1)] [InlineData("/server/Temp/S01E02 foo.mp4", "", 1, 2)] - [InlineData("Series/4-12 - The Woman.mp4", "", 4, 12)] [InlineData("Series/4x12 - The Woman.mp4", "", 4, 12)] [InlineData("Series/LA X, Pt. 1_s06e32.mp4", "LA X, Pt. 1", 6, 32)] [InlineData("[Baz-Bar]Foo - [1080p][Multiple Subtitle]/[Baz-Bar] Foo - 05 [1080p][Multiple Subtitle].mkv", "Foo", null, 5)] @@ -24,16 +24,37 @@ namespace Jellyfin.Naming.Tests.TV // TODO: [InlineData("[Baz-Bar]Foo - 01 - 12[1080p][Multiple Subtitle]/[Baz-Bar] Foo - 05 [1080p][Multiple Subtitle].mkv", "Foo", null, 5)] // TODO: [InlineData("E:\\Anime\\Yahari Ore no Seishun Love Comedy wa Machigatteiru\\Yahari Ore no Seishun Love Comedy wa Machigatteiru. Zoku\\Oregairu Zoku 11 - Hayama Hayato Always Renconds to Everyone's Expectations..mkv", "Yahari Ore no Seishun Love Comedy wa Machigatteiru", null, 11)] // TODO: [InlineData(@"/Library/Series/The Grand Tour (2016)/Season 1/S01E01 The Holy Trinity.mkv", "The Grand Tour", 1, 1)] - public void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber) + public void TestSimple(string path, string seriesName, int? seasonNumber, int? episodeNumber) + { + Test(path, seriesName, seasonNumber, episodeNumber, null); + } + + [Theory] + [InlineData("Series/4-12 - The Woman.mp4", "", 4, 12, 12)] + public void TestWithPossibleEpisodeEnd(string path, string seriesName, int? seasonNumber, int? episodeNumber, int? episodeEndNumber) + { + Test(path, seriesName, seasonNumber, episodeNumber, episodeEndNumber); + } + + private void Test(string path, string seriesName, int? seasonNumber, int? episodeNumber, int? episodeEndNumber) { var options = new NamingOptions(); var result = new EpisodeResolver(options) .Resolve(path, false); + Assert.NotNull(result); Assert.Equal(seasonNumber, result?.SeasonNumber); Assert.Equal(episodeNumber, result?.EpisodeNumber); Assert.Equal(seriesName, result?.SeriesName, true); + Assert.Equal(path, result?.Path); + Assert.Equal(Path.GetExtension(path).Substring(1), result?.Container); + Assert.Null(result?.Format3D); + Assert.False(result?.Is3D); + Assert.False(result?.IsStub); + Assert.Null(result?.StubType); + Assert.Equal(episodeEndNumber, result?.EndingEpisodeNumber); + Assert.False(result?.IsByDate); } } } From 85965741f57e709133fbaf5ba59ed45bbd3b5d26 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 8 Nov 2020 01:39:32 +0800 Subject: [PATCH 0232/1930] add initial support for HEVC over FMP4-HLS --- .../Controllers/DynamicHlsController.cs | 76 ++++++- .../Controllers/UniversalAudioController.cs | 7 +- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 198 ++++++++++++++++-- Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs | 29 ++- .../MediaEncoding/EncodingHelper.cs | 187 +++++++++++------ .../Dlna/ResolutionNormalizer.cs | 1 - 6 files changed, 396 insertions(+), 102 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index e07690e110..1247ef502e 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1136,11 +1136,19 @@ namespace Jellyfin.Api.Controllers var segmentLengths = GetSegmentLengths(state); + var segmentContainer = state.Request.SegmentContainer ?? "ts"; + + // http://ffmpeg.org/ffmpeg-all.html#toc-hls-2 + var isHlsInFmp4 = string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase); + var hlsVersion = isHlsInFmp4 ? "7" : "3"; + var builder = new StringBuilder(); builder.AppendLine("#EXTM3U") .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD") - .AppendLine("#EXT-X-VERSION:3") + .Append("#EXT-X-VERSION:") + .Append(hlsVersion) + .AppendLine() .Append("#EXT-X-TARGETDURATION:") .Append(Math.Ceiling(segmentLengths.Length > 0 ? segmentLengths.Max() : state.SegmentLength)) .AppendLine() @@ -1150,6 +1158,18 @@ namespace Jellyfin.Api.Controllers var segmentExtension = GetSegmentFileExtension(streamingRequest.SegmentContainer); var queryString = Request.QueryString; + if (isHlsInFmp4) + { + builder.Append("#EXT-X-MAP:URI=\"") + .Append("hls1/") + .Append(name) + .Append("/-1") + .Append(segmentExtension) + .Append(queryString) + .Append('"') + .AppendLine(); + } + foreach (var length in segmentLengths) { builder.Append("#EXTINF:") @@ -1232,7 +1252,13 @@ namespace Jellyfin.Api.Controllers var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension); var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength; - if (currentTranscodingIndex == null) + if (segmentId == -1) + { + _logger.LogDebug("Starting transcoding because fmp4 header file is being requested"); + startTranscoding = true; + segmentId = 0; + } + else if (currentTranscodingIndex == null) { _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null"); startTranscoding = true; @@ -1347,13 +1373,24 @@ namespace Jellyfin.Api.Controllers var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); + var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)); + var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); + var outputTsArg = outputPrefix + "%d" + outputExtension; var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) { segmentFormat = "mpegts"; } + else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) + { + var outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\""; + segmentFormat = "fmp4" + outputFmp4HeaderArg; + } + else + { + _logger.LogError("Invalid HLS segment container: " + segmentFormat); + } var maxMuxingQueueSize = encodingOptions.MaxMuxingQueueSize > 128 ? encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture) @@ -1384,7 +1421,7 @@ namespace Jellyfin.Api.Controllers { if (EncodingHelper.IsCopyCodec(audioCodec)) { - return "-acodec copy"; + return "-acodec copy -strict -2"; } var audioTranscodeParams = new List<string>(); @@ -1416,10 +1453,10 @@ namespace Jellyfin.Api.Controllers if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec)) { - return "-codec:a:0 copy -copypriorss:a:0 0"; + return "-codec:a:0 copy -strict -2 -copypriorss:a:0 0"; } - return "-codec:a:0 copy"; + return "-codec:a:0 copy -strict -2"; } var args = "-codec:a:0 " + audioCodec; @@ -1459,6 +1496,15 @@ namespace Jellyfin.Api.Controllers var args = "-codec:v:0 " + codec; + // Prefer hvc1 to hev1 + if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + args += " -tag:v:0 hvc1"; + } + // if (state.EnableMpegtsM2TsMode) // { // args += " -mpegts_m2ts_mode 1"; @@ -1505,18 +1551,32 @@ namespace Jellyfin.Api.Controllers args += " " + _encodingHelper.GetVideoQualityParam(state, codec, encodingOptions, "veryfast"); - // Unable to force key frames using these hw encoders, set key frames by GOP + // Unable to force key frames using these encoders, set key frames by GOP if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)) + || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase)) { args += " " + gopArg; } + else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) + { + args += " " + keyFrameArg; + } else { args += " " + keyFrameArg + gopArg; } + // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now + if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) + { + args += " -bf 0"; + } + // args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0"; var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index e10f1fe912..9820c401af 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -191,8 +191,11 @@ namespace Jellyfin.Api.Controllers if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) { // hls segment container can only be mpegts or fmp4 per ffmpeg documentation + // ffmpeg option -> file extension + // mpegts -> ts + // fmp4 -> mp4 // TODO: remove this when we switch back to the segment muxer - var supportedHlsContainers = new[] { "mpegts", "fmp4" }; + var supportedHlsContainers = new[] { "ts", "mp4" }; var dynamicHlsRequestDto = new HlsAudioRequestDto { @@ -201,7 +204,7 @@ namespace Jellyfin.Api.Controllers Static = isStatic, PlaySessionId = info.PlaySessionId, // fallback to mpegts if device reports some weird value unsupported by hls - SegmentContainer = Array.Exists(supportedHlsContainers, element => element == transcodingContainer) ? transcodingContainer : "mpegts", + SegmentContainer = Array.Exists(supportedHlsContainers, element => element == transcodingContainer) ? transcodingContainer : "ts", MediaSourceId = mediaSourceId, DeviceId = deviceId, AudioCodec = audioCodec, diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index ea012f8376..46c1ddc9f7 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -202,7 +202,61 @@ namespace Jellyfin.Api.Helpers AddSubtitles(state, subtitleStreams, builder, _httpContextAccessor.HttpContext.User); } - AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup); + var basicPlaylist = AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup); + + if (state.VideoStream != null && state.VideoRequest != null) + { + // Provide SDR HEVC entrance for backward compatibility + if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) + && !string.IsNullOrEmpty(state.VideoStream.VideoRange) + && string.Equals(state.VideoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase) + && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + var requestedVideoProfiles = state.GetRequestedProfiles("hevc"); + if (requestedVideoProfiles != null && requestedVideoProfiles.Length > 0) + { + // Force HEVC Main Profile and disable video stream copy + state.OutputVideoCodec = "hevc"; + var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(",", requestedVideoProfiles), "main"); + sdrVideoUrl += "&AllowVideoStreamCopy=false"; + + EncodingHelper encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); + var sdrOutputVideoBitrate = encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec) ?? 0; + var sdrOutputAudioBitrate = encodingHelper.GetAudioBitrateParam(state.VideoRequest.AudioBitRate, state.AudioStream) ?? 0; + var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate; + + AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup); + + // Restore the video codec + state.OutputVideoCodec = "copy"; + } + } + + // Provide Level 5.0 entrance for backward compatibility + // e.g. Apple A10 chips refuse the master playlist containing SDR HEVC Main Level 5.1 video, + // but in fact it is capable of playing videos up to Level 6.1. + if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) + && state.VideoStream.Level.HasValue + && state.VideoStream.Level > 150 + && !string.IsNullOrEmpty(state.VideoStream.VideoRange) + && string.Equals(state.VideoStream.VideoRange, "SDR", StringComparison.OrdinalIgnoreCase) + && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + var playlistCodecsField = new StringBuilder(); + AppendPlaylistCodecsField(playlistCodecsField, state); + + // Force the video level to 5.0 + var originalLevel = state.VideoStream.Level; + state.VideoStream.Level = 150; + var newPlaylistCodecsField = new StringBuilder(); + AppendPlaylistCodecsField(newPlaylistCodecsField, state); + + // Restore the video level + state.VideoStream.Level = originalLevel; + var newPlaylist = ReplacePlaylistCodecsField(basicPlaylist, playlistCodecsField, newPlaylistCodecsField); + builder.Append(newPlaylist); + } + } if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp())) { @@ -212,40 +266,77 @@ namespace Jellyfin.Api.Helpers var variation = GetBitrateVariation(totalBitrate); var newBitrate = totalBitrate - variation; - var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation); + var variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation); AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup); variation *= 2; newBitrate = totalBitrate - variation; - variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation); + variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation); AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup); } return new FileContentResult(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8")); } - private void AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string? subtitleGroup) + private StringBuilder AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string? subtitleGroup) { - builder.Append("#EXT-X-STREAM-INF:BANDWIDTH=") + var playlistBuilder = new StringBuilder(); + playlistBuilder.Append("#EXT-X-STREAM-INF:BANDWIDTH=") .Append(bitrate.ToString(CultureInfo.InvariantCulture)) .Append(",AVERAGE-BANDWIDTH=") .Append(bitrate.ToString(CultureInfo.InvariantCulture)); - AppendPlaylistCodecsField(builder, state); + AppendPlaylistVideoRangeField(playlistBuilder, state); - AppendPlaylistResolutionField(builder, state); + AppendPlaylistCodecsField(playlistBuilder, state); - AppendPlaylistFramerateField(builder, state); + AppendPlaylistResolutionField(playlistBuilder, state); + + AppendPlaylistFramerateField(playlistBuilder, state); if (!string.IsNullOrWhiteSpace(subtitleGroup)) { - builder.Append(",SUBTITLES=\"") + playlistBuilder.Append(",SUBTITLES=\"") .Append(subtitleGroup) .Append('"'); } - builder.Append(Environment.NewLine); - builder.AppendLine(url); + playlistBuilder.Append(Environment.NewLine); + playlistBuilder.AppendLine(url); + builder.Append(playlistBuilder); + + return playlistBuilder; + } + + /// <summary> + /// Appends a VIDEO-RANGE field containing the range of the output video stream. + /// </summary> + /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/> + /// <param name="builder">StringBuilder to append the field to.</param> + /// <param name="state">StreamState of the current stream.</param> + private void AppendPlaylistVideoRangeField(StringBuilder builder, StreamState state) + { + if (state.VideoStream != null && !string.IsNullOrEmpty(state.VideoStream.VideoRange)) + { + var videoRange = state.VideoStream.VideoRange; + if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)) + { + if (string.Equals(videoRange, "SDR", StringComparison.OrdinalIgnoreCase)) + { + builder.Append(",VIDEO-RANGE=SDR"); + } + + if (string.Equals(videoRange, "HDR", StringComparison.OrdinalIgnoreCase)) + { + builder.Append(",VIDEO-RANGE=PQ"); + } + } + else + { + // Currently we only encode to SDR + builder.Append(",VIDEO-RANGE=SDR"); + } + } } /// <summary> @@ -414,25 +505,68 @@ namespace Jellyfin.Api.Helpers /// <returns>H.26X level of the output video stream.</returns> private int? GetOutputVideoCodecLevel(StreamState state) { - string? levelString; + string levelString = string.Empty; if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) + && state.VideoStream != null && state.VideoStream.Level.HasValue) { - levelString = state.VideoStream?.Level.ToString(); + levelString = state.VideoStream.Level.ToString(); } else { - levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec); + if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) + { + levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec) ?? "41"; + levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString); + } + + if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + levelString = state.GetRequestedLevel("h265") ?? state.GetRequestedLevel("hevc") ?? "120"; + levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString); + } } if (int.TryParse(levelString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLevel)) { return parsedLevel; } - return null; } + /// <summary> + /// Get the H.26X profile of the output video stream. + /// </summary> + /// <param name="state">StreamState of the current stream.</param> + /// <param name="codec">Video codec.</param> + /// <returns>H.26X profile of the output video stream.</returns> + private string GetOutputVideoCodecProfile(StreamState state, string codec) + { + string profileString = string.Empty; + if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) + && !string.IsNullOrEmpty(state.VideoStream.Profile)) + { + profileString = state.VideoStream.Profile; + } + else if (!string.IsNullOrEmpty(codec)) + { + profileString = state.GetRequestedProfiles(codec).FirstOrDefault(); + if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) + { + profileString = profileString ?? "high"; + } + + if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + profileString = profileString ?? "main"; + } + } + + return profileString; + } + /// <summary> /// Gets a formatted string of the output audio codec, for use in the CODECS field. /// </summary> @@ -463,6 +597,16 @@ namespace Jellyfin.Api.Helpers return HlsCodecStringHelpers.GetEAC3String(); } + if (string.Equals(state.ActualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)) + { + return HlsCodecStringHelpers.GetFLACString(); + } + + if (string.Equals(state.ActualOutputAudioCodec, "alac", StringComparison.OrdinalIgnoreCase)) + { + return HlsCodecStringHelpers.GetALACString(); + } + return string.Empty; } @@ -487,15 +631,14 @@ namespace Jellyfin.Api.Helpers if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase)) { - string profile = state.GetRequestedProfiles("h264").FirstOrDefault(); + string profile = GetOutputVideoCodecProfile(state, "h264"); return HlsCodecStringHelpers.GetH264String(profile, level); } if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)) { - string profile = state.GetRequestedProfiles("h265").FirstOrDefault(); - + string profile = GetOutputVideoCodecProfile(state, "hevc"); return HlsCodecStringHelpers.GetH265String(profile, level); } @@ -539,12 +682,29 @@ namespace Jellyfin.Api.Helpers return variation; } - private string ReplaceBitrate(string url, int oldValue, int newValue) + private string ReplaceVideoBitrate(string url, int oldValue, int newValue) { return url.Replace( "videobitrate=" + oldValue.ToString(CultureInfo.InvariantCulture), "videobitrate=" + newValue.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase); } + + private string ReplaceProfile(string url, string codec, string oldValue, string newValue) + { + return url.Replace( + codec + "-profile=" + oldValue.ToString(), + codec + "-profile=" + newValue.ToString(), + StringComparison.OrdinalIgnoreCase); + } + + private string ReplacePlaylistCodecsField(StringBuilder playlist, StringBuilder oldValue, StringBuilder newValue) + { + var oldPlaylist = playlist.ToString(); + return oldPlaylist.Replace( + oldValue.ToString(), + newValue.ToString(), + StringComparison.OrdinalIgnoreCase); + } } } diff --git a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs index 95f1906ef0..3d7a9d9a01 100644 --- a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs @@ -85,20 +85,21 @@ namespace Jellyfin.Api.Helpers // The h265 syntax is a bit of a mystery at the time this comment was written. // This is what I've found through various sources: // FORMAT: [codecTag].[profile].[constraint?].L[level * 30].[UNKNOWN] - StringBuilder result = new StringBuilder("hev1", 16); + StringBuilder result = new StringBuilder("hvc1", 16); - if (string.Equals(profile, "main10", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(profile, "main10", StringComparison.OrdinalIgnoreCase) + || string.Equals(profile, "main 10", StringComparison.OrdinalIgnoreCase)) { - result.Append(".2.6"); + result.Append(".2.4"); } else { // Default to main if profile is invalid - result.Append(".1.6"); + result.Append(".1.4"); } result.Append(".L") - .Append(level * 3) + .Append(level) .Append(".B0"); return result.ToString(); @@ -121,5 +122,23 @@ namespace Jellyfin.Api.Helpers { return "mp4a.a6"; } + + /// <summary> + /// Gets an FLAC codec string. + /// </summary> + /// <returns>FLAC codec string.</returns> + public static string GetFLACString() + { + return "fLaC"; + } + + /// <summary> + /// Gets an ALAC codec string. + /// </summary> + /// <returns>ALAC codec string.</returns> + public static string GetALACString() + { + return "alac"; + } } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 5846a603a2..87670e2eb3 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -7,6 +7,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; +using System.Text.RegularExpressions; using System.Threading; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Entities; @@ -23,7 +24,7 @@ namespace MediaBrowser.Controller.MediaEncoding { public class EncodingHelper { - private readonly CultureInfo _usCulture = new CultureInfo("en-US"); + private static readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IMediaEncoder _mediaEncoder; private readonly IFileSystem _fileSystem; @@ -654,16 +655,26 @@ namespace MediaBrowser.Controller.MediaEncoding return string.Empty; } - public string NormalizeTranscodingLevel(string videoCodec, string level) + public static string NormalizeTranscodingLevel(EncodingJobInfo state, string level) { - // Clients may direct play higher than level 41, but there's no reason to transcode higher - if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel) - && requestLevel > 41 - && (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoCodec, "h265", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoCodec, "hevc", StringComparison.OrdinalIgnoreCase))) + if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)) { - return "41"; + if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)) + { + if (requestLevel >= 150) + { + return "150"; + } + } + else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) + { + // Clients may direct play higher than level 41, but there's no reason to transcode higher + if (requestLevel >= 41) + { + return "41"; + } + } } return level; @@ -809,7 +820,8 @@ namespace MediaBrowser.Controller.MediaEncoding param += " -crf " + defaultCrf; } } - else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)) // h264 (h264_qsv) + else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv) + || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv) { string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" }; @@ -825,8 +837,9 @@ namespace MediaBrowser.Controller.MediaEncoding param += " -look_ahead 0"; } else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc) - || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc) { + // following preset will be deprecated in ffmpeg 4.4, use p1~p7 instead switch (encodingOptions.EncoderPreset) { case "veryslow": @@ -856,8 +869,8 @@ namespace MediaBrowser.Controller.MediaEncoding break; } } - else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf) { switch (encodingOptions.EncoderPreset) { @@ -896,6 +909,11 @@ namespace MediaBrowser.Controller.MediaEncoding // Enhance workload when tone mapping with AMF on some APUs param += " -preanalysis true"; } + + if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + param += " -header_insertion_mode gop -gops_per_idr 1"; + } } else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // webm { @@ -945,10 +963,24 @@ namespace MediaBrowser.Controller.MediaEncoding } var targetVideoCodec = state.ActualOutputVideoCodec; + if (string.Equals(targetVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(targetVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + targetVideoCodec = "hevc"; + } var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault(); + profile = Regex.Replace(profile, @"\s+", String.Empty); - // vaapi does not support Baseline profile, force Constrained Baseline in this case, + // only libx264 support encoding H264 High 10 Profile, otherwise force High Profile + if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) + && profile != null + && profile.IndexOf("high 10", StringComparison.OrdinalIgnoreCase) != -1) + { + profile = "high"; + } + + // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case, // which is compatible (and ugly) if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && profile != null @@ -957,6 +989,24 @@ namespace MediaBrowser.Controller.MediaEncoding profile = "constrained_baseline"; } + // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case + if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)) + && profile != null + && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) + { + profile = "baseline"; + } + + // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile + if (!string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase) + && profile != null + && profile.IndexOf("main 10", StringComparison.OrdinalIgnoreCase) != -1) + { + profile = "main"; + } + if (!string.IsNullOrEmpty(profile)) { if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) @@ -971,55 +1021,35 @@ namespace MediaBrowser.Controller.MediaEncoding if (!string.IsNullOrEmpty(level)) { - level = NormalizeTranscodingLevel(state.OutputVideoCodec, level); + level = NormalizeTranscodingLevel(state, level); - // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format - // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307 + // libx264, QSV, AMF, VAAPI can adjust the given level to match the output if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)) { - switch (level) + param += " -level " + level; + } + else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) + { + // hevc_qsv use -level 51 instead of -level 153 + if (double.TryParse(level, NumberStyles.Any, _usCulture, out double hevcLevel)) { - case "30": - param += " -level 3.0"; - break; - case "31": - param += " -level 3.1"; - break; - case "32": - param += " -level 3.2"; - break; - case "40": - param += " -level 4.0"; - break; - case "41": - param += " -level 4.1"; - break; - case "42": - param += " -level 4.2"; - break; - case "50": - param += " -level 5.0"; - break; - case "51": - param += " -level 5.1"; - break; - case "52": - param += " -level 5.2"; - break; - default: - param += " -level " + level; - break; + param += " -level " + hevcLevel / 3; } } + else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + param += " -level " + level; + } else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) { - // nvenc doesn't decode with param -level set ?! - // TODO: + // level option may cause NVENC to fail. + // NVENC cannot adjust the given level, just throw an error. } - else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)) + else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) + || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) { param += " -level " + level; } @@ -1032,7 +1062,11 @@ namespace MediaBrowser.Controller.MediaEncoding if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) { - // todo + // libx265 only accept level option in -x265-params + // level option may cause libx265 to fail + // libx265 cannot adjust the given level, just throw an error + // TODO: set fine tuned params + param += " -x265-params:0 no-info=1"; } if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) @@ -1040,13 +1074,19 @@ namespace MediaBrowser.Controller.MediaEncoding && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) + && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) { param = "-pix_fmt yuv420p " + param; } if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) { var videoStream = state.VideoStream; var isColorDepth10 = IsColorDepth10(state); @@ -1708,7 +1748,8 @@ namespace MediaBrowser.Controller.MediaEncoding } // For QSV, feed it into hardware encoder now - if (isLinux && string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) + if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))) { videoSizeParam += ",hwupload=extra_hw_frames=64"; } @@ -1729,7 +1770,8 @@ namespace MediaBrowser.Controller.MediaEncoding : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""; // When the input may or may not be hardware VAAPI decodable - if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) { /* [base]: HW scaling video to OutputSize @@ -1741,7 +1783,8 @@ namespace MediaBrowser.Controller.MediaEncoding // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1 - && string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase)) + && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase))) { /* [base]: SW scaling video to OutputSize @@ -1750,7 +1793,8 @@ namespace MediaBrowser.Controller.MediaEncoding */ retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\""; } - else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) { /* QSV in FFMpeg can now setup hardware overlay for transcodes. @@ -1776,7 +1820,7 @@ namespace MediaBrowser.Controller.MediaEncoding videoSizeParam); } - private (int? width, int? height) GetFixedOutputSize( + public static (int? width, int? height) GetFixedOutputSize( int? videoWidth, int? videoHeight, int? requestedWidth, @@ -1836,7 +1880,9 @@ namespace MediaBrowser.Controller.MediaEncoding requestedMaxHeight); if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) && width.HasValue && height.HasValue) { @@ -1845,7 +1891,8 @@ namespace MediaBrowser.Controller.MediaEncoding // output dimensions. Output dimensions are guaranteed to be even. var outputWidth = width.Value; var outputHeight = height.Value; - var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase); + var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase); var isDeintEnabled = state.DeInterlace("h264", true) || state.DeInterlace("avc", true) || state.DeInterlace("h265", true) @@ -2107,10 +2154,13 @@ namespace MediaBrowser.Controller.MediaEncoding var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1; + var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1; var isNvdecH264Decoder = videoDecoder.IndexOf("h264_cuvid", StringComparison.OrdinalIgnoreCase) != -1; var isNvdecHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1; + var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1; var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isColorDepth10 = IsColorDepth10(state); @@ -2185,6 +2235,7 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add("hwdownload"); if (isLibX264Encoder + || isLibX265Encoder || hasGraphicalSubs || (isNvdecHevcDecoder && isDeinterlaceHevc) || (!isNvdecHevcDecoder && isDeinterlaceH264 || isDeinterlaceHevc)) @@ -2195,20 +2246,20 @@ namespace MediaBrowser.Controller.MediaEncoding } // When the input may or may not be hardware VAAPI decodable - if (isVaapiH264Encoder) + if (isVaapiH264Encoder || isVaapiHevcEncoder) { filters.Add("format=nv12|vaapi"); filters.Add("hwupload"); } // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context - else if (isLinux && hasGraphicalSubs && isQsvH264Encoder) + else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)) { filters.Add("hwupload=extra_hw_frames=64"); } // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first - else if (IsVaapiSupported(state) && isVaapiDecoder && isLibX264Encoder) + else if (IsVaapiSupported(state) && isVaapiDecoder && (isLibX264Encoder || isLibX265Encoder)) { var codec = videoStream.Codec.ToLowerInvariant(); @@ -2250,7 +2301,9 @@ namespace MediaBrowser.Controller.MediaEncoding // Add software deinterlace filter before scaling filter if ((isDeinterlaceH264 || isDeinterlaceHevc) && !isVaapiH264Encoder + && !isVaapiHevcEncoder && !isQsvH264Encoder + && !isQsvHevcEncoder && !isNvdecH264Decoder) { if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase)) @@ -2289,7 +2342,7 @@ namespace MediaBrowser.Controller.MediaEncoding } // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642) - if (isVaapiH264Encoder) + if (isVaapiH264Encoder || isVaapiHevcEncoder) { if (hasTextSubs) { diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index a4305c8104..102db3b44e 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -15,7 +15,6 @@ namespace MediaBrowser.Model.Dlna new ResolutionConfiguration(720, 950000), new ResolutionConfiguration(1280, 2500000), new ResolutionConfiguration(1920, 4000000), - new ResolutionConfiguration(2560, 8000000), new ResolutionConfiguration(3840, 35000000) }; From c6ff56a230c2de4a983374898647fca2f7414ab9 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 7 Nov 2020 18:59:32 +0000 Subject: [PATCH 0233/1930] Update BaseControlHandler.cs --- Emby.Dlna/Service/BaseControlHandler.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 4b0bbba969..198852ec17 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -169,6 +169,7 @@ namespace Emby.Dlna.Service var result = new ControlRequestInfo(localName, namespaceURI); using var subReader = reader.ReadSubtree(); await ParseFirstBodyChildAsync(subReader, result.Headers).ConfigureAwait(false); + return result; } else { From 7f4a3219eac136749546bebe0f398eb1e15c8311 Mon Sep 17 00:00:00 2001 From: Tomislav <tvctc@outlook.com> Date: Sat, 7 Nov 2020 20:23:16 +0000 Subject: [PATCH 0234/1930] Translated using Weblate (Croatian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hr/ --- .../Localization/Core/hr.json | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index a3c936240d..712ffde699 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -5,13 +5,13 @@ "Artists": "Izvođači", "AuthenticationSucceededWithUserName": "{0} uspješno ovjerena", "Books": "Knjige", - "CameraImageUploadedFrom": "Nova fotografija sa kamere je uploadana iz {0}", + "CameraImageUploadedFrom": "Nova fotografija sa kamere je učitana iz {0}", "Channels": "Kanali", "ChapterNameValue": "Poglavlje {0}", "Collections": "Kolekcije", - "DeviceOfflineWithName": "{0} se odspojilo", - "DeviceOnlineWithName": "{0} je spojeno", - "FailedLoginAttemptWithUserName": "Neuspjeli pokušaj prijave za {0}", + "DeviceOfflineWithName": "{0} je prekinuo vezu", + "DeviceOnlineWithName": "{0} je povezan", + "FailedLoginAttemptWithUserName": "Neuspjeli pokušaj prijave od {0}", "Favorites": "Favoriti", "Folders": "Mape", "Genres": "Žanrovi", @@ -23,19 +23,19 @@ "HeaderFavoriteShows": "Omiljene serije", "HeaderFavoriteSongs": "Omiljene pjesme", "HeaderLiveTV": "TV uživo", - "HeaderNextUp": "Sljedeće je", + "HeaderNextUp": "Slijedi", "HeaderRecordingGroups": "Grupa snimka", - "HomeVideos": "Kućni videi", + "HomeVideos": "Kućni video", "Inherit": "Naslijedi", "ItemAddedWithName": "{0} je dodano u biblioteku", - "ItemRemovedWithName": "{0} je uklonjen iz biblioteke", + "ItemRemovedWithName": "{0} je uklonjeno iz biblioteke", "LabelIpAddressValue": "IP adresa: {0}", "LabelRunningTimeValue": "Vrijeme rada: {0}", "Latest": "Najnovije", - "MessageApplicationUpdated": "Jellyfin Server je ažuriran", - "MessageApplicationUpdatedTo": "Jellyfin Server je ažuriran na {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Odjeljak postavka servera {0} je ažuriran", - "MessageServerConfigurationUpdated": "Postavke servera su ažurirane", + "MessageApplicationUpdated": "Jellyfin server je ažuriran", + "MessageApplicationUpdatedTo": "Jellyfin server je ažuriran na {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Dio konfiguracije servera {0} je ažuriran", + "MessageServerConfigurationUpdated": "Konfiguracija servera je ažurirana", "MixedContent": "Miješani sadržaj", "Movies": "Filmovi", "Music": "Glazba", @@ -113,5 +113,7 @@ "TaskCleanLogsDescription": "Briši logove koji su stariji od {0} dana.", "TaskCleanLogs": "Očisti direktorij sa logovima", "TasksChannelsCategory": "Internet kanali", - "TasksLibraryCategory": "Biblioteka" + "TasksLibraryCategory": "Biblioteka", + "TaskCleanActivityLogDescription": "Briše zapise dnevnika aktivnosti starije od navedenog vremena.", + "TaskCleanActivityLog": "Očisti dnevnik aktivnosti" } From 826f58b461fb892ff82b1902168b632f41ba5020 Mon Sep 17 00:00:00 2001 From: Tomislav <tvctc@outlook.com> Date: Sat, 7 Nov 2020 21:30:03 +0000 Subject: [PATCH 0235/1930] Translated using Weblate (Croatian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hr/ --- .../Localization/Core/hr.json | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index 712ffde699..4f570c8126 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -42,26 +42,26 @@ "MusicVideos": "Glazbeni spotovi", "NameInstallFailed": "{0} neuspješnih instalacija", "NameSeasonNumber": "Sezona {0}", - "NameSeasonUnknown": "Nepoznata sezona", + "NameSeasonUnknown": "Sezona nepoznata", "NewVersionIsAvailable": "Nova verzija Jellyfin servera je dostupna za preuzimanje.", - "NotificationOptionApplicationUpdateAvailable": "Dostupno ažuriranje aplikacije", - "NotificationOptionApplicationUpdateInstalled": "Instalirano ažuriranje aplikacije", - "NotificationOptionAudioPlayback": "Reprodukcija glazbe započeta", - "NotificationOptionAudioPlaybackStopped": "Reprodukcija audiozapisa je zaustavljena", - "NotificationOptionCameraImageUploaded": "Slike kamere preuzete", - "NotificationOptionInstallationFailed": "Instalacija neuspješna", - "NotificationOptionNewLibraryContent": "Novi sadržaj je dodan", - "NotificationOptionPluginError": "Dodatak otkazao", + "NotificationOptionApplicationUpdateAvailable": "Dostupno je ažuriranje aplikacije", + "NotificationOptionApplicationUpdateInstalled": "Instalirano je ažuriranje aplikacije", + "NotificationOptionAudioPlayback": "Reprodukcija glazbe započela", + "NotificationOptionAudioPlaybackStopped": "Reprodukcija glazbe zaustavljena", + "NotificationOptionCameraImageUploaded": "Slika s kamere učitana", + "NotificationOptionInstallationFailed": "Instalacija nije uspjela", + "NotificationOptionNewLibraryContent": "Novi sadržaj dodan", + "NotificationOptionPluginError": "Dodatak zakazao", "NotificationOptionPluginInstalled": "Dodatak instaliran", - "NotificationOptionPluginUninstalled": "Dodatak uklonjen", - "NotificationOptionPluginUpdateInstalled": "Instalirano ažuriranje za dodatak", - "NotificationOptionServerRestartRequired": "Potrebno ponovo pokretanje servera", - "NotificationOptionTaskFailed": "Zakazan zadatak nije izvršen", + "NotificationOptionPluginUninstalled": "Dodatak deinstaliran", + "NotificationOptionPluginUpdateInstalled": "Instalirano ažuriranje dodatka", + "NotificationOptionServerRestartRequired": "Ponovno pokrenite server", + "NotificationOptionTaskFailed": "Greška zakazanog zadatka", "NotificationOptionUserLockedOut": "Korisnik zaključan", - "NotificationOptionVideoPlayback": "Reprodukcija videa započeta", - "NotificationOptionVideoPlaybackStopped": "Reprodukcija videozapisa je zaustavljena", - "Photos": "Slike", - "Playlists": "Popis za reprodukciju", + "NotificationOptionVideoPlayback": "Reprodukcija videa započela", + "NotificationOptionVideoPlaybackStopped": "Reprodukcija videa zaustavljena", + "Photos": "Fotografije", + "Playlists": "Popisi za reprodukciju", "Plugin": "Dodatak", "PluginInstalledWithName": "{0} je instalirano", "PluginUninstalledWithName": "{0} je deinstalirano", From 2afaa1fc5bbf63558be3b98cb9129b003a19681f Mon Sep 17 00:00:00 2001 From: Tomislav <tvctc@outlook.com> Date: Sat, 7 Nov 2020 21:43:57 +0000 Subject: [PATCH 0236/1930] Translated using Weblate (Croatian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hr/ --- .../Localization/Core/hr.json | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index 4f570c8126..15f24d8c99 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -66,38 +66,38 @@ "PluginInstalledWithName": "{0} je instalirano", "PluginUninstalledWithName": "{0} je deinstalirano", "PluginUpdatedWithName": "{0} je ažurirano", - "ProviderValue": "Pružitelj: {0}", + "ProviderValue": "Pružatelj: {0}", "ScheduledTaskFailedWithName": "{0} neuspjelo", "ScheduledTaskStartedWithName": "{0} pokrenuto", - "ServerNameNeedsToBeRestarted": "{0} treba biti ponovno pokrenuto", + "ServerNameNeedsToBeRestarted": "{0} treba ponovno pokrenuti", "Shows": "Serije", "Songs": "Pjesme", - "StartupEmbyServerIsLoading": "Jellyfin Server se učitava. Pokušajte ponovo kasnije.", + "StartupEmbyServerIsLoading": "Jellyfin server se učitava. Pokušajte ponovo uskoro.", "SubtitleDownloadFailureForItem": "Titlovi prijevoda nisu preuzeti za {0}", - "SubtitleDownloadFailureFromForItem": "Prijevodi nisu uspješno preuzeti {0} od {1}", - "Sync": "Sink.", - "System": "Sistem", + "SubtitleDownloadFailureFromForItem": "Prijevod nije uspješno preuzet od {0} za {1}", + "Sync": "Sinkronizacija", + "System": "Sustav", "TvShows": "Serije", "User": "Korisnik", - "UserCreatedWithName": "Korisnik {0} je stvoren", + "UserCreatedWithName": "Korisnik {0} je kreiran", "UserDeletedWithName": "Korisnik {0} je obrisan", - "UserDownloadingItemWithValues": "{0} se preuzima {1}", + "UserDownloadingItemWithValues": "{0} preuzima {1}", "UserLockedOutWithName": "Korisnik {0} je zaključan", - "UserOfflineFromDevice": "{0} se odspojilo od {1}", - "UserOnlineFromDevice": "{0} je online od {1}", + "UserOfflineFromDevice": "{0} prekinuo vezu od {1}", + "UserOnlineFromDevice": "{0} povezan od {1}", "UserPasswordChangedWithName": "Lozinka je promijenjena za korisnika {0}", - "UserPolicyUpdatedWithName": "Pravila za korisnika su ažurirana za {0}", - "UserStartedPlayingItemWithValues": "{0} je pokrenuo {1}", - "UserStoppedPlayingItemWithValues": "{0} je zaustavio {1}", + "UserPolicyUpdatedWithName": "Pravila za korisnika ažurirana su za {0}", + "UserStartedPlayingItemWithValues": "{0} je pokrenuo reprodukciju {1} na {2}", + "UserStoppedPlayingItemWithValues": "{0} je završio reprodukciju {1} na {2}", "ValueHasBeenAddedToLibrary": "{0} je dodano u medijsku biblioteku", - "ValueSpecialEpisodeName": "Specijal - {0}", + "ValueSpecialEpisodeName": "Posebno - {0}", "VersionNumber": "Verzija {0}", "TaskRefreshLibraryDescription": "Skenira vašu medijsku knjižnicu sa novim datotekama i osvježuje metapodatke.", "TaskRefreshLibrary": "Skeniraj medijsku knjižnicu", "TaskRefreshChapterImagesDescription": "Stvara sličice za videozapise koji imaju poglavlja.", "TaskRefreshChapterImages": "Raspakiraj slike poglavlja", "TaskCleanCacheDescription": "Briše priručne datoteke nepotrebne za sistem.", - "TaskCleanCache": "Očisti priručnu memoriju", + "TaskCleanCache": "Očisti mapu predmemorije", "TasksApplicationCategory": "Aplikacija", "TasksMaintenanceCategory": "Održavanje", "TaskDownloadMissingSubtitlesDescription": "Pretraživanje interneta za prijevodima koji nedostaju bazirano na konfiguraciji meta podataka.", From a7f2073c68dae639ccc555a0c57ea0f8392e33a3 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 7 Nov 2020 17:30:56 -0700 Subject: [PATCH 0237/1930] Add missing dlna attributes. --- .../Controllers/DlnaServerController.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 271ae293b4..4e6455eaa7 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -77,6 +77,7 @@ namespace Jellyfin.Api.Controllers /// Gets Dlna media receiver registrar xml. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Dlna media receiver registrar xml returned.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/MediaReceiverRegistrar")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")] @@ -94,6 +95,7 @@ namespace Jellyfin.Api.Controllers /// Gets Dlna media receiver registrar xml. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Dlna media receiver registrar xml returned.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/ConnectionManager")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")] @@ -111,8 +113,12 @@ namespace Jellyfin.Api.Controllers /// Process a content directory control request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ContentDirectory/Control")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessContentDirectoryControlRequest([FromRoute, Required] string serverId) { return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false); @@ -122,8 +128,12 @@ namespace Jellyfin.Api.Controllers /// Process a connection manager control request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ConnectionManager/Control")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessConnectionManagerControlRequest([FromRoute, Required] string serverId) { return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false); @@ -133,8 +143,12 @@ namespace Jellyfin.Api.Controllers /// Process a media receiver registrar control request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/MediaReceiverRegistrar/Control")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId) { return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false); @@ -144,11 +158,15 @@ namespace Jellyfin.Api.Controllers /// Processes an event subscription request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")] [HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessMediaReceiverRegistrarEventRequest(string serverId) { return ProcessEventRequest(_mediaReceiverRegistrar); @@ -158,11 +176,15 @@ namespace Jellyfin.Api.Controllers /// Processes an event subscription request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ContentDirectory/Events")] [HttpUnsubscribe("{serverId}/ContentDirectory/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessContentDirectoryEventRequest(string serverId) { return ProcessEventRequest(_contentDirectory); @@ -172,11 +194,15 @@ namespace Jellyfin.Api.Controllers /// Processes an event subscription request. /// </summary> /// <param name="serverId">Server UUID.</param> + /// <response code="200">Request processed.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ConnectionManager/Events")] [HttpUnsubscribe("{serverId}/ConnectionManager/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(MediaTypeNames.Text.Xml)] + [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessConnectionManagerEventRequest(string serverId) { return ProcessEventRequest(_connectionManager); From dc3f24c11201b320206ef11ca5dab97358445048 Mon Sep 17 00:00:00 2001 From: Winnie <alvaritocrafter@gmail.com> Date: Sun, 8 Nov 2020 00:19:54 +0000 Subject: [PATCH 0238/1930] Translated using Weblate (Spanish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es/ --- Emby.Server.Implementations/Localization/Core/es.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json index d4e0b299dd..60abc08d40 100644 --- a/Emby.Server.Implementations/Localization/Core/es.json +++ b/Emby.Server.Implementations/Localization/Core/es.json @@ -77,7 +77,7 @@ "SubtitleDownloadFailureFromForItem": "Fallo de descarga de subtítulos desde {0} para {1}", "Sync": "Sincronizar", "System": "Sistema", - "TvShows": "Programas de televisión", + "TvShows": "Series", "User": "Usuario", "UserCreatedWithName": "El usuario {0} ha sido creado", "UserDeletedWithName": "El usuario {0} ha sido borrado", From ad1b08f2d63bc8aec79f8bbd131c1c85e65a0eba Mon Sep 17 00:00:00 2001 From: Tomislav <tvctc@outlook.com> Date: Sat, 7 Nov 2020 22:00:12 +0000 Subject: [PATCH 0239/1930] Translated using Weblate (Croatian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hr/ --- .../Localization/Core/hr.json | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index 15f24d8c99..9be91b7240 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -92,26 +92,26 @@ "ValueHasBeenAddedToLibrary": "{0} je dodano u medijsku biblioteku", "ValueSpecialEpisodeName": "Posebno - {0}", "VersionNumber": "Verzija {0}", - "TaskRefreshLibraryDescription": "Skenira vašu medijsku knjižnicu sa novim datotekama i osvježuje metapodatke.", - "TaskRefreshLibrary": "Skeniraj medijsku knjižnicu", - "TaskRefreshChapterImagesDescription": "Stvara sličice za videozapise koji imaju poglavlja.", - "TaskRefreshChapterImages": "Raspakiraj slike poglavlja", - "TaskCleanCacheDescription": "Briše priručne datoteke nepotrebne za sistem.", + "TaskRefreshLibraryDescription": "Skenira medijsku biblioteku radi novih datoteka i osvježava metapodatke.", + "TaskRefreshLibrary": "Skeniraj medijsku biblioteku", + "TaskRefreshChapterImagesDescription": "Kreira sličice za videozapise koji imaju poglavlja.", + "TaskRefreshChapterImages": "Izdvoji slike poglavlja", + "TaskCleanCacheDescription": "Briše nepotrebne datoteke iz predmemorije.", "TaskCleanCache": "Očisti mapu predmemorije", "TasksApplicationCategory": "Aplikacija", "TasksMaintenanceCategory": "Održavanje", - "TaskDownloadMissingSubtitlesDescription": "Pretraživanje interneta za prijevodima koji nedostaju bazirano na konfiguraciji meta podataka.", - "TaskDownloadMissingSubtitles": "Preuzimanje prijevoda koji nedostaju", - "TaskRefreshChannelsDescription": "Osvježava informacije o internet kanalima.", + "TaskDownloadMissingSubtitlesDescription": "Pretraži Internet za prijevodima koji nedostaju prema konfiguraciji metapodataka.", + "TaskDownloadMissingSubtitles": "Preuzmi prijevod koji nedostaje", + "TaskRefreshChannelsDescription": "Osvježava informacije Internet kanala.", "TaskRefreshChannels": "Osvježi kanale", - "TaskCleanTranscodeDescription": "Briše transkodirane fajlove starije od jednog dana.", - "TaskCleanTranscode": "Očisti direktorij za transkodiranje", - "TaskUpdatePluginsDescription": "Preuzima i instalira ažuriranja za dodatke koji su podešeni da se ažuriraju automatski.", + "TaskCleanTranscodeDescription": "Briše transkodirane datoteke starije od jednog dana.", + "TaskCleanTranscode": "Očisti mapu transkodiranja", + "TaskUpdatePluginsDescription": "Preuzima i instalira ažuriranja za dodatke koji su konfigurirani da se ažuriraju automatski.", "TaskUpdatePlugins": "Ažuriraj dodatke", - "TaskRefreshPeopleDescription": "Ažurira meta podatke za glumce i redatelje u vašoj medijskoj biblioteci.", - "TaskRefreshPeople": "Osvježi ljude", - "TaskCleanLogsDescription": "Briši logove koji su stariji od {0} dana.", - "TaskCleanLogs": "Očisti direktorij sa logovima", + "TaskRefreshPeopleDescription": "Ažurira metapodatke za glumce i redatelje u medijskoj biblioteci.", + "TaskRefreshPeople": "Osvježi osobe", + "TaskCleanLogsDescription": "Briše zapise dnevnika koji su stariji od {0} dana.", + "TaskCleanLogs": "Očisti mapu dnevnika zapisa", "TasksChannelsCategory": "Internet kanali", "TasksLibraryCategory": "Biblioteka", "TaskCleanActivityLogDescription": "Briše zapise dnevnika aktivnosti starije od navedenog vremena.", From 1bd5f780250993b01e551699f54f703032a0d1dd Mon Sep 17 00:00:00 2001 From: johan456789 <johan456789@gmail.com> Date: Sat, 7 Nov 2020 22:20:54 +0000 Subject: [PATCH 0240/1930] Translated using Weblate (Chinese (Traditional)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant/ --- Emby.Server.Implementations/Localization/Core/zh-TW.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index 30f7266300..d2e3d77a3a 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -112,5 +112,7 @@ "TaskRefreshChapterImagesDescription": "為有章節的影片建立縮圖。", "TasksChannelsCategory": "網路頻道", "TasksApplicationCategory": "應用程式", - "TasksMaintenanceCategory": "維修" + "TasksMaintenanceCategory": "維護", + "TaskCleanActivityLogDescription": "刪除超過所設時間的活動紀錄。", + "TaskCleanActivityLog": "清除活動紀錄" } From 1abd3d1bd8049e0fad557b95ee7d76916883b539 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 8 Nov 2020 07:13:00 +0000 Subject: [PATCH 0241/1930] fix the fmp4 header file generate on linux --- .../Controllers/DynamicHlsController.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 1247ef502e..9941c9f6e6 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -1373,7 +1374,8 @@ namespace Jellyfin.Api.Controllers var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)); + var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); + var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), outputFileNameWithoutExtension); var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); var outputTsArg = outputPrefix + "%d" + outputExtension; @@ -1384,7 +1386,19 @@ namespace Jellyfin.Api.Controllers } else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) { - var outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\""; + var outputFmp4HeaderArg = string.Empty; + var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + if (isWindows) + { + // on Windows, the path of fmp4 header file needs to be configured + outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\""; + } + else + { + // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder + outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""; + } + segmentFormat = "fmp4" + outputFmp4HeaderArg; } else From 0d1d0d113e9a8b272201f0455df5d51014a6d430 Mon Sep 17 00:00:00 2001 From: Ricky Zhang <haoyuzhangca@outlook.com> Date: Sun, 8 Nov 2020 06:07:42 +0000 Subject: [PATCH 0242/1930] Translated using Weblate (Chinese (Simplified)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hans/ --- Emby.Server.Implementations/Localization/Core/zh-CN.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index 53a902de28..e98047a369 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -113,5 +113,6 @@ "TaskCleanCacheDescription": "删除系统不再需要的缓存文件。", "TaskCleanCache": "清理缓存目录", "TasksApplicationCategory": "应用程序", - "TasksMaintenanceCategory": "维护" + "TasksMaintenanceCategory": "维护", + "TaskCleanActivityLog": "清理程序日志" } From 5048719a64ce914f859e058c1a7b03258255836e Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 8 Nov 2020 09:01:58 +0000 Subject: [PATCH 0243/1930] minor changes per suggestions --- .../Controllers/DynamicHlsController.cs | 6 +- Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs | 99 ++++++++++++------- .../MediaEncoding/EncodingHelper.cs | 8 +- 3 files changed, 72 insertions(+), 41 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 9941c9f6e6..6b1618421d 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1412,7 +1412,7 @@ namespace Jellyfin.Api.Controllers return string.Format( CultureInfo.InvariantCulture, - "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"", + "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts 0 -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"", inputModifier, _encodingHelper.GetInputArgument(state, encodingOptions), threads, @@ -1576,7 +1576,9 @@ namespace Jellyfin.Api.Controllers args += " " + gopArg; } else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) + || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) { args += " " + keyFrameArg; } diff --git a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs index 3d7a9d9a01..4999fcc62f 100644 --- a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs @@ -9,13 +9,38 @@ namespace Jellyfin.Api.Helpers /// </summary> public static class HlsCodecStringHelpers { + /// <summary> + /// Codec name for MP3. + /// </summary> + public const string MP3 = "mp4a.40.34"; + + /// <summary> + /// Codec name for AC-3. + /// </summary> + public const string AC3 = "mp4a.a5"; + + /// <summary> + /// Codec name for E-AC-3. + /// </summary> + public const string EAC3 = "mp4a.a6"; + + /// <summary> + /// Codec name for FLAC. + /// </summary> + public const string FLAC = "fLaC"; + + /// <summary> + /// Codec name for ALAC. + /// </summary> + public const string ALAC = "alac"; + /// <summary> /// Gets a MP3 codec string. /// </summary> /// <returns>MP3 codec string.</returns> public static string GetMP3String() { - return "mp4a.40.34"; + return MP3; } /// <summary> @@ -40,6 +65,42 @@ namespace Jellyfin.Api.Helpers return result.ToString(); } + /// <summary> + /// Gets an AC-3 codec string. + /// </summary> + /// <returns>AC-3 codec string.</returns> + public static string GetAC3String() + { + return AC3; + } + + /// <summary> + /// Gets an E-AC-3 codec string. + /// </summary> + /// <returns>E-AC-3 codec string.</returns> + public static string GetEAC3String() + { + return EAC3; + } + + /// <summary> + /// Gets an FLAC codec string. + /// </summary> + /// <returns>FLAC codec string.</returns> + public static string GetFLACString() + { + return FLAC; + } + + /// <summary> + /// Gets an ALAC codec string. + /// </summary> + /// <returns>ALAC codec string.</returns> + public static string GetALACString() + { + return ALAC; + } + /// <summary> /// Gets a H.264 codec string. /// </summary> @@ -104,41 +165,5 @@ namespace Jellyfin.Api.Helpers return result.ToString(); } - - /// <summary> - /// Gets an AC-3 codec string. - /// </summary> - /// <returns>AC-3 codec string.</returns> - public static string GetAC3String() - { - return "mp4a.a5"; - } - - /// <summary> - /// Gets an E-AC-3 codec string. - /// </summary> - /// <returns>E-AC-3 codec string.</returns> - public static string GetEAC3String() - { - return "mp4a.a6"; - } - - /// <summary> - /// Gets an FLAC codec string. - /// </summary> - /// <returns>FLAC codec string.</returns> - public static string GetFLACString() - { - return "fLaC"; - } - - /// <summary> - /// Gets an ALAC codec string. - /// </summary> - /// <returns>ALAC codec string.</returns> - public static string GetALACString() - { - return "alac"; - } } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 87670e2eb3..6e348f1e65 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -662,6 +662,10 @@ namespace MediaBrowser.Controller.MediaEncoding if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)) { + // Transcode to level 5.0 and lower for maximum compatibility + // level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it + // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels + // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880, if (requestLevel >= 150) { return "150"; @@ -3293,7 +3297,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps) { - args += " -copyts -avoid_negative_ts disabled -start_at_zero"; + args += " -copyts -avoid_negative_ts 0 -start_at_zero"; } if (!state.RunTimeTicks.HasValue) @@ -3341,7 +3345,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -copyts"; } - args += " -avoid_negative_ts disabled"; + args += " -avoid_negative_ts 0"; if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)) { From babb298b90f3c8d8025788d9c6c552fa92c09571 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 8 Nov 2020 09:35:04 +0000 Subject: [PATCH 0244/1930] fix ci --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 46c1ddc9f7..4999a582e3 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -532,6 +532,7 @@ namespace Jellyfin.Api.Helpers { return parsedLevel; } + return null; } @@ -693,8 +694,8 @@ namespace Jellyfin.Api.Helpers private string ReplaceProfile(string url, string codec, string oldValue, string newValue) { return url.Replace( - codec + "-profile=" + oldValue.ToString(), - codec + "-profile=" + newValue.ToString(), + codec + "-profile=" + oldValue, + codec + "-profile=" + newValue, StringComparison.OrdinalIgnoreCase); } From 38185f832688a3329045ee1bb26a38445c7777b2 Mon Sep 17 00:00:00 2001 From: Claus Vium <cvium@users.noreply.github.com> Date: Sun, 8 Nov 2020 11:20:28 +0100 Subject: [PATCH 0245/1930] Apply suggestions from code review --- MediaBrowser.Providers/Subtitles/SubtitleManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index f4a58775db..49ee70bb55 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -154,7 +154,7 @@ namespace MediaBrowser.Providers.Subtitles { var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false); - await TrySaveSubtitle(video, libraryOptions, response); + await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false); } catch (RateLimitExceededException) { @@ -174,10 +174,10 @@ namespace MediaBrowser.Providers.Subtitles } /// <inheritdoc /> - public async Task UploadSubtitle(Video video, SubtitleResponse response) + public Task UploadSubtitle(Video video, SubtitleResponse response) { var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video); - await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false); + return TrySaveSubtitle(video, libraryOptions, response); } private async Task TrySaveSubtitle( From 2229ca38aca0d3007473a52c9560cec0bac8ac05 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 8 Nov 2020 19:33:40 +0800 Subject: [PATCH 0246/1930] pascal case --- Jellyfin.Api/Controllers/SubtitleController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 4c9a153840..a01ae31a0e 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -459,7 +459,7 @@ namespace Jellyfin.Api.Controllers if (fontFile != null && fileSize != null && fileSize > 0) { - _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize); + _logger.LogDebug("Fallback font size is {fileSize} Bytes", fileSize); return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName)); } else From 802d37aac5a806dac5ef7e4c64b63b64dcf30302 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 8 Nov 2020 12:09:32 +0000 Subject: [PATCH 0247/1930] Update Emby.Naming/Common/NamingOptions.cs --- Emby.Naming/Common/NamingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 0a7224774c..20667abd27 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -137,7 +137,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*", - @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*" + @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*", @"(.+\w)\W+\p{Ps}(19[0-9]{2}|20[0-9]{2})\p{Pe}", // Prefer year enclosed in parenthesis (){}[] @"(.+\w)\W+(19[0-9]{2}|20[0-9]{2})(\W|$)", // Secondary year surrounded by non-word chars }; From 866c41519f2dcf40bb881cec4d8995e17a99b596 Mon Sep 17 00:00:00 2001 From: Neil Burrows <neil.burrows@nvable.com> Date: Sun, 8 Nov 2020 12:34:35 +0000 Subject: [PATCH 0248/1930] Perform hashing of Password for Schedules Direct on server --- .../LiveTv/Listings/SchedulesDirect.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 28aabc1599..8735745c6b 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -15,6 +15,7 @@ using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; @@ -33,17 +34,20 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly IHttpClientFactory _httpClientFactory; private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1); private readonly IApplicationHost _appHost; + private readonly ICryptoProvider _cryptoProvider; public SchedulesDirect( ILogger<SchedulesDirect> logger, IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory, - IApplicationHost appHost) + IApplicationHost appHost, + ICryptoProvider cryptoProvider) { _logger = logger; _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _appHost = appHost; + _cryptoProvider = cryptoProvider; } private string UserAgent => _appHost.ApplicationUserAgent; @@ -642,7 +646,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken cancellationToken) { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); - options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); + var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>()); + string hashedPassword = string.Concat(hashedPasswordBytes.Select(b => b.ToString("x2", CultureInfo.InvariantCulture))); + options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); From e8b832ea185a912f9546ae749bc65e7c3584e21f Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 06:42:33 -0700 Subject: [PATCH 0249/1930] Update MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 967c6fa154..763c56fa6c 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -63,7 +63,7 @@ namespace MediaBrowser.Controller.BaseItemManager if (baseItem.SourceType == SourceType.Channel) { - // hack alert + // Hack alert. return !baseItem.EnableMediaSourceDisplay; } @@ -83,4 +83,4 @@ namespace MediaBrowser.Controller.BaseItemManager return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); } } -} \ No newline at end of file +} From e06b33af83e0555ddc2461bcfa72eaeb7a9bc973 Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 06:42:40 -0700 Subject: [PATCH 0250/1930] Update MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 763c56fa6c..218920b044 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.Controller.BaseItemManager { if (baseItem is Channel) { - // hack alert + // Hack alert. return true; } From 1996e08dd12ee92b3cc2ef4d1b9932a6a0b7b27d Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 06:42:49 -0700 Subject: [PATCH 0251/1930] Update MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 218920b044..5d9b851d36 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Controller.BaseItemManager if (baseItem.SourceType == SourceType.Channel) { - // hack alert + // Hack alert. return !baseItem.EnableMediaSourceDisplay; } From ce88815b3cd0c3be5aba07daf0af0e73e043d91b Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 06:42:54 -0700 Subject: [PATCH 0252/1930] Update MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 5d9b851d36..67aa7f3383 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Controller.BaseItemManager { if (baseItem is Channel) { - // hack alert + // Hack alert. return true; } From e78c63c4dc819867acddc5a15a7d7c02f7aa9b30 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sun, 8 Nov 2020 16:10:33 +0100 Subject: [PATCH 0253/1930] Remove OriginalAuthenticationInfo and add IsAuthenticated property --- .../HttpServer/Security/AuthService.cs | 5 ++-- .../Security/AuthorizationContext.cs | 25 +++++++++---------- .../Auth/CustomAuthenticationHandler.cs | 2 +- .../Net/AuthorizationInfo.cs | 5 ++++ .../Auth/CustomAuthenticationHandlerTests.cs | 5 ++-- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 7d53e886f7..df7a034e8f 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using Jellyfin.Data.Enums; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; @@ -19,9 +20,9 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo Authenticate(HttpRequest request) { var auth = _authorizationContext.GetAuthorizationInfo(request); - if (auth == null) + if (!auth.IsAuthenticated) { - throw new SecurityException("Unauthenticated request."); + throw new AuthenticationException("Invalid token."); } if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index de7e7bf3b8..e733c9092a 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -36,8 +36,7 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext) { var auth = GetAuthorizationDictionary(requestContext); - var (authInfo, _) = - GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query); + var authInfo = GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query); return authInfo; } @@ -49,19 +48,13 @@ namespace Emby.Server.Implementations.HttpServer.Security private AuthorizationInfo GetAuthorization(HttpContext httpReq) { var auth = GetAuthorizationDictionary(httpReq); - var (authInfo, originalAuthInfo) = - GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query); - - if (originalAuthInfo != null) - { - httpReq.Request.HttpContext.Items["OriginalAuthenticationInfo"] = originalAuthInfo; - } + var authInfo = GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query); httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo; return authInfo; } - private (AuthorizationInfo authInfo, AuthenticationInfo originalAuthenticationInfo) GetAuthorizationInfoFromDictionary( + private AuthorizationInfo GetAuthorizationInfoFromDictionary( in Dictionary<string, string> auth, in IHeaderDictionary headers, in IQueryCollection queryString) @@ -108,13 +101,14 @@ namespace Emby.Server.Implementations.HttpServer.Security Device = device, DeviceId = deviceId, Version = version, - Token = token + Token = token, + IsAuthenticated = false }; if (string.IsNullOrWhiteSpace(token)) { // Request doesn't contain a token. - return (null, null); + return authInfo; } var result = _authRepo.Get(new AuthenticationInfoQuery @@ -122,6 +116,11 @@ namespace Emby.Server.Implementations.HttpServer.Security AccessToken = token }); + if (result.Items.Count > 0) + { + authInfo.IsAuthenticated = true; + } + var originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null; if (originalAuthenticationInfo != null) @@ -197,7 +196,7 @@ namespace Emby.Server.Implementations.HttpServer.Security } } - return (authInfo, originalAuthenticationInfo); + return authInfo; } /// <summary> diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index e8cc389072..27a1f61be0 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -1,10 +1,10 @@ using System.Globalization; -using System.Security.Authentication; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Data.Enums; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs index 5c642edff2..0194c596f1 100644 --- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs +++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs @@ -53,5 +53,10 @@ namespace MediaBrowser.Controller.Net /// Gets or sets the user making the request. /// </summary> public User User { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the token is authenticated. + /// </summary> + public bool IsAuthenticated { get; set; } } } diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index 33534abd2f..a46d94457f 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -8,6 +8,7 @@ using Jellyfin.Api.Auth; using Jellyfin.Api.Constants; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; +using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; @@ -68,14 +69,14 @@ namespace Jellyfin.Api.Tests.Auth } [Fact] - public async Task HandleAuthenticateAsyncShouldFailOnSecurityException() + public async Task HandleAuthenticateAsyncShouldFailOnAuthenticationException() { var errorMessage = _fixture.Create<string>(); _jellyfinAuthServiceMock.Setup( a => a.Authenticate( It.IsAny<HttpRequest>())) - .Throws(new SecurityException(errorMessage)); + .Throws(new AuthenticationException(errorMessage)); var authenticateResult = await _sut.AuthenticateAsync(); From 73f923c8d50cdf673fe094c33f6e92b77144bedf Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 09:31:53 -0700 Subject: [PATCH 0254/1930] Use class instead of struct --- MediaBrowser.Common/Plugins/LocalPlugin.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 922fad23ae..7927c663d4 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -7,10 +7,10 @@ namespace MediaBrowser.Common.Plugins /// <summary> /// Local plugin struct. /// </summary> - public readonly struct LocalPlugin : IEquatable<LocalPlugin> + public class LocalPlugin : IEquatable<LocalPlugin> { /// <summary> - /// Initializes a new instance of the <see cref="LocalPlugin"/> struct. + /// Initializes a new instance of the <see cref="LocalPlugin"/> class. /// </summary> /// <param name="id">The plugin id.</param> /// <param name="name">The plugin name.</param> From e9d35cb2cab134c1f285d695778424fafd8b35d6 Mon Sep 17 00:00:00 2001 From: Neil Burrows <neil.burrows@nvable.com> Date: Sun, 8 Nov 2020 17:16:51 +0000 Subject: [PATCH 0255/1930] Switching to the more efficient Hex.Encode function --- Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 8735745c6b..aacadde504 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -647,7 +647,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>()); - string hashedPassword = string.Concat(hashedPasswordBytes.Select(b => b.ToString("x2", CultureInfo.InvariantCulture))); + string hashedPassword = Hex.Encode(hashedPasswordBytes); options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); From d2f439efd29301774a54cbec907fe16e237cc7c5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 8 Nov 2020 10:22:38 -0700 Subject: [PATCH 0256/1930] Remove unstable npm ci task --- .ci/azure-pipelines-api-client.yml | 19 ------------------- .../templates/typescript/axios/generate.sh | 10 +--------- 2 files changed, 1 insertion(+), 28 deletions(-) diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml index de6bbf04ce..03102121ff 100644 --- a/.ci/azure-pipelines-api-client.yml +++ b/.ci/azure-pipelines-api-client.yml @@ -35,14 +35,6 @@ jobs: customEndpoint: 'jellyfin-bot for NPM' ## Generate npm api client -# Unstable - - task: CmdLine@2 - displayName: 'Build unstable typescript axios client' - condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master') - inputs: - script: "bash ./apiclient/templates/typescript/axios/generate.sh $(System.ArtifactsDirectory) $(Build.BuildNumber)" - -# Stable - task: CmdLine@2 displayName: 'Build stable typescript axios client' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') @@ -57,17 +49,6 @@ jobs: workingDir: ./apiclient/generated/typescript/axios ## Publish npm packages -# Unstable - - task: Npm@1 - displayName: 'Publish unstable typescript axios client' - condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master') - inputs: - command: publish - publishRegistry: useFeed - publishFeed: 'jellyfin/unstable' - workingDir: ./apiclient/generated/typescript/axios - -# Stable - task: Npm@1 displayName: 'Publish stable typescript axios client' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') diff --git a/apiclient/templates/typescript/axios/generate.sh b/apiclient/templates/typescript/axios/generate.sh index 8c4d742825..9599f85dbd 100644 --- a/apiclient/templates/typescript/axios/generate.sh +++ b/apiclient/templates/typescript/axios/generate.sh @@ -1,14 +1,6 @@ #!/bin/bash artifactsDirectory="${1}" -buildNumber="${2}" -if [[ -n ${buildNumber} ]]; then - # Unstable build - additionalProperties=",snapshotVersion=-SNAPSHOT.${buildNumber},npmRepository=https://pkgs.dev.azure.com/jellyfin-project/jellyfin/_packaging/unstable/npm/registry/" -else - # Stable build - additionalProperties="" -fi java -jar openapi-generator-cli.jar generate \ --input-spec ${artifactsDirectory}/openapispec/openapi.json \ @@ -16,4 +8,4 @@ java -jar openapi-generator-cli.jar generate \ --output ./apiclient/generated/typescript/axios \ --template-dir ./apiclient/templates/typescript/axios \ --ignore-file-override ./apiclient/.openapi-generator-ignore \ - --additional-properties=useSingleRequestParameter="true",withSeparateModelsAndApi="true",modelPackage="models",apiPackage="api",npmName="axios"${additionalProperties} + --additional-properties=useSingleRequestParameter="true",withSeparateModelsAndApi="true",modelPackage="models",apiPackage="api",npmName="axios" From e5c0aaead2f190e080e534fcd4ba36d874896104 Mon Sep 17 00:00:00 2001 From: Ekrem KANGAL <ekangal@gmail.com> Date: Sun, 8 Nov 2020 15:05:52 +0000 Subject: [PATCH 0257/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 818b57c7f6..54d3a65f0d 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -114,5 +114,6 @@ "TaskRefreshChapterImagesDescription": "Sahnelere ayrılmış videolar için küçük resimler oluştur.", "TaskRefreshChapterImages": "Bölüm Resimlerini Çıkar", "TaskCleanCacheDescription": "Sistem tarafından artık ihtiyaç duyulmayan önbellek dosyalarını siler.", - "TaskCleanActivityLog": "İşlem Günlüğünü Temizle" + "TaskCleanActivityLog": "İşlem Günlüğünü Temizle", + "TaskCleanActivityLogDescription": "Belirtilen sureden daha eski etkinlik log kayıtları silindi." } From 363d41f9435e5dbdc8e933690cff66f89d3808fc Mon Sep 17 00:00:00 2001 From: Kyle Yue <sevenbookyue@gmail.com> Date: Sun, 8 Nov 2020 11:46:46 +0000 Subject: [PATCH 0258/1930] Translated using Weblate (Chinese (Simplified)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hans/ --- Emby.Server.Implementations/Localization/Core/zh-CN.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index e98047a369..3ae0fe5e77 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -114,5 +114,6 @@ "TaskCleanCache": "清理缓存目录", "TasksApplicationCategory": "应用程序", "TasksMaintenanceCategory": "维护", - "TaskCleanActivityLog": "清理程序日志" + "TaskCleanActivityLog": "清理程序日志", + "TaskCleanActivityLogDescription": "删除早于设置时间的活动日志条目。" } From f680a0fbbed346a5a5e98b2066604c463791190c Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Sun, 8 Nov 2020 11:55:38 -0800 Subject: [PATCH 0259/1930] fix merge --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 4d24e45b0c..be313bde1b 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -271,6 +271,7 @@ namespace MediaBrowser.Model.Configuration /// </summary> public string[] KnownProxies { get; set; } + /// <summary> /// Gets or sets the number of days we should retain activity logs. /// </summary> public int? ActivityLogRetentionDays { get; set; } From 254c188f6cf0e4c53df012d6c471924550ec4490 Mon Sep 17 00:00:00 2001 From: hoanghuy309 <hoanghuy309@gmail.com> Date: Mon, 9 Nov 2020 02:30:53 +0000 Subject: [PATCH 0260/1930] Translated using Weblate (Vietnamese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/vi/ --- Emby.Server.Implementations/Localization/Core/vi.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index ac74deff82..ba58e4bebf 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -112,5 +112,7 @@ "Books": "Sách", "AuthenticationSucceededWithUserName": "{0} xác thực thành công", "Application": "Ứng Dụng", - "AppDeviceValues": "Ứng Dụng: {0}, Thiết Bị: {1}" + "AppDeviceValues": "Ứng Dụng: {0}, Thiết Bị: {1}", + "TaskCleanActivityLogDescription": "Xóa các mục nhật ký hoạt động cũ hơn độ tuổi đã cài đặt.", + "TaskCleanActivityLog": "Xóa Nhật Ký Hoạt Động" } From f63a706a86aeedd6bdea96903bd8dd03c6703b5e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:23:52 +0000 Subject: [PATCH 0261/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 69f8521d08..97d46a0c06 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -826,7 +826,7 @@ namespace Emby.Server.Implementations private void RegisterPluginServices() { - foreach (var pluginServiceRegistrar in GetExportTypes<IPluginServiceRegistrator>()) + foreach (var pluginServiceRegistrator in GetExportTypes<IPluginServiceRegistrator>()) { try { From 69790ef6b8632e46cbdad0ea8415c35a107dcb1e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:24:53 +0000 Subject: [PATCH 0262/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- .../AppBase/BaseConfigurationManager.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index a5a361d24b..15bf92db1d 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -148,9 +148,11 @@ namespace Emby.Server.Implementations.AppBase } else { - var list = _configurationFactories.ToList(); - list.Add(factory); - _configurationFactories = list.ToArray(); + var oldLen = _configurationFactories.Length; + var arr = new IConfigurationFactory[oldLen + 1]; + _configurationFactories.CopyTo(arr, 0); + arr[oldLen] = factory; + _configurationFactories = arr; } _configurationStores = _configurationFactories From e340e755f27f0022806e8c119ef3a12e11b88911 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:25:05 +0000 Subject: [PATCH 0263/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 97d46a0c06..04f0b55185 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -830,7 +830,7 @@ namespace Emby.Server.Implementations { try { - var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrar); + var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator); instance.RegisterServices(ServiceCollection); } catch (Exception ex) From 11a5353810badafb0b0d4256007ed057c0b94e27 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:25:16 +0000 Subject: [PATCH 0264/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 04f0b55185..b180df5e75 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -835,7 +835,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrar.Assembly); + Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly); } } } From 429de724430671a9019ab38af55b8f11889a62cd Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:25:42 +0000 Subject: [PATCH 0265/1930] Update MediaBrowser.Common/Plugins/BasePlugin.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- MediaBrowser.Common/Plugins/BasePlugin.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 11445d79d4..ae9218bcd1 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -56,8 +56,8 @@ namespace MediaBrowser.Common.Plugins /// Gets a value indicating whether the plugin can be uninstalled. /// </summary> public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) - .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) && - !typeof(IPluginServiceRegistrator).IsAssignableFrom(this.GetType()); + .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) + && !typeof(IPluginServiceRegistrator).IsAssignableFrom(this.GetType()); /// <summary> /// Gets the plugin info. From 957b5df0f0048f5e4930cdce97e4306c98a96b40 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 9 Nov 2020 11:26:06 +0000 Subject: [PATCH 0266/1930] Update MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs index cb6c27f862..3afe874c52 100644 --- a/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs +++ b/MediaBrowser.Common/Plugins/IPluginServiceRegistrator.cs @@ -9,8 +9,10 @@ namespace MediaBrowser.Common.Plugins { /// <summary> /// Registers the plugin's services with the service collection. - /// This object is created prior to the plugin creation, so access to other classes is limited. /// </summary> + /// <remarks> + /// This interface is only used for service registration and requires a parameterless constructor. + /// </remarks> /// <param name="serviceCollection">The service collection.</param> void RegisterServices(IServiceCollection serviceCollection); } From e15891df5109388254119e877c2d9e6e7114ffbb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2020 12:00:39 +0000 Subject: [PATCH 0267/1930] Bump Microsoft.NET.Test.Sdk from 16.7.1 to 16.8.0 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.7.1 to 16.8.0. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.7.1...v16.8.0) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 0236f2ac1e..ce61f5684e 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.9" /> <PackageReference Include="Microsoft.Extensions.Options" Version="3.1.9" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index e3f87d29b7..67dc8286a3 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index 5de02a29ba..30e84842a0 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 3ac60819b4..4fd0d53421 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -19,7 +19,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 37d0a9929a..0d240fd65a 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 05323490e2..db1f2956ea 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -16,7 +16,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="Moq" Version="4.14.7" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> From 3874f570edca18e6ae3ae83c11418331acff2437 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2020 12:00:50 +0000 Subject: [PATCH 0268/1930] Bump Serilog.Sinks.Graylog from 2.2.1 to 2.2.2 Bumps [Serilog.Sinks.Graylog](https://github.com/whir1/serilog-sinks-graylog) from 2.2.1 to 2.2.2. - [Release notes](https://github.com/whir1/serilog-sinks-graylog/releases) - [Commits](https://github.com/whir1/serilog-sinks-graylog/commits) Signed-off-by: dependabot[bot] <support@github.com> --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index a64d2e1cdb..3558f144cf 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -50,7 +50,7 @@ <PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" /> <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" /> - <PackageReference Include="Serilog.Sinks.Graylog" Version="2.2.1" /> + <PackageReference Include="Serilog.Sinks.Graylog" Version="2.2.2" /> <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.0.4" /> <PackageReference Include="SQLitePCLRaw.provider.sqlite3.netstandard11" Version="1.1.14" /> </ItemGroup> From 78551d166a98eabe0f10c43b9fbb486a74887275 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 9 Nov 2020 06:10:16 -0700 Subject: [PATCH 0269/1930] Don't throw exception if name is null --- Emby.Naming/Video/CleanDateTimeParser.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index 579c9e91e1..f05d540f8b 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -15,6 +15,11 @@ namespace Emby.Naming.Video public static CleanDateTimeResult Clean(string name, IReadOnlyList<Regex> cleanDateTimeRegexes) { CleanDateTimeResult result = new CleanDateTimeResult(name); + if (string.IsNullOrEmpty(name)) + { + return result; + } + var len = cleanDateTimeRegexes.Count; for (int i = 0; i < len; i++) { From b99519898d2c9e8ba3020e11892718f1eca37c66 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Mon, 9 Nov 2020 20:15:15 +0100 Subject: [PATCH 0270/1930] Remove duplicate /Similar endpoints and add poor matching for artists and albums --- .../Data/SqliteItemRepository.cs | 28 ++- Jellyfin.Api/Controllers/AlbumsController.cs | 135 ------------- Jellyfin.Api/Controllers/LibraryController.cs | 164 +++++++--------- Jellyfin.Api/Helpers/SimilarItemsHelper.cs | 182 ------------------ 4 files changed, 90 insertions(+), 419 deletions(-) delete mode 100644 Jellyfin.Api/Controllers/AlbumsController.cs delete mode 100644 Jellyfin.Api/Helpers/SimilarItemsHelper.cs diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index acb75e9b89..0761b64bd2 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -2403,11 +2403,11 @@ namespace Emby.Server.Implementations.Data if (string.IsNullOrEmpty(item.OfficialRating)) { - builder.Append("((OfficialRating is null) * 10)"); + builder.Append("(OfficialRating is null * 10)"); } else { - builder.Append("((OfficialRating=@ItemOfficialRating) * 10)"); + builder.Append("(OfficialRating=@ItemOfficialRating * 10)"); } if (item.ProductionYear.HasValue) @@ -2416,8 +2416,26 @@ namespace Emby.Server.Implementations.Data builder.Append("+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 5 Then 5 Else 0 End )"); } - //// genres, tags - builder.Append("+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId)) * 10)"); + // genres, tags, studios, person, year? + builder.Append("+ (Select count(1) * 10 from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId))"); + + if (item is MusicArtist) + { + // Match albums where the artist is AlbumArtist against other albums. + // It is assumed that similar albums => similar artists. + builder.Append( + @"+ (WITH artistValues AS ( + SELECT DISTINCT albumValues.CleanValue + FROM ItemValues albumValues + INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId + INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = @SimilarItemId + ), similarArtist AS ( + SELECT albumValues.ItemId + FROM ItemValues albumValues + INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId + INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = A.Guid + ) SELECT COUNT(DISTINCT(CleanValue)) * 10 FROM ItemValues WHERE ItemId IN (SELECT ItemId FROM similarArtist) AND CleanValue IN (SELECT CleanValue FROM artistValues))"); + } builder.Append(") as SimilarityScore"); @@ -5052,7 +5070,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type CheckDisposed(); - var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People"; + var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People p"; var whereClauses = GetPeopleWhereClauses(query, null); diff --git a/Jellyfin.Api/Controllers/AlbumsController.cs b/Jellyfin.Api/Controllers/AlbumsController.cs deleted file mode 100644 index 357f646a2b..0000000000 --- a/Jellyfin.Api/Controllers/AlbumsController.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Querying; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; - -namespace Jellyfin.Api.Controllers -{ - /// <summary> - /// The albums controller. - /// </summary> - [Route("")] - public class AlbumsController : BaseJellyfinApiController - { - private readonly IUserManager _userManager; - private readonly ILibraryManager _libraryManager; - private readonly IDtoService _dtoService; - - /// <summary> - /// Initializes a new instance of the <see cref="AlbumsController"/> class. - /// </summary> - /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> - /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> - /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param> - public AlbumsController( - IUserManager userManager, - ILibraryManager libraryManager, - IDtoService dtoService) - { - _userManager = userManager; - _libraryManager = libraryManager; - _dtoService = dtoService; - } - - /// <summary> - /// Finds albums similar to a given album. - /// </summary> - /// <param name="albumId">The album id.</param> - /// <param name="userId">Optional. Filter by user id, and attach user data.</param> - /// <param name="excludeArtistIds">Optional. Ids of artists to exclude.</param> - /// <param name="limit">Optional. The maximum number of records to return.</param> - /// <response code="200">Similar albums returned.</response> - /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with similar albums.</returns> - [HttpGet("Albums/{albumId}/Similar")] - [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<QueryResult<BaseItemDto>> GetSimilarAlbums( - [FromRoute, Required] string albumId, - [FromQuery] Guid? userId, - [FromQuery] string? excludeArtistIds, - [FromQuery] int? limit) - { - var dtoOptions = new DtoOptions().AddClientFields(Request); - - return SimilarItemsHelper.GetSimilarItemsResult( - dtoOptions, - _userManager, - _libraryManager, - _dtoService, - userId, - albumId, - excludeArtistIds, - limit, - new[] { typeof(MusicAlbum) }, - GetAlbumSimilarityScore); - } - - /// <summary> - /// Finds artists similar to a given artist. - /// </summary> - /// <param name="artistId">The artist id.</param> - /// <param name="userId">Optional. Filter by user id, and attach user data.</param> - /// <param name="excludeArtistIds">Optional. Ids of artists to exclude.</param> - /// <param name="limit">Optional. The maximum number of records to return.</param> - /// <response code="200">Similar artists returned.</response> - /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with similar artists.</returns> - [HttpGet("Artists/{artistId}/Similar")] - [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<QueryResult<BaseItemDto>> GetSimilarArtists( - [FromRoute, Required] string artistId, - [FromQuery] Guid? userId, - [FromQuery] string? excludeArtistIds, - [FromQuery] int? limit) - { - var dtoOptions = new DtoOptions().AddClientFields(Request); - - return SimilarItemsHelper.GetSimilarItemsResult( - dtoOptions, - _userManager, - _libraryManager, - _dtoService, - userId, - artistId, - excludeArtistIds, - limit, - new[] { typeof(MusicArtist) }, - SimilarItemsHelper.GetSimiliarityScore); - } - - /// <summary> - /// Gets a similairty score of two albums. - /// </summary> - /// <param name="item1">The first item.</param> - /// <param name="item1People">The item1 people.</param> - /// <param name="allPeople">All people.</param> - /// <param name="item2">The second item.</param> - /// <returns>System.Int32.</returns> - private int GetAlbumSimilarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2) - { - var points = SimilarItemsHelper.GetSimiliarityScore(item1, item1People, allPeople, item2); - - var album1 = (MusicAlbum)item1; - var album2 = (MusicAlbum)item2; - - var artists1 = album1 - .GetAllArtists() - .DistinctNames() - .ToList(); - - var artists2 = new HashSet<string>( - album2.GetAllArtists().DistinctNames(), - StringComparer.OrdinalIgnoreCase); - - return points + artists1.Where(artists2.Contains).Sum(i => 5); - } - } -} diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 8a872ae133..112415ef03 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -680,12 +680,12 @@ namespace Jellyfin.Api.Controllers /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> /// <response code="200">Similar items returned.</response> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns> - [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists2")] + [HttpGet("Artists/{itemId}/Similar")] [HttpGet("Items/{itemId}/Similar")] - [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums2")] - [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows2")] - [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies2")] - [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers2")] + [HttpGet("Albums/{itemId}/Similar")] + [HttpGet("Shows/{itemId}/Similar")] + [HttpGet("Movies/{itemId}/Similar")] + [HttpGet("Trailers/{itemId}/Similar")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems( @@ -701,33 +701,72 @@ namespace Jellyfin.Api.Controllers : _libraryManager.RootFolder) : _libraryManager.GetItemById(itemId); - var program = item as IHasProgramAttributes; - var isMovie = item is MediaBrowser.Controller.Entities.Movies.Movie || (program != null && program.IsMovie) || item is Trailer; - if (program != null && program.IsSeries) - { - return GetSimilarItemsResult( - item, - excludeArtistIds, - userId, - limit, - fields, - new[] { nameof(Series) }, - false); - } - - if (item is MediaBrowser.Controller.Entities.TV.Episode || (item is IItemByName && !(item is MusicArtist))) + if (item is Episode || (item is IItemByName && !(item is MusicArtist))) { return new QueryResult<BaseItemDto>(); } - return GetSimilarItemsResult( - item, - excludeArtistIds, - userId, - limit, - fields, - new[] { item.GetType().Name }, - isMovie); + var user = userId.HasValue && !userId.Equals(Guid.Empty) + ? _userManager.GetUserById(userId.Value) + : null; + var dtoOptions = new DtoOptions() + .AddItemFields(fields) + .AddClientFields(Request); + + var program = item as IHasProgramAttributes; + bool? isMovie = item is Movie || (program != null && program.IsMovie) || item is Trailer; + bool? isSeries = item is Series || (program != null && program.IsSeries); + + var includeItemTypes = new List<string>(); + if (isMovie.Value) + { + includeItemTypes.Add(nameof(Movie)); + if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions) + { + includeItemTypes.Add(nameof(Trailer)); + includeItemTypes.Add(nameof(LiveTvProgram)); + } + } + else if (isSeries.Value) + { + includeItemTypes.Add(nameof(Series)); + } + else + { + // For non series and movie types these columns are typically null + isSeries = null; + isMovie = null; + includeItemTypes.Add(item.GetType().Name); + } + + var query = new InternalItemsQuery(user) + { + Limit = limit, + IncludeItemTypes = includeItemTypes.ToArray(), + IsMovie = isMovie, + IsSeries = isSeries, + SimilarTo = item, + DtoOptions = dtoOptions, + EnableTotalRecordCount = !isMovie ?? true, + EnableGroupByMetadataKey = isMovie ?? false, + MinSimilarityScore = 2 // A remnant from album/artist scoring + }; + + // ExcludeArtistIds + if (!string.IsNullOrEmpty(excludeArtistIds)) + { + query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds); + } + + List<BaseItem> itemsResult = _libraryManager.GetItemList(query); + + var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user); + + return new QueryResult<BaseItemDto> + { + Items = returnList, + TotalRecordCount = itemsResult.Count + }; } /// <summary> @@ -880,75 +919,6 @@ namespace Jellyfin.Api.Controllers } } - private QueryResult<BaseItemDto> GetSimilarItemsResult( - BaseItem item, - string? excludeArtistIds, - Guid? userId, - int? limit, - string? fields, - string[] includeItemTypes, - bool isMovie) - { - var user = userId.HasValue && !userId.Equals(Guid.Empty) - ? _userManager.GetUserById(userId.Value) - : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) - .AddClientFields(Request); - - var query = new InternalItemsQuery(user) - { - Limit = limit, - IncludeItemTypes = includeItemTypes, - IsMovie = isMovie, - SimilarTo = item, - DtoOptions = dtoOptions, - EnableTotalRecordCount = !isMovie, - EnableGroupByMetadataKey = isMovie - }; - - // ExcludeArtistIds - if (!string.IsNullOrEmpty(excludeArtistIds)) - { - query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds); - } - - List<BaseItem> itemsResult; - - if (isMovie) - { - var itemTypes = new List<string> { nameof(MediaBrowser.Controller.Entities.Movies.Movie) }; - if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions) - { - itemTypes.Add(nameof(Trailer)); - itemTypes.Add(nameof(LiveTvProgram)); - } - - query.IncludeItemTypes = itemTypes.ToArray(); - itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList(); - } - else if (item is MusicArtist) - { - query.IncludeItemTypes = Array.Empty<string>(); - - itemsResult = _libraryManager.GetArtists(query).Items.Select(i => i.Item1).ToList(); - } - else - { - itemsResult = _libraryManager.GetItemList(query); - } - - var returnList = _dtoService.GetBaseItemDtos(itemsResult, dtoOptions, user); - - var result = new QueryResult<BaseItemDto> - { - Items = returnList, - TotalRecordCount = itemsResult.Count - }; - - return result; - } - private static string[] GetRepresentativeItemTypes(string? contentType) { return contentType switch diff --git a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs b/Jellyfin.Api/Helpers/SimilarItemsHelper.cs deleted file mode 100644 index 6b06f87cd7..0000000000 --- a/Jellyfin.Api/Helpers/SimilarItemsHelper.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using MediaBrowser.Controller.Dto; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Querying; - -namespace Jellyfin.Api.Helpers -{ - /// <summary> - /// The similar items helper class. - /// </summary> - public static class SimilarItemsHelper - { - internal static QueryResult<BaseItemDto> GetSimilarItemsResult( - DtoOptions dtoOptions, - IUserManager userManager, - ILibraryManager libraryManager, - IDtoService dtoService, - Guid? userId, - string id, - string? excludeArtistIds, - int? limit, - Type[] includeTypes, - Func<BaseItem, List<PersonInfo>, List<PersonInfo>, BaseItem, int> getSimilarityScore) - { - var user = userId.HasValue && !userId.Equals(Guid.Empty) - ? userManager.GetUserById(userId.Value) - : null; - - var item = string.IsNullOrEmpty(id) ? - (!userId.Equals(Guid.Empty) ? libraryManager.GetUserRootFolder() : - libraryManager.RootFolder) : libraryManager.GetItemById(id); - - var query = new InternalItemsQuery(user) - { - IncludeItemTypes = includeTypes.Select(i => i.Name).ToArray(), - Recursive = true, - DtoOptions = dtoOptions, - ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds) - }; - - var inputItems = libraryManager.GetItemList(query); - - var items = GetSimilaritems(item, libraryManager, inputItems, getSimilarityScore) - .ToList(); - - var returnItems = items; - - if (limit.HasValue && limit < returnItems.Count) - { - returnItems = returnItems.GetRange(0, limit.Value); - } - - var dtos = dtoService.GetBaseItemDtos(returnItems, dtoOptions, user); - - return new QueryResult<BaseItemDto> - { - Items = dtos, - TotalRecordCount = items.Count - }; - } - - /// <summary> - /// Gets the similaritems. - /// </summary> - /// <param name="item">The item.</param> - /// <param name="libraryManager">The library manager.</param> - /// <param name="inputItems">The input items.</param> - /// <param name="getSimilarityScore">The get similarity score.</param> - /// <returns>IEnumerable{BaseItem}.</returns> - private static IEnumerable<BaseItem> GetSimilaritems( - BaseItem item, - ILibraryManager libraryManager, - IEnumerable<BaseItem> inputItems, - Func<BaseItem, List<PersonInfo>, List<PersonInfo>, BaseItem, int> getSimilarityScore) - { - var itemId = item.Id; - inputItems = inputItems.Where(i => i.Id != itemId); - var itemPeople = libraryManager.GetPeople(item); - var allPeople = libraryManager.GetPeople(new InternalPeopleQuery - { - AppearsInItemId = item.Id - }); - - return inputItems.Select(i => new Tuple<BaseItem, int>(i, getSimilarityScore(item, itemPeople, allPeople, i))) - .Where(i => i.Item2 > 2) - .OrderByDescending(i => i.Item2) - .Select(i => i.Item1); - } - - private static IEnumerable<string> GetTags(BaseItem item) - { - return item.Tags; - } - - /// <summary> - /// Gets the similiarity score. - /// </summary> - /// <param name="item1">The item1.</param> - /// <param name="item1People">The item1 people.</param> - /// <param name="allPeople">All people.</param> - /// <param name="item2">The item2.</param> - /// <returns>System.Int32.</returns> - internal static int GetSimiliarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2) - { - var points = 0; - - if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase)) - { - points += 10; - } - - // Find common genres - points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10); - - // Find common tags - points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10); - - // Find common studios - points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 3); - - var item2PeopleNames = allPeople.Where(i => i.ItemId == item2.Id) - .Select(i => i.Name) - .Where(i => !string.IsNullOrWhiteSpace(i)) - .DistinctNames() - .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); - - points += item1People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i => - { - if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase)) - { - return 5; - } - - if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase)) - { - return 3; - } - - if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase)) - { - return 3; - } - - if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase)) - { - return 3; - } - - if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase)) - { - return 2; - } - - return 1; - }); - - if (item1.ProductionYear.HasValue && item2.ProductionYear.HasValue) - { - var diff = Math.Abs(item1.ProductionYear.Value - item2.ProductionYear.Value); - - // Add if they came out within the same decade - if (diff < 10) - { - points += 2; - } - - // And more if within five years - if (diff < 5) - { - points += 2; - } - } - - return points; - } - } -} From b22831f7e551f11c0326a8b0977920f2250e0114 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 9 Nov 2020 14:53:23 -0700 Subject: [PATCH 0271/1930] Add ModelBinder to ImageType --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/GenresController.cs | 3 ++- Jellyfin.Api/Controllers/InstantMixController.cs | 15 ++++++++------- Jellyfin.Api/Controllers/ItemsController.cs | 6 +++--- Jellyfin.Api/Controllers/LiveTvController.cs | 11 ++++++----- Jellyfin.Api/Controllers/MusicGenresController.cs | 3 ++- Jellyfin.Api/Controllers/PersonsController.cs | 2 +- Jellyfin.Api/Controllers/PlaylistsController.cs | 3 ++- Jellyfin.Api/Controllers/StudiosController.cs | 3 ++- Jellyfin.Api/Controllers/TrailersController.cs | 4 ++-- Jellyfin.Api/Controllers/TvShowsController.cs | 9 +++++---- Jellyfin.Api/Controllers/UserLibraryController.cs | 3 ++- Jellyfin.Api/Controllers/YearsController.cs | 3 ++- 13 files changed, 39 insertions(+), 30 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 826fce6b0c..a35d7a556f 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -101,7 +101,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, @@ -310,7 +310,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 4e47658b06..f6e0772ec1 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -77,7 +78,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index 7f8a2be12e..2f342d0a8a 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -4,6 +4,7 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -72,7 +73,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -109,7 +110,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var album = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -146,7 +147,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var playlist = (Playlist)_libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -183,7 +184,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -219,7 +220,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -256,7 +257,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -293,7 +294,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var item = _libraryManager.GetItemById(id); var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 7ca5775438..adc95f7574 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -186,7 +186,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, - [FromQuery] ImageType[] imageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, [FromQuery] string? genres, @@ -195,7 +195,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, @@ -537,7 +537,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? mediaTypes, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] bool enableTotalRecordCount = true, diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 88a7542cee..31253cbbcd 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -14,6 +14,7 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LiveTvDtos; using Jellyfin.Data.Enums; using MediaBrowser.Common; @@ -146,7 +147,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isDisliked, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy, @@ -263,7 +264,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? seriesTimerId, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] bool? isMovie, @@ -350,7 +351,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? seriesTimerId, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) @@ -561,7 +562,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? genreIds, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] string? seriesTimerId, [FromQuery] Guid? librarySeriesId, @@ -705,7 +706,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isSports, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? genreIds, [FromQuery] string? fields, [FromQuery] bool? enableUserData, diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index e105befe8e..e434f190ac 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -77,7 +78,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 1e0bdb6bc7..80395950cf 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -76,7 +76,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isFavorite, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? excludePersonTypes, [FromQuery] string? personTypes, [FromQuery] string? appearsInItemId, diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 0419b2436b..f2213f20d8 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.PlaylistDtos; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Library; @@ -152,7 +153,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) { var playlist = (Playlist)_libraryManager.GetItemById(playlistId); if (playlist == null) diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index c5fcfb3569..c60d14479d 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -77,7 +78,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isFavorite, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 281c0016e9..6b4eee718b 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -151,7 +151,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] string? mediaTypes, - [FromQuery] ImageType[] imageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, [FromQuery] string? genres, @@ -160,7 +160,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, [FromQuery] string? personIds, [FromQuery] string? personTypes, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 49a6c386fe..55cdae39d0 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; @@ -78,7 +79,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { @@ -135,7 +136,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData) { var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -207,7 +208,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy) { @@ -326,7 +327,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? adjacentTo, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData) { var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index a52af17815..faa8a0634b 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -272,7 +273,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, [FromQuery] int limit = 20, [FromQuery] bool groupItems = true) diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 2c685309a6..1712a6a543 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -78,7 +79,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortBy, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, - [FromQuery] ImageType[] enableImageTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] Guid? userId, [FromQuery] bool recursive = true, [FromQuery] bool? enableImages = true) From 0dd2b169a3d9b0c1b31cd83b4022c729e28f0d3b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 9 Nov 2020 14:59:04 -0700 Subject: [PATCH 0272/1930] Add ModelBinder to ItemFilter --- Jellyfin.Api/Controllers/ArtistsController.cs | 4 ++-- Jellyfin.Api/Controllers/ChannelsController.cs | 4 ++-- Jellyfin.Api/Controllers/GenresController.cs | 3 ++- Jellyfin.Api/Controllers/InstantMixController.cs | 15 ++++++++------- Jellyfin.Api/Controllers/ItemsController.cs | 4 ++-- Jellyfin.Api/Controllers/LibraryController.cs | 3 ++- Jellyfin.Api/Controllers/LiveTvController.cs | 11 ++++++----- Jellyfin.Api/Controllers/MoviesController.cs | 3 ++- Jellyfin.Api/Controllers/MusicGenresController.cs | 3 ++- Jellyfin.Api/Controllers/PersonsController.cs | 2 +- Jellyfin.Api/Controllers/PlaylistsController.cs | 3 ++- Jellyfin.Api/Controllers/StudiosController.cs | 3 ++- Jellyfin.Api/Controllers/TrailersController.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 9 +++++---- Jellyfin.Api/Controllers/UserLibraryController.cs | 3 ++- Jellyfin.Api/Controllers/YearsController.cs | 3 ++- 16 files changed, 43 insertions(+), 32 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 4394abf9ef..f58c136ef8 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -88,7 +88,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, @@ -296,7 +296,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index b8df49a028..eed54105da 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -124,7 +124,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] string? sortBy, - [FromQuery] ItemFields[] fields) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields) { var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -197,7 +197,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? channelIds) { var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index a273c33dcb..468ad7b81b 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -72,7 +73,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] bool? isFavorite, diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index a4c91d1d8f..7d68e9ab45 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -4,6 +4,7 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -68,7 +69,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -104,7 +105,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -140,7 +141,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -176,7 +177,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string name, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -211,7 +212,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -247,7 +248,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -283,7 +284,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 2d98f91c80..3d939453e2 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -180,7 +180,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, @@ -532,7 +532,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? mediaTypes, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index e0f0bda26f..2eb8363d7c 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -12,6 +12,7 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LibraryDtos; using Jellyfin.Data.Entities; using MediaBrowser.Common.Progress; @@ -693,7 +694,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? excludeArtistIds, [FromQuery] Guid? userId, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields) { var item = itemId.Equals(Guid.Empty) ? (!userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index dc1dca1941..2edfffa483 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -14,6 +14,7 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LiveTvDtos; using Jellyfin.Data.Enums; using MediaBrowser.Common; @@ -147,7 +148,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] string? sortBy, [FromQuery] SortOrder? sortOrder, @@ -263,7 +264,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool? isMovie, [FromQuery] bool? isSeries, @@ -349,7 +350,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { @@ -563,7 +564,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] string? seriesTimerId, [FromQuery] Guid? librarySeriesId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool enableTotalRecordCount = true) { var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -703,7 +704,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageTypeLimit, [FromQuery] ImageType[] enableImageTypes, [FromQuery] string? genreIds, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) { diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index b37c3f0b35..ebc148fe56 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; @@ -65,7 +66,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<IEnumerable<RecommendationDto>> GetMovieRecommendations( [FromQuery] Guid? userId, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] int categoryLimit = 5, [FromQuery] int itemLimit = 8) { diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 1af3bbccc9..7e122e7549 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -72,7 +73,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] bool? isFavorite, diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index fcba75e67b..6c5b346cb7 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -71,7 +71,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryResult<BaseItemDto>> GetPersons( [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery] bool? enableUserData, diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index a1c8219ca9..07d3658cad 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.PlaylistDtos; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Library; @@ -148,7 +149,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] Guid userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableImages, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index bda1c0b2f3..99e6b7c8e5 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -71,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? searchTerm, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] bool? isFavorite, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 0806dc3e8a..9532df42fd 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -146,7 +146,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index e07e906001..901aeb43fb 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; @@ -73,7 +74,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? seriesId, [FromQuery] string? parentId, [FromQuery] bool? enableImges, @@ -130,7 +131,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, @@ -195,7 +196,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryResult<BaseItemDto>> GetEpisodes( [FromRoute, Required] string seriesId, [FromQuery] Guid? userId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] int? season, [FromQuery] string? seasonId, [FromQuery] bool? isMissing, @@ -317,7 +318,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryResult<BaseItemDto>> GetSeasons( [FromRoute, Required] string seriesId, [FromQuery] Guid? userId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? isSpecialSeason, [FromQuery] bool? isMissing, [FromQuery] string? adjacentTo, diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index ff68cd497b..fd11adf9c5 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -267,7 +268,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<IEnumerable<BaseItemDto>> GetLatestMedia( [FromRoute, Required] Guid userId, [FromQuery] Guid? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? includeItemTypes, [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 0b4a2776b2..e146b69593 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -5,6 +5,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -71,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? sortOrder, [FromQuery] string? parentId, - [FromQuery] ItemFields[] fields, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? excludeItemTypes, [FromQuery] string? includeItemTypes, [FromQuery] string? mediaTypes, From 2ce9a56cae36f2538f6a3df7d1c46f65e39750bc Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 9 Nov 2020 15:01:30 -0700 Subject: [PATCH 0273/1930] Remove GetImageTypes --- Jellyfin.Api/Helpers/RequestHelpers.cs | 27 -------------------------- 1 file changed, 27 deletions(-) diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 49632dd01a..13d6da3174 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -165,33 +165,6 @@ namespace Jellyfin.Api.Helpers .ToArray(); } - /// <summary> - /// Gets the item fields. - /// </summary> - /// <param name="imageTypes">The image types string.</param> - /// <returns>IEnumerable{ItemFields}.</returns> - internal static ImageType[] GetImageTypes(string? imageTypes) - { - if (string.IsNullOrEmpty(imageTypes)) - { - return Array.Empty<ImageType>(); - } - - return Split(imageTypes, ',', true) - .Select(v => - { - if (Enum.TryParse(v, true, out ImageType value)) - { - return (ImageType?)value; - } - - return null; - }) - .Where(i => i.HasValue) - .Select(i => i!.Value) - .ToArray(); - } - internal static QueryResult<BaseItemDto> CreateQueryResult( QueryResult<(BaseItem, ItemCounts)> result, DtoOptions dtoOptions, From 477e7f78985372297f3611f47c932da6448d27d9 Mon Sep 17 00:00:00 2001 From: Fardin <fardinarafat30@gmail.com> Date: Mon, 9 Nov 2020 18:58:04 +0000 Subject: [PATCH 0274/1930] Translated using Weblate (Spanish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es/ --- Emby.Server.Implementations/Localization/Core/es.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json index 60abc08d40..d6af40c409 100644 --- a/Emby.Server.Implementations/Localization/Core/es.json +++ b/Emby.Server.Implementations/Localization/Core/es.json @@ -113,5 +113,7 @@ "TaskRefreshChannels": "Actualizar canales", "TaskRefreshChannelsDescription": "Actualiza la información de los canales de internet.", "TaskDownloadMissingSubtitles": "Descargar los subtítulos que faltan", - "TaskDownloadMissingSubtitlesDescription": "Busca en internet los subtítulos que falten en el contenido de tus bibliotecas, basándose en la configuración de los metadatos." + "TaskDownloadMissingSubtitlesDescription": "Busca en internet los subtítulos que falten en el contenido de tus bibliotecas, basándose en la configuración de los metadatos.", + "TaskCleanActivityLogDescription": "Elimina todos los registros de actividad anteriores a la fecha configurada.", + "TaskCleanActivityLog": "Limpiar registro de actividad" } From 103d503c1501436d855a774bc83ef656d68d587f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Mon, 9 Nov 2020 21:46:18 +0100 Subject: [PATCH 0275/1930] Removed code as suggested by @cvium --- .../Manager/MetadataService.cs | 29 +++++-------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index a507bd4a6d..dca8acb7d8 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -252,7 +252,13 @@ namespace MediaBrowser.Providers.Manager if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) { - await AddPersonImageAsync(personEntity, libraryOptions, person.ImageUrl, cancellationToken).ConfigureAwait(false); + personEntity.SetImage( + new ItemImageInfo + { + Path = person.ImageUrl, + Type = ImageType.Primary + }, + 0); saveEntity = true; updateType |= ItemUpdateType.ImageUpdate; @@ -266,27 +272,6 @@ namespace MediaBrowser.Providers.Manager } } - private async Task AddPersonImageAsync(Person personEntity, LibraryOptions libraryOptions, string imageUrl, CancellationToken cancellationToken) - { - try - { - await ProviderManager.SaveImage(personEntity, imageUrl, ImageType.Primary, null, cancellationToken).ConfigureAwait(false); - return; - } - catch (Exception ex) - { - Logger.LogError(ex, "Error in AddPersonImage"); - } - - personEntity.SetImage( - new ItemImageInfo - { - Path = imageUrl, - Type = ImageType.Primary - }, - 0); - } - protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) { item.AfterMetadataRefresh(); From d6a04fd406a4aa7d7fd40e3b8183c10c8d7e150f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Tue, 10 Nov 2020 00:20:12 +0100 Subject: [PATCH 0276/1930] Remove setting from existing libraries with a migration --- Jellyfin.Server/Migrations/MigrationRunner.cs | 3 +- .../Routines/RemoveDownloadImagesInAdvance.cs | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index 844dae61f6..aca1654084 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -23,7 +23,8 @@ namespace Jellyfin.Server.Migrations typeof(Routines.AddDefaultPluginRepository), typeof(Routines.MigrateUserDb), typeof(Routines.ReaddDefaultPluginRepository), - typeof(Routines.MigrateDisplayPreferencesDb) + typeof(Routines.MigrateDisplayPreferencesDb), + typeof(Routines.RemoveDownloadImagesInAdvance) }; /// <summary> diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs new file mode 100644 index 0000000000..b31deba844 --- /dev/null +++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs @@ -0,0 +1,46 @@ +using System; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Migrations.Routines +{ + /// <summary> + /// Removes the old 'RemoveDownloadImagesInAdvance' from library options. + /// </summary> + internal class RemoveDownloadImagesInAdvance : IMigrationRoutine + { + private readonly ILogger<RemoveDownloadImagesInAdvance> _logger; + private readonly ILibraryManager _libraryManager; + + public RemoveDownloadImagesInAdvance(ILogger<RemoveDownloadImagesInAdvance> logger, ILibraryManager libraryManager) + { + _logger = logger; + _libraryManager = libraryManager; + } + + /// <inheritdoc/> + public Guid Id => Guid.Parse("{A81F75E0-8F43-416F-A5E8-516CCAB4D8CC}"); + + /// <inheritdoc/> + public string Name => "RemoveDownloadImagesInAdvance"; + + /// <inheritdoc/> + public bool PerformOnNewInstall => false; + + /// <inheritdoc/> + public void Perform() + { + var virtual_folders = _libraryManager.GetVirtualFolders(false); + _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries"); + foreach (var virtual_folder in virtual_folders) + { + var library_options = virtual_folder.LibraryOptions; + var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(virtual_folder.ItemId); + // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed. + collectionFolder.UpdateLibraryOptions(library_options); + _logger.LogInformation("Removed from '{VirtualFolder}'", virtual_folder.Name); + } + } + } +} From 27a1337cf3bea291a5f0be5fca9d8ee3470df525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Tue, 10 Nov 2020 10:24:05 +0100 Subject: [PATCH 0277/1930] Remove underscore Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- .../Routines/RemoveDownloadImagesInAdvance.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs index b31deba844..42b87ec5f5 100644 --- a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs +++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs @@ -31,15 +31,15 @@ namespace Jellyfin.Server.Migrations.Routines /// <inheritdoc/> public void Perform() { - var virtual_folders = _libraryManager.GetVirtualFolders(false); + var virtualFolders = _libraryManager.GetVirtualFolders(false); _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries"); - foreach (var virtual_folder in virtual_folders) + foreach (var virtualFolder in virtualFolders) { - var library_options = virtual_folder.LibraryOptions; - var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(virtual_folder.ItemId); + var libraryOptions = virtualFolder.LibraryOptions; + var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(virtualFolder.ItemId); // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed. - collectionFolder.UpdateLibraryOptions(library_options); - _logger.LogInformation("Removed from '{VirtualFolder}'", virtual_folder.Name); + collectionFolder.UpdateLibraryOptions(libraryOptions); + _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name); } } } From 693760e38ae51b9267f9383c3957df742bb136a6 Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Tue, 10 Nov 2020 17:11:48 +0100 Subject: [PATCH 0278/1930] Xml-doc part1 --- Emby.Naming/Audio/AlbumParser.cs | 15 ++++++-- Emby.Naming/Audio/AudioFileParser.cs | 12 ++++-- .../AudioBook/AudioBookFilePathParser.cs | 15 ++++++-- .../AudioBookFilePathParserResult.cs | 12 ++++-- .../AudioBook/AudioBookListResolver.cs | 14 ++++++- Emby.Naming/AudioBook/AudioBookNameParser.cs | 15 ++++++-- .../AudioBook/AudioBookNameParserResult.cs | 12 ++++-- Emby.Naming/AudioBook/AudioBookResolver.cs | 15 ++++++-- Emby.Naming/Common/EpisodeExpression.cs | 38 +++++++++++++++---- Emby.Naming/Common/MediaType.cs | 2 - Emby.Naming/Common/NamingOptions.cs | 2 - Emby.Naming/Subtitles/SubtitleInfo.cs | 2 - Emby.Naming/Subtitles/SubtitleParser.cs | 3 -- Emby.Naming/TV/EpisodeInfo.cs | 30 ++++++++++++++- Emby.Naming/TV/EpisodePathParser.cs | 20 ++++++++-- Emby.Naming/TV/EpisodePathParserResult.cs | 33 +++++++++++++++- Emby.Naming/TV/EpisodeResolver.cs | 3 -- Emby.Naming/TV/SeasonPathParser.cs | 2 - Emby.Naming/TV/SeasonPathParserResult.cs | 2 - Emby.Naming/Video/CleanDateTimeParser.cs | 9 +++-- Emby.Naming/Video/CleanDateTimeResult.cs | 19 +++++----- Emby.Naming/Video/CleanStringParser.cs | 10 +++-- Emby.Naming/Video/ExtraResolver.cs | 3 -- Emby.Naming/Video/ExtraResult.cs | 2 - Emby.Naming/Video/ExtraRule.cs | 2 - Emby.Naming/Video/ExtraRuleType.cs | 5 ++- Emby.Naming/Video/FileStack.cs | 2 - Emby.Naming/Video/FlagParser.cs | 2 - Emby.Naming/Video/Format3DParser.cs | 2 - Emby.Naming/Video/Format3DResult.cs | 2 - Emby.Naming/Video/Format3DRule.cs | 2 - Emby.Naming/Video/StackResolver.cs | 2 - Emby.Naming/Video/StubResolver.cs | 3 -- Emby.Naming/Video/StubTypeRule.cs | 2 - Emby.Naming/Video/VideoListResolver.cs | 2 - Emby.Naming/Video/VideoResolver.cs | 3 -- 36 files changed, 218 insertions(+), 101 deletions(-) diff --git a/Emby.Naming/Audio/AlbumParser.cs b/Emby.Naming/Audio/AlbumParser.cs index b63be3a647..bbfdccc902 100644 --- a/Emby.Naming/Audio/AlbumParser.cs +++ b/Emby.Naming/Audio/AlbumParser.cs @@ -1,6 +1,3 @@ -#nullable enable -#pragma warning disable CS1591 - using System; using System.Globalization; using System.IO; @@ -9,15 +6,27 @@ using Emby.Naming.Common; namespace Emby.Naming.Audio { + /// <summary> + /// Helper class to determine if Album is multipart. + /// </summary> public class AlbumParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="AlbumParser"/> class. + /// </summary> + /// <param name="options">Naming options containing AlbumStackingPrefixes.</param> public AlbumParser(NamingOptions options) { _options = options; } + /// <summary> + /// Function that determines if album is multipart. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>True if album is multipart.</returns> public bool IsMultiPart(string path) { var filename = Path.GetFileName(path); diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs index 6b2f4be93e..8b47dd12e4 100644 --- a/Emby.Naming/Audio/AudioFileParser.cs +++ b/Emby.Naming/Audio/AudioFileParser.cs @@ -1,6 +1,3 @@ -#nullable enable -#pragma warning disable CS1591 - using System; using System.IO; using System.Linq; @@ -8,8 +5,17 @@ using Emby.Naming.Common; namespace Emby.Naming.Audio { + /// <summary> + /// Static helper class to determine if file at path is audio file. + /// </summary> public static class AudioFileParser { + /// <summary> + /// Static helper method to determine if file at path is audio file. + /// </summary> + /// <param name="path">Path to file.</param> + /// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions.</param> + /// <returns>True if file at path is audio file.</returns> public static bool IsAudioFile(string path, NamingOptions options) { var extension = Path.GetExtension(path); diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs index 56580f194b..7b4429ab15 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParser.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParser.cs @@ -1,6 +1,3 @@ -#nullable enable -#pragma warning disable CS1591 - using System.Globalization; using System.IO; using System.Text.RegularExpressions; @@ -8,15 +5,27 @@ using Emby.Naming.Common; namespace Emby.Naming.AudioBook { + /// <summary> + /// Parser class to extract part and/or chapter number from audiobook filename. + /// </summary> public class AudioBookFilePathParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="AudioBookFilePathParser"/> class. + /// </summary> + /// <param name="options">Naming options containing AudioBookPartsExpressions.</param> public AudioBookFilePathParser(NamingOptions options) { _options = options; } + /// <summary> + /// Based on regex determines if filename includes part/chapter number. + /// </summary> + /// <param name="path">Path to audiobook file.</param> + /// <returns>Returns <see cref="AudioBookFilePathParser"/> object.</returns> public AudioBookFilePathParserResult Parse(string path) { AudioBookFilePathParserResult result = default; diff --git a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs index b65d231dfd..48ab8b57dc 100644 --- a/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs +++ b/Emby.Naming/AudioBook/AudioBookFilePathParserResult.cs @@ -1,12 +1,18 @@ -#nullable enable -#pragma warning disable CS1591 - namespace Emby.Naming.AudioBook { + /// <summary> + /// Data object for passing result of audiobook part/chapter extraction. + /// </summary> public struct AudioBookFilePathParserResult { + /// <summary> + /// Gets or sets optional number of path extracted from audiobook filename. + /// </summary> public int? PartNumber { get; set; } + /// <summary> + /// Gets or sets optional number of chapter extracted from audiobook filename. + /// </summary> public int? ChapterNumber { get; set; } } } diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index e8908aa37c..b203f99022 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; using System.IO; @@ -10,15 +8,27 @@ using MediaBrowser.Model.IO; namespace Emby.Naming.AudioBook { + /// <summary> + /// Class used to resolve Name, Year, alternative files and extras from stack of files. + /// </summary> public class AudioBookListResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="AudioBookListResolver"/> class. + /// </summary> + /// <param name="options">Naming options passed along to <see cref="AudioBookResolver"/> and <see cref="AudioBookNameParser"/>.</param> public AudioBookListResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Resolves Name, Year and differentiate alternative files and extras from regular audiobook files. + /// </summary> + /// <param name="files">List of files related to audiobook.</param> + /// <returns>Returns IEnumerable of <see cref="AudioBookInfo"/>.</returns> public IEnumerable<AudioBookInfo> Resolve(IEnumerable<FileSystemMetadata> files) { var audioBookResolver = new AudioBookResolver(_options); diff --git a/Emby.Naming/AudioBook/AudioBookNameParser.cs b/Emby.Naming/AudioBook/AudioBookNameParser.cs index 7c86161241..120482bc2c 100644 --- a/Emby.Naming/AudioBook/AudioBookNameParser.cs +++ b/Emby.Naming/AudioBook/AudioBookNameParser.cs @@ -1,21 +1,30 @@ -#nullable enable -#pragma warning disable CS1591 - using System.Globalization; using System.Text.RegularExpressions; using Emby.Naming.Common; namespace Emby.Naming.AudioBook { + /// <summary> + /// Helper class to retrieve name and year from audiobook previously retrieved name. + /// </summary> public class AudioBookNameParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="AudioBookNameParser"/> class. + /// </summary> + /// <param name="options">Naming options containing AudioBookNamesExpressions.</param> public AudioBookNameParser(NamingOptions options) { _options = options; } + /// <summary> + /// Parse name and year from previously determined name of audiobook. + /// </summary> + /// <param name="name">Name of the audiobook.</param> + /// <returns>Returns <see cref="AudioBookNameParserResult"/> object.</returns> public AudioBookNameParserResult Parse(string name) { AudioBookNameParserResult result = default; diff --git a/Emby.Naming/AudioBook/AudioBookNameParserResult.cs b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs index b28e259dda..3f2d7b2b0b 100644 --- a/Emby.Naming/AudioBook/AudioBookNameParserResult.cs +++ b/Emby.Naming/AudioBook/AudioBookNameParserResult.cs @@ -1,12 +1,18 @@ -#nullable enable -#pragma warning disable CS1591 - namespace Emby.Naming.AudioBook { + /// <summary> + /// Data object used to pass result of name and year parsing. + /// </summary> public struct AudioBookNameParserResult { + /// <summary> + /// Gets or sets name of audiobook. + /// </summary> public string Name { get; set; } + /// <summary> + /// Gets or sets optional year of release. + /// </summary> public int? Year { get; set; } } } diff --git a/Emby.Naming/AudioBook/AudioBookResolver.cs b/Emby.Naming/AudioBook/AudioBookResolver.cs index c7b3b2d2d1..f6ad3601d7 100644 --- a/Emby.Naming/AudioBook/AudioBookResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookResolver.cs @@ -1,6 +1,3 @@ -#nullable enable -#pragma warning disable CS1591 - using System; using System.IO; using System.Linq; @@ -8,15 +5,27 @@ using Emby.Naming.Common; namespace Emby.Naming.AudioBook { + /// <summary> + /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file. + /// </summary> public class AudioBookResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="AudioBookResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions and also used to pass to AudioBookFilePathParser.</param> public AudioBookResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file. + /// </summary> + /// <param name="path">Path to audiobook file.</param> + /// <returns>Returns <see cref="AudioBookResolver"/> object.</returns> public AudioBookFileInfo? Resolve(string path) { if (path.Length == 0 || Path.GetFileNameWithoutExtension(path).Length == 0) diff --git a/Emby.Naming/Common/EpisodeExpression.cs b/Emby.Naming/Common/EpisodeExpression.cs index 00b27541a6..19d3c7aab0 100644 --- a/Emby.Naming/Common/EpisodeExpression.cs +++ b/Emby.Naming/Common/EpisodeExpression.cs @@ -1,16 +1,22 @@ -#pragma warning disable CS1591 - using System; using System.Text.RegularExpressions; namespace Emby.Naming.Common { + /// <summary> + /// Regular expressions for parsing TV Episodes. + /// </summary> public class EpisodeExpression { private string _expression; private Regex? _regex; - public EpisodeExpression(string expression, bool byDate) + /// <summary> + /// Initializes a new instance of the <see cref="EpisodeExpression"/> class. + /// </summary> + /// <param name="expression">Regular expressions.</param> + /// <param name="byDate">True if date is expected.</param> + public EpisodeExpression(string expression, bool byDate = false) { _expression = expression; IsByDate = byDate; @@ -18,11 +24,9 @@ namespace Emby.Naming.Common SupportsAbsoluteEpisodeNumbers = true; } - public EpisodeExpression(string expression) - : this(expression, false) - { - } - + /// <summary> + /// Gets or sets raw expressions string. + /// </summary> public string Expression { get => _expression; @@ -33,16 +37,34 @@ namespace Emby.Naming.Common } } + /// <summary> + /// Gets or sets a value indicating whether gets or sets property indicating if date can be find in expression. + /// </summary> public bool IsByDate { get; set; } + /// <summary> + /// Gets or sets a value indicating whether gets or sets property indicating if expression is optimistic. + /// </summary> public bool IsOptimistic { get; set; } + /// <summary> + /// Gets or sets a value indicating whether gets or sets property indicating if expression is named. + /// </summary> public bool IsNamed { get; set; } + /// <summary> + /// Gets or sets a value indicating whether gets or sets property indicating if expression supports episodes with absolute numbers. + /// </summary> public bool SupportsAbsoluteEpisodeNumbers { get; set; } + /// <summary> + /// Gets or sets optional list of date formats used for date parsing. + /// </summary> public string[] DateTimeFormats { get; set; } + /// <summary> + /// Gets a <see cref="Regex"/> expressions objects (creates it if null). + /// </summary> public Regex Regex => _regex ??= new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled); } } diff --git a/Emby.Naming/Common/MediaType.cs b/Emby.Naming/Common/MediaType.cs index 148833765f..1231b18871 100644 --- a/Emby.Naming/Common/MediaType.cs +++ b/Emby.Naming/Common/MediaType.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.Common { public enum MediaType diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 471491d22c..0f02c03cbb 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Linq; using System.Text.RegularExpressions; diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs index 2f16fb2df9..62cc3ead17 100644 --- a/Emby.Naming/Subtitles/SubtitleInfo.cs +++ b/Emby.Naming/Subtitles/SubtitleInfo.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.Subtitles { public class SubtitleInfo diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index c8659e1b26..476a83cf35 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -1,6 +1,3 @@ -#nullable enable -#pragma warning disable CS1591 - using System; using System.IO; using System.Linq; diff --git a/Emby.Naming/TV/EpisodeInfo.cs b/Emby.Naming/TV/EpisodeInfo.cs index e01c810628..a8920b36ae 100644 --- a/Emby.Naming/TV/EpisodeInfo.cs +++ b/Emby.Naming/TV/EpisodeInfo.cs @@ -1,9 +1,14 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.TV { + /// <summary> + /// Holder object for Episode information. + /// </summary> public class EpisodeInfo { + /// <summary> + /// Initializes a new instance of the <see cref="EpisodeInfo"/> class. + /// </summary> + /// <param name="path">Path to the file.</param> public EpisodeInfo(string path) { Path = path; @@ -51,18 +56,39 @@ namespace Emby.Naming.TV /// <value>The type of the stub.</value> public string? StubType { get; set; } + /// <summary> + /// Gets or sets optional season number. + /// </summary> public int? SeasonNumber { get; set; } + /// <summary> + /// Gets or sets optional episode number. + /// </summary> public int? EpisodeNumber { get; set; } + /// <summary> + /// Gets or sets optional ending episode number. For multi-episode files 1-13. + /// </summary> public int? EndingEpisodeNumber { get; set; } + /// <summary> + /// Gets or sets optional year of release. + /// </summary> public int? Year { get; set; } + /// <summary> + /// Gets or sets optional year of release. + /// </summary> public int? Month { get; set; } + /// <summary> + /// Gets or sets optional day of release. + /// </summary> public int? Day { get; set; } + /// <summary> + /// Gets or sets a value indicating whether by date expression was used. + /// </summary> public bool IsByDate { get; set; } } } diff --git a/Emby.Naming/TV/EpisodePathParser.cs b/Emby.Naming/TV/EpisodePathParser.cs index d9cc8172bd..6d0597356b 100644 --- a/Emby.Naming/TV/EpisodePathParser.cs +++ b/Emby.Naming/TV/EpisodePathParser.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System; using System.Collections.Generic; using System.Globalization; @@ -9,15 +6,32 @@ using Emby.Naming.Common; namespace Emby.Naming.TV { + /// <summary> + /// Used to parse information about episode from path. + /// </summary> public class EpisodePathParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="EpisodePathParser"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing EpisodeExpressions and MultipleEpisodeExpressions.</param> public EpisodePathParser(NamingOptions options) { _options = options; } + /// <summary> + /// Parses information about episode from path. + /// </summary> + /// <param name="path">Path.</param> + /// <param name="isDirectory">Is path for a directory or file.</param> + /// <param name="isNamed">Do we want to use IsNamed expressions.</param> + /// <param name="isOptimistic">Do we want to use Optimistic expressions.</param> + /// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param> + /// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param> + /// <returns>Returns <see cref="EpisodePathParserResult"/> object.</returns> public EpisodePathParserResult Parse( string path, bool isDirectory, diff --git a/Emby.Naming/TV/EpisodePathParserResult.cs b/Emby.Naming/TV/EpisodePathParserResult.cs index 5fa0b6f0b4..233d5a4f6c 100644 --- a/Emby.Naming/TV/EpisodePathParserResult.cs +++ b/Emby.Naming/TV/EpisodePathParserResult.cs @@ -1,25 +1,54 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.TV { + /// <summary> + /// Holder object for <see cref="EpisodePathParser"/> result. + /// </summary> public class EpisodePathParserResult { + /// <summary> + /// Gets or sets optional season number. + /// </summary> public int? SeasonNumber { get; set; } + /// <summary> + /// Gets or sets optional episode number. + /// </summary> public int? EpisodeNumber { get; set; } + /// <summary> + /// Gets or sets optional ending episode number. For multi-episode files 1-13. + /// </summary> public int? EndingEpisodeNumber { get; set; } + /// <summary> + /// Gets or sets the name of the series. + /// </summary> + /// <value>The name of the series.</value> public string? SeriesName { get; set; } + /// <summary> + /// Gets or sets a value indicating whether parsing was successful. + /// </summary> public bool Success { get; set; } + /// <summary> + /// Gets or sets a value indicating whether by date expression was used. + /// </summary> public bool IsByDate { get; set; } + /// <summary> + /// Gets or sets optional year of release. + /// </summary> public int? Year { get; set; } + /// <summary> + /// Gets or sets optional year of release. + /// </summary> public int? Month { get; set; } + /// <summary> + /// Gets or sets optional day of release. + /// </summary> public int? Day { get; set; } } } diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 5f02c553de..26dd6915b9 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System; using System.IO; using System.Linq; diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index 142680f0cd..cf99097bc4 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Globalization; using System.IO; diff --git a/Emby.Naming/TV/SeasonPathParserResult.cs b/Emby.Naming/TV/SeasonPathParserResult.cs index a142fafea0..f52f941a7c 100644 --- a/Emby.Naming/TV/SeasonPathParserResult.cs +++ b/Emby.Naming/TV/SeasonPathParserResult.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.TV { public class SeasonPathParserResult diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index f05d540f8b..0ee633dcc6 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; @@ -12,6 +9,12 @@ namespace Emby.Naming.Video /// </summary> public static class CleanDateTimeParser { + /// <summary> + /// Attempts to clean the name. + /// </summary> + /// <param name="name">Name of video.</param> + /// <param name="cleanDateTimeRegexes">Optional list of regexes to clean the name.</param> + /// <returns>Returns <see cref="CleanDateTimeResult"/> object.</returns> public static CleanDateTimeResult Clean(string name, IReadOnlyList<Regex> cleanDateTimeRegexes) { CleanDateTimeResult result = new CleanDateTimeResult(name); diff --git a/Emby.Naming/Video/CleanDateTimeResult.cs b/Emby.Naming/Video/CleanDateTimeResult.cs index 57eeaa7e32..c675a19d0f 100644 --- a/Emby.Naming/Video/CleanDateTimeResult.cs +++ b/Emby.Naming/Video/CleanDateTimeResult.cs @@ -1,22 +1,21 @@ -#pragma warning disable CS1591 -#nullable enable - namespace Emby.Naming.Video { + /// <summary> + /// Holder structure for name and year. + /// </summary> public readonly struct CleanDateTimeResult { - public CleanDateTimeResult(string name, int? year) + /// <summary> + /// Initializes a new instance of the <see cref="CleanDateTimeResult"/> struct. + /// </summary> + /// <param name="name">Name of video.</param> + /// <param name="year">Year of release.</param> + public CleanDateTimeResult(string name, int? year = null) { Name = name; Year = year; } - public CleanDateTimeResult(string name) - { - Name = name; - Year = null; - } - /// <summary> /// Gets the name. /// </summary> diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index 3f584d5847..09a0cd1893 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -12,6 +9,13 @@ namespace Emby.Naming.Video /// </summary> public static class CleanStringParser { + /// <summary> + /// Attempts to extract clean name with regular expressions. + /// </summary> + /// <param name="name">Name of file.</param> + /// <param name="expressions">List of regex to parse name and year from.</param> + /// <param name="newName">Parsing result string.</param> + /// <returns>True if parsing was successful.</returns> public static bool TryClean(string name, IReadOnlyList<Regex> expressions, out ReadOnlySpan<char> newName) { var len = expressions.Count; diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index bd78299dcd..98ea342acc 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -1,9 +1,6 @@ -#pragma warning disable CS1591 - using System; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using Emby.Naming.Audio; using Emby.Naming.Common; diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs index 6be7e60525..f3b8d2a2fc 100644 --- a/Emby.Naming/Video/ExtraResult.cs +++ b/Emby.Naming/Video/ExtraResult.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using MediaBrowser.Model.Entities; namespace Emby.Naming.Video diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs index c018894fdf..a93474bc69 100644 --- a/Emby.Naming/Video/ExtraRule.cs +++ b/Emby.Naming/Video/ExtraRule.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using MediaBrowser.Model.Entities; using MediaType = Emby.Naming.Common.MediaType; diff --git a/Emby.Naming/Video/ExtraRuleType.cs b/Emby.Naming/Video/ExtraRuleType.cs index 98114c7e8b..3243195057 100644 --- a/Emby.Naming/Video/ExtraRuleType.cs +++ b/Emby.Naming/Video/ExtraRuleType.cs @@ -1,7 +1,8 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.Video { + /// <summary> + /// Extra rules type to determine against what <see cref="ExtraRule.Token"/> should be matched. + /// </summary> public enum ExtraRuleType { /// <summary> diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs index b0a22b18b0..75620e9610 100644 --- a/Emby.Naming/Video/FileStack.cs +++ b/Emby.Naming/Video/FileStack.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs index 6015c41a0c..cd15b4666f 100644 --- a/Emby.Naming/Video/FlagParser.cs +++ b/Emby.Naming/Video/FlagParser.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.IO; using Emby.Naming.Common; diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index fb881f978f..73ad36af46 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Linq; using Emby.Naming.Common; diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs index 36dc1c12b2..539060c982 100644 --- a/Emby.Naming/Video/Format3DResult.cs +++ b/Emby.Naming/Video/Format3DResult.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System.Collections.Generic; namespace Emby.Naming.Video diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs index 7679164b30..bee5c109e1 100644 --- a/Emby.Naming/Video/Format3DRule.cs +++ b/Emby.Naming/Video/Format3DRule.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.Video { public class Format3DRule diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index 30b812e21d..d6de468cc9 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index b0eb92e53e..6241a46b03 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System; using System.IO; using System.Linq; diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs index fa42af6049..df2d3c7d22 100644 --- a/Emby.Naming/Video/StubTypeRule.cs +++ b/Emby.Naming/Video/StubTypeRule.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace Emby.Naming.Video { public class StubTypeRule diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index be9b4959a7..dda3225217 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index fed567d03d..31b47cdf15 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,6 +1,3 @@ -#pragma warning disable CS1591 -#nullable enable - using System; using System.IO; using System.Linq; From 83629ab6f24ee1a8991dae2b8a55d24c93832ad5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 10 Nov 2020 09:52:34 -0700 Subject: [PATCH 0279/1930] Update packages to net5 --- DvdLib/DvdLib.csproj | 2 +- Emby.Dlna/Emby.Dlna.csproj | 2 +- Emby.Drawing/Emby.Drawing.csproj | 2 +- Emby.Naming/Emby.Naming.csproj | 2 +- Emby.Notifications/Emby.Notifications.csproj | 2 +- Emby.Photos/Emby.Photos.csproj | 2 +- .../Emby.Server.Implementations.csproj | 12 ++++++------ Jellyfin.Api/Jellyfin.Api.csproj | 6 +++--- Jellyfin.Data/Jellyfin.Data.csproj | 6 +++--- Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj | 2 +- .../Jellyfin.Server.Implementations.csproj | 8 ++++---- Jellyfin.Server/Jellyfin.Server.csproj | 10 +++++----- MediaBrowser.Common/MediaBrowser.Common.csproj | 6 +++--- .../MediaBrowser.Controller.csproj | 6 +++--- .../MediaBrowser.LocalMetadata.csproj | 2 +- .../MediaBrowser.MediaEncoding.csproj | 4 ++-- MediaBrowser.Model/Extensions/StringHelper.cs | 6 ------ MediaBrowser.Model/MediaBrowser.Model.csproj | 8 ++++---- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 8 ++++---- .../MediaBrowser.XbmcMetadata.csproj | 2 +- RSSDP/RSSDP.csproj | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 6 +++--- .../Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- .../Jellyfin.Naming.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 27 files changed, 55 insertions(+), 61 deletions(-) diff --git a/DvdLib/DvdLib.csproj b/DvdLib/DvdLib.csproj index 64d041cb05..7bbd9acf82 100644 --- a/DvdLib/DvdLib.csproj +++ b/DvdLib/DvdLib.csproj @@ -10,7 +10,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index 6ed49944c0..bd30cc1e11 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -17,7 +17,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 092f8580a6..7d479a5c65 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 6857f9952c..80800840ee 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 1d430a5e58..16ee918c46 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index dbe01257f4..62e33e6c44 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -19,7 +19,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index c762aa0b84..bcddea281c 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -32,13 +32,13 @@ <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> <PackageReference Include="Mono.Nat" Version="3.0.0" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.0" /> - <PackageReference Include="ServiceStack.Text.Core" Version="5.9.2" /> + <PackageReference Include="ServiceStack.Text.Core" Version="5.10.0" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="2.1.0" /> <PackageReference Include="DotNet.Glob" Version="3.1.0" /> @@ -49,7 +49,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release'">true</TreatWarningsAsErrors> diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index da0852cebc..2836f7b0ae 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> @@ -14,9 +14,9 @@ <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.9" /> + <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> <PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="5.6.3" /> </ItemGroup> diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 5038988f96..9ae129d072 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> @@ -41,8 +41,8 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.9" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.9" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" /> </ItemGroup> <ItemGroup> diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index c11ac5fb37..466a12e676 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index c52be3b8a9..e663798da0 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> @@ -24,12 +24,12 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="System.Linq.Async" Version="4.1.1" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.9"> + <PackageReference Include="System.Linq.Async" Version="5.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9"> + <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 3558f144cf..03d06fdff3 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -8,7 +8,7 @@ <PropertyGroup> <AssemblyName>jellyfin</AssemblyName> <OutputType>Exe</OutputType> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> @@ -38,10 +38,10 @@ <ItemGroup> <PackageReference Include="CommandLineParser" Version="2.8.0" /> - <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="5.0.0" /> <PackageReference Include="prometheus-net" Version="4.0.0" /> <PackageReference Include="prometheus-net.AspNetCore" Version="4.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index e716a6610f..b67a549835 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -18,8 +18,8 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> <PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.8" /> </ItemGroup> @@ -29,7 +29,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 4374317d67..9acc98dcec 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -14,8 +14,8 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="5.0.0" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> </ItemGroup> @@ -29,7 +29,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release' ">true</TreatWarningsAsErrors> diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index 529e7065cd..3ce9ff4cc4 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -11,7 +11,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 6ead93e09b..7bb2a7d03f 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> @@ -25,7 +25,7 @@ <ItemGroup> <PackageReference Include="BDInfo" Version="0.7.6.1" /> <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.6" /> - <PackageReference Include="System.Text.Encoding.CodePages" Version="4.7.1" /> + <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" /> <PackageReference Include="UTF.Unknown" Version="2.3.0" /> </ItemGroup> diff --git a/MediaBrowser.Model/Extensions/StringHelper.cs b/MediaBrowser.Model/Extensions/StringHelper.cs index 8ffa3c4ba6..2d9a6c4dbc 100644 --- a/MediaBrowser.Model/Extensions/StringHelper.cs +++ b/MediaBrowser.Model/Extensions/StringHelper.cs @@ -22,11 +22,6 @@ namespace MediaBrowser.Model.Extensions return str; } -#if NETSTANDARD2_0 - char[] a = str.ToCharArray(); - a[0] = char.ToUpperInvariant(a[0]); - return new string(a); -#else return string.Create( str.Length, str, @@ -38,7 +33,6 @@ namespace MediaBrowser.Model.Extensions chars[i] = buf[i]; } }); -#endif } } } diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 253ee7e795..b86187f9be 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -14,7 +14,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release' ">true</TreatWarningsAsErrors> @@ -32,11 +32,11 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" /> - <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" /> <PackageReference Include="System.Globalization" Version="4.3.0" /> - <PackageReference Include="System.Text.Json" Version="5.0.0-preview.8.20407.11" /> + <PackageReference Include="System.Text.Json" Version="5.0.0" /> </ItemGroup> <ItemGroup> diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 9465fe42c2..fd3f9f4c7e 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -16,9 +16,9 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.9" /> + <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" /> <PackageReference Include="PlaylistsNET" Version="1.1.2" /> <PackageReference Include="TMDbLib" Version="1.7.3-alpha" /> @@ -26,7 +26,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release'">true</TreatWarningsAsErrors> diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 45fd9add92..87d1e9464c 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -15,7 +15,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/RSSDP/RSSDP.csproj b/RSSDP/RSSDP.csproj index 664663bd76..d0962e82c8 100644 --- a/RSSDP/RSSDP.csproj +++ b/RSSDP/RSSDP.csproj @@ -10,7 +10,7 @@ </ItemGroup> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> </PropertyGroup> diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index ce61f5684e..5bf322f071 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> @@ -16,8 +16,8 @@ <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.9" /> - <PackageReference Include="Microsoft.Extensions.Options" Version="3.1.9" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 67dc8286a3..e8eca67600 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index 30e84842a0..6e3fac43d4 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 4fd0d53421..e88de38112 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 0d240fd65a..567cf34ef3 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <Nullable>enable</Nullable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index db1f2956ea..b960fda723 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -6,7 +6,7 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> From 9b7c5cddae73124fcb7b89cb033ac6ac817dcf75 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 10 Nov 2020 10:03:21 -0700 Subject: [PATCH 0280/1930] Update build ci, dockerfiles to .Net5.0 --- .ci/azure-pipelines-main.yml | 2 +- .ci/azure-pipelines.yml | 2 +- Dockerfile | 4 ++-- Dockerfile.arm | 4 ++-- Dockerfile.arm64 | 4 ++-- README.md | 2 +- deployment/Dockerfile.debian.amd64 | 3 ++- deployment/Dockerfile.debian.arm64 | 3 ++- deployment/Dockerfile.debian.armhf | 3 ++- deployment/Dockerfile.linux.amd64 | 3 ++- deployment/Dockerfile.macos | 3 ++- deployment/Dockerfile.portable | 3 ++- deployment/Dockerfile.ubuntu.amd64 | 3 ++- deployment/Dockerfile.ubuntu.arm64 | 3 ++- deployment/Dockerfile.ubuntu.armhf | 3 ++- deployment/Dockerfile.windows.amd64 | 3 ++- 16 files changed, 29 insertions(+), 19 deletions(-) diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index 7617f0f5a2..95dd3ccac2 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -1,7 +1,7 @@ parameters: LinuxImage: 'ubuntu-latest' RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj' - DotNetSdkVersion: 3.1.100 + DotNetSdkVersion: 5.0.100 jobs: - job: Build diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 5b5a17dea2..ec4c254358 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -6,7 +6,7 @@ variables: - name: RestoreBuildProjects value: 'Jellyfin.Server/Jellyfin.Server.csproj' - name: DotNetSdkVersion - value: 3.1.100 + value: 5.0.100 pr: autoCancel: true diff --git a/Dockerfile b/Dockerfile index 69af9b77b5..639a1196c6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM node:alpine as web-builder ARG JELLYFIN_WEB_VERSION=master @@ -8,7 +8,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine- && yarn install \ && mv dist /dist -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster as builder +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 diff --git a/Dockerfile.arm b/Dockerfile.arm index efeed25dff..e0eaca0edd 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -2,7 +2,7 @@ ##################################### # Requires binfm_misc registration # https://github.com/multiarch/qemu-user-static#binfmt_misc-register -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM node:alpine as web-builder @@ -14,7 +14,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine- && mv dist /dist -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 1f2c2ec36d..db7de935cf 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -2,7 +2,7 @@ ##################################### # Requires binfm_misc registration # https://github.com/multiarch/qemu-user-static#binfmt_misc-register -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM node:alpine as web-builder @@ -14,7 +14,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine- && mv dist /dist -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION} as builder +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 diff --git a/README.md b/README.md index 435e709b33..1786ed8de5 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ These instructions will help you get set up with a local development environment ### Prerequisites -Before the project can be built, you must first install the [.NET Core 3.1 SDK](https://dotnet.microsoft.com/download) on your system. +Before the project can be built, you must first install the [.NET 5.0 SDK](https://dotnet.microsoft.com/download) on your system. Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download). diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index aaca8fe01e..6241aa1a7f 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index 594da04ceb..d09ba957e2 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 3e6e2d0d70..dbffb8846c 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index f98881ebfe..e3faf43774 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index ec9d2d8c77..b68c25a8ce 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index 3523f8aceb..3a93b97261 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index 0a365e1aee..bac6fadaf6 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index ab3ec9b9f8..dd042edbc2 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index fa41bdf48a..e5f669eff6 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 7216b2363b..5170b6895a 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/fdd9ecec-56b4-40f4-b762-d7efe24fc3cd/ffef51844c92afa6714528e10609a30f/dotnet-sdk-3.1.403-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet From 158eff62d75db2d5e6e6f09fbe6e03eac607fc56 Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Tue, 10 Nov 2020 19:23:10 +0100 Subject: [PATCH 0281/1930] Xml-doc part2 --- Emby.Naming/Common/MediaType.cs | 3 + Emby.Naming/Common/NamingOptions.cs | 87 +++++++++++++++++++ Emby.Naming/Subtitles/SubtitleInfo.cs | 9 ++ Emby.Naming/Subtitles/SubtitleParser.cs | 14 ++- Emby.Naming/TV/EpisodeResolver.cs | 17 ++++ Emby.Naming/TV/SeasonPathParser.cs | 10 +++ Emby.Naming/TV/SeasonPathParserResult.cs | 7 ++ Emby.Naming/Video/ExtraResolver.cs | 12 +++ Emby.Naming/Video/ExtraResult.cs | 3 + Emby.Naming/Video/ExtraRule.cs | 7 ++ Emby.Naming/Video/FileStack.cs | 21 +++++ Emby.Naming/Video/FlagParser.cs | 18 ++++ Emby.Naming/Video/Format3DParser.cs | 12 +++ Emby.Naming/Video/Format3DResult.cs | 6 ++ Emby.Naming/Video/Format3DRule.cs | 8 ++ Emby.Naming/Video/StackResolver.cs | 27 ++++++ Emby.Naming/Video/StubResolver.cs | 10 +++ Emby.Naming/Video/StubTypeRule.cs | 8 ++ Emby.Naming/Video/VideoListResolver.cs | 13 +++ Emby.Naming/Video/VideoResolver.cs | 29 +++++++ .../Subtitles/SubtitleParserTests.cs | 7 +- 21 files changed, 321 insertions(+), 7 deletions(-) diff --git a/Emby.Naming/Common/MediaType.cs b/Emby.Naming/Common/MediaType.cs index 1231b18871..dc9784c6da 100644 --- a/Emby.Naming/Common/MediaType.cs +++ b/Emby.Naming/Common/MediaType.cs @@ -1,5 +1,8 @@ namespace Emby.Naming.Common { + /// <summary> + /// Type of audiovisual media. + /// </summary> public enum MediaType { /// <summary> diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 0f02c03cbb..035d1b2280 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -8,8 +8,14 @@ using MediaBrowser.Model.Entities; namespace Emby.Naming.Common { + /// <summary> + /// Big ugly class containing lot of different naming options that should be split and injected instead of passes everywhere. + /// </summary> public class NamingOptions { + /// <summary> + /// Initializes a new instance of the <see cref="NamingOptions"/> class. + /// </summary> public NamingOptions() { VideoFileExtensions = new[] @@ -644,58 +650,139 @@ namespace Emby.Naming.Common Compile(); } + /// <summary> + /// Gets or sets list of audio file extensions. + /// </summary> public string[] AudioFileExtensions { get; set; } + /// <summary> + /// Gets or sets list of album stacking prefixes. + /// </summary> public string[] AlbumStackingPrefixes { get; set; } + /// <summary> + /// Gets or sets list of subtitle file extensions. + /// </summary> public string[] SubtitleFileExtensions { get; set; } + /// <summary> + /// Gets or sets list of subtitles flag delimiters. + /// </summary> public char[] SubtitleFlagDelimiters { get; set; } + /// <summary> + /// Gets or sets list of subtitle forced flags. + /// </summary> public string[] SubtitleForcedFlags { get; set; } + /// <summary> + /// Gets or sets list of subtitle default flags. + /// </summary> public string[] SubtitleDefaultFlags { get; set; } + /// <summary> + /// Gets or sets list of episode regular expressions. + /// </summary> public EpisodeExpression[] EpisodeExpressions { get; set; } + /// <summary> + /// Gets or sets list of raw episode without season regular expressions strings. + /// </summary> public string[] EpisodeWithoutSeasonExpressions { get; set; } + /// <summary> + /// Gets or sets list of raw multi-part episodes regular expressions strings. + /// </summary> public string[] EpisodeMultiPartExpressions { get; set; } + /// <summary> + /// Gets or sets list of video file extensions. + /// </summary> public string[] VideoFileExtensions { get; set; } + /// <summary> + /// Gets or sets list of video stub file extensions. + /// </summary> public string[] StubFileExtensions { get; set; } + /// <summary> + /// Gets or sets list of raw audiobook parts regular expressions strings. + /// </summary> public string[] AudioBookPartsExpressions { get; set; } + /// <summary> + /// Gets or sets list of raw audiobook names regular expressions strings. + /// </summary> public string[] AudioBookNamesExpressions { get; set; } + /// <summary> + /// Gets or sets list of stub type rules. + /// </summary> public StubTypeRule[] StubTypes { get; set; } + /// <summary> + /// Gets or sets list of video flag delimiters. + /// </summary> public char[] VideoFlagDelimiters { get; set; } + /// <summary> + /// Gets or sets list of 3D Format rules. + /// </summary> public Format3DRule[] Format3DRules { get; set; } + /// <summary> + /// Gets or sets list of raw video file-stacking expressions strings. + /// </summary> public string[] VideoFileStackingExpressions { get; set; } + /// <summary> + /// Gets or sets list of raw clean DateTimes regular expressions strings. + /// </summary> public string[] CleanDateTimes { get; set; } + /// <summary> + /// Gets or sets list of raw clean strings regular expressions strings. + /// </summary> public string[] CleanStrings { get; set; } + /// <summary> + /// Gets or sets list of multi-episode regular expressions. + /// </summary> public EpisodeExpression[] MultipleEpisodeExpressions { get; set; } + /// <summary> + /// Gets or sets list of extra rules for videos. + /// </summary> public ExtraRule[] VideoExtraRules { get; set; } + /// <summary> + /// Gets list of video file-stack regular expressions. + /// </summary> public Regex[] VideoFileStackingRegexes { get; private set; } = Array.Empty<Regex>(); + /// <summary> + /// Gets list of clean datetime regular expressions. + /// </summary> public Regex[] CleanDateTimeRegexes { get; private set; } = Array.Empty<Regex>(); + /// <summary> + /// Gets list of clean string regular expressions. + /// </summary> public Regex[] CleanStringRegexes { get; private set; } = Array.Empty<Regex>(); + /// <summary> + /// Gets list of episode without season regular expressions. + /// </summary> public Regex[] EpisodeWithoutSeasonRegexes { get; private set; } = Array.Empty<Regex>(); + /// <summary> + /// Gets list of multi-part episode regular expressions. + /// </summary> public Regex[] EpisodeMultiPartRegexes { get; private set; } = Array.Empty<Regex>(); + /// <summary> + /// Compiles raw regex strings into regexes. + /// </summary> public void Compile() { VideoFileStackingRegexes = VideoFileStackingExpressions.Select(Compile).ToArray(); diff --git a/Emby.Naming/Subtitles/SubtitleInfo.cs b/Emby.Naming/Subtitles/SubtitleInfo.cs index 62cc3ead17..1fb2e0dc89 100644 --- a/Emby.Naming/Subtitles/SubtitleInfo.cs +++ b/Emby.Naming/Subtitles/SubtitleInfo.cs @@ -1,7 +1,16 @@ namespace Emby.Naming.Subtitles { + /// <summary> + /// Class holding information about subtitle. + /// </summary> public class SubtitleInfo { + /// <summary> + /// Initializes a new instance of the <see cref="SubtitleInfo"/> class. + /// </summary> + /// <param name="path">Path to file.</param> + /// <param name="isDefault">Is subtitle default.</param> + /// <param name="isForced">Is subtitle forced.</param> public SubtitleInfo(string path, bool isDefault, bool isForced) { Path = path; diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index 476a83cf35..e872452519 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -5,20 +5,32 @@ using Emby.Naming.Common; namespace Emby.Naming.Subtitles { + /// <summary> + /// Subtitle Parser class. + /// </summary> public class SubtitleParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="SubtitleParser"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing SubtitleFileExtensions, SubtitleDefaultFlags, SubtitleForcedFlags and SubtitleFlagDelimiters.</param> public SubtitleParser(NamingOptions options) { _options = options; } + /// <summary> + /// Parse file to determine if is subtitle and <see cref="SubtitleInfo"/>. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>Returns null or <see cref="SubtitleInfo"/> object if parsing is successful.</returns> public SubtitleInfo? ParseFile(string path) { if (path.Length == 0) { - throw new ArgumentException("File path can't be empty.", nameof(path)); + return null; } var extension = Path.GetExtension(path); diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index 26dd6915b9..f7df587864 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -6,15 +6,32 @@ using Emby.Naming.Video; namespace Emby.Naming.TV { + /// <summary> + /// Used to resolve information about episode from path. + /// </summary> public class EpisodeResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="EpisodeResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoFileExtensions and passed to <see cref="StubResolver"/>, <see cref="FlagParser"/>, <see cref="Format3DParser"/> and <see cref="EpisodePathParser"/>.</param> public EpisodeResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Resolve information about episode from path. + /// </summary> + /// <param name="path">Path.</param> + /// <param name="isDirectory">Is path for a directory or file.</param> + /// <param name="isNamed">Do we want to use IsNamed expressions.</param> + /// <param name="isOptimistic">Do we want to use Optimistic expressions.</param> + /// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param> + /// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param> + /// <returns>Returns null or <see cref="EpisodeInfo"/> object if successful.</returns> public EpisodeInfo? Resolve( string path, bool isDirectory, diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index cf99097bc4..d11c7c99e8 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -4,6 +4,9 @@ using System.IO; namespace Emby.Naming.TV { + /// <summary> + /// Class to parse season paths. + /// </summary> public static class SeasonPathParser { /// <summary> @@ -21,6 +24,13 @@ namespace Emby.Naming.TV "stagione" }; + /// <summary> + /// Attempts to parse season number from path. + /// </summary> + /// <param name="path">Path to season.</param> + /// <param name="supportSpecialAliases">Support special aliases when parsing.</param> + /// <param name="supportNumericSeasonFolders">Support numeric season folders when parsing.</param> + /// <returns>Returns <see cref="SeasonPathParserResult"/> object.</returns> public static SeasonPathParserResult Parse(string path, bool supportSpecialAliases, bool supportNumericSeasonFolders) { var result = new SeasonPathParserResult(); diff --git a/Emby.Naming/TV/SeasonPathParserResult.cs b/Emby.Naming/TV/SeasonPathParserResult.cs index f52f941a7c..b4b6f236a7 100644 --- a/Emby.Naming/TV/SeasonPathParserResult.cs +++ b/Emby.Naming/TV/SeasonPathParserResult.cs @@ -1,5 +1,8 @@ namespace Emby.Naming.TV { + /// <summary> + /// Data object to pass result of <see cref="SeasonPathParser"/>. + /// </summary> public class SeasonPathParserResult { /// <summary> @@ -14,6 +17,10 @@ namespace Emby.Naming.TV /// <value><c>true</c> if success; otherwise, <c>false</c>.</value> public bool Success { get; set; } + /// <summary> + /// Gets or sets a value indicating whether "Is season folder". + /// Seems redundant and barely used. + /// </summary> public bool IsSeasonFolder { get; set; } } } diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index 98ea342acc..dd934d91b0 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -6,15 +6,27 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { + /// <summary> + /// Resolve if file is extra for video. + /// </summary> public class ExtraResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="ExtraResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoExtraRules and passed to <see cref="AudioFileParser"/> and <see cref="VideoResolver"/>.</param> public ExtraResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Attempts to resolve if file is extra. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>Returns <see cref="ExtraResult"/> object.</returns> public ExtraResult GetExtraInfo(string path) { return _options.VideoExtraRules diff --git a/Emby.Naming/Video/ExtraResult.cs b/Emby.Naming/Video/ExtraResult.cs index f3b8d2a2fc..243fc2b415 100644 --- a/Emby.Naming/Video/ExtraResult.cs +++ b/Emby.Naming/Video/ExtraResult.cs @@ -2,6 +2,9 @@ using MediaBrowser.Model.Entities; namespace Emby.Naming.Video { + /// <summary> + /// Holder object for passing results from ExtraResolver. + /// </summary> public class ExtraResult { /// <summary> diff --git a/Emby.Naming/Video/ExtraRule.cs b/Emby.Naming/Video/ExtraRule.cs index a93474bc69..e267ac55fc 100644 --- a/Emby.Naming/Video/ExtraRule.cs +++ b/Emby.Naming/Video/ExtraRule.cs @@ -8,6 +8,13 @@ namespace Emby.Naming.Video /// </summary> public class ExtraRule { + /// <summary> + /// Initializes a new instance of the <see cref="ExtraRule"/> class. + /// </summary> + /// <param name="extraType">Type of extra.</param> + /// <param name="ruleType">Type of rule.</param> + /// <param name="token">Token.</param> + /// <param name="mediaType">Media type.</param> public ExtraRule(ExtraType extraType, ExtraRuleType ruleType, string token, MediaType mediaType) { Token = token; diff --git a/Emby.Naming/Video/FileStack.cs b/Emby.Naming/Video/FileStack.cs index 75620e9610..6519db57c3 100644 --- a/Emby.Naming/Video/FileStack.cs +++ b/Emby.Naming/Video/FileStack.cs @@ -4,19 +4,40 @@ using System.Linq; namespace Emby.Naming.Video { + /// <summary> + /// Object holding list of files paths with additional information. + /// </summary> public class FileStack { + /// <summary> + /// Initializes a new instance of the <see cref="FileStack"/> class. + /// </summary> public FileStack() { Files = new List<string>(); } + /// <summary> + /// Gets or sets name of file stack. + /// </summary> public string Name { get; set; } = string.Empty; + /// <summary> + /// Gets or sets list of paths in stack. + /// </summary> public List<string> Files { get; set; } + /// <summary> + /// Gets or sets a value indicating whether stack is directory stack. + /// </summary> public bool IsDirectoryStack { get; set; } + /// <summary> + /// Helper function to determine if path is in the stack. + /// </summary> + /// <param name="file">Path of desired file.</param> + /// <param name="isDirectory">Requested type of stack.</param> + /// <returns>True if file is in the stack.</returns> public bool ContainsFile(string file, bool isDirectory) { if (IsDirectoryStack == isDirectory) diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs index cd15b4666f..439de18138 100644 --- a/Emby.Naming/Video/FlagParser.cs +++ b/Emby.Naming/Video/FlagParser.cs @@ -4,20 +4,38 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { + /// <summary> + /// Parses list of flags from filename based on delimiters. + /// </summary> public class FlagParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="FlagParser"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoFlagDelimiters.</param> public FlagParser(NamingOptions options) { _options = options; } + /// <summary> + /// Calls GetFlags function with _options.VideoFlagDelimiters parameter. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>List of found flags.</returns> public string[] GetFlags(string path) { return GetFlags(path, _options.VideoFlagDelimiters); } + /// <summary> + /// Parses flags from filename based on delimiters. + /// </summary> + /// <param name="path">Path to file.</param> + /// <param name="delimiters">Delimiters used to extract flags.</param> + /// <returns>List of found flags.</returns> public string[] GetFlags(string path, char[] delimiters) { if (string.IsNullOrEmpty(path)) diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index 73ad36af46..4fd5d78ba7 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -4,15 +4,27 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { + /// <summary> + /// Parste 3D format related flags. + /// </summary> public class Format3DParser { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="Format3DParser"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoFlagDelimiters and passes options to <see cref="FlagParser"/>.</param> public Format3DParser(NamingOptions options) { _options = options; } + /// <summary> + /// Parse 3D format related flags. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>Returns <see cref="Format3DResult"/> object.</returns> public Format3DResult Parse(string path) { int oldLen = _options.VideoFlagDelimiters.Length; diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs index 539060c982..ac935f2030 100644 --- a/Emby.Naming/Video/Format3DResult.cs +++ b/Emby.Naming/Video/Format3DResult.cs @@ -2,8 +2,14 @@ using System.Collections.Generic; namespace Emby.Naming.Video { + /// <summary> + /// Helper object to return data from <see cref="Format3DParser"/>. + /// </summary> public class Format3DResult { + /// <summary> + /// Initializes a new instance of the <see cref="Format3DResult"/> class. + /// </summary> public Format3DResult() { Tokens = new List<string>(); diff --git a/Emby.Naming/Video/Format3DRule.cs b/Emby.Naming/Video/Format3DRule.cs index bee5c109e1..e562691df9 100644 --- a/Emby.Naming/Video/Format3DRule.cs +++ b/Emby.Naming/Video/Format3DRule.cs @@ -1,7 +1,15 @@ namespace Emby.Naming.Video { + /// <summary> + /// Data holder class for 3D format rule. + /// </summary> public class Format3DRule { + /// <summary> + /// Initializes a new instance of the <see cref="Format3DRule"/> class. + /// </summary> + /// <param name="token">Token.</param> + /// <param name="precedingToken">Token present before current token.</param> public Format3DRule(string token, string? precedingToken = null) { Token = token; diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index d6de468cc9..550c429614 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -9,25 +9,47 @@ using MediaBrowser.Model.IO; namespace Emby.Naming.Video { + /// <summary> + /// Resolve <see cref="FileStack"/> from list of paths. + /// </summary> public class StackResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="StackResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoFileStackingRegexes and passes options to <see cref="VideoResolver"/>.</param> public StackResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Resolves only directories from paths. + /// </summary> + /// <param name="files">List of paths.</param> + /// <returns>Enumerable <see cref="FileStack"/> of directories.</returns> public IEnumerable<FileStack> ResolveDirectories(IEnumerable<string> files) { return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = true })); } + /// <summary> + /// Resolves only files from paths. + /// </summary> + /// <param name="files">List of paths.</param> + /// <returns>Enumerable <see cref="FileStack"/> of files.</returns> public IEnumerable<FileStack> ResolveFiles(IEnumerable<string> files) { return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = false })); } + /// <summary> + /// Resolves audiobooks from paths. + /// </summary> + /// <param name="files">List of paths.</param> + /// <returns>Enumerable <see cref="FileStack"/> of directories.</returns> public IEnumerable<FileStack> ResolveAudioBooks(IEnumerable<AudioBookFileInfo> files) { var groupedDirectoryFiles = files.GroupBy(file => Path.GetDirectoryName(file.Path)); @@ -56,6 +78,11 @@ namespace Emby.Naming.Video } } + /// <summary> + /// Resolves videos from paths. + /// </summary> + /// <param name="files">List of paths.</param> + /// <returns>Enumerable <see cref="FileStack"/> of videos.</returns> public IEnumerable<FileStack> Resolve(IEnumerable<FileSystemMetadata> files) { var resolver = new VideoResolver(_options); diff --git a/Emby.Naming/Video/StubResolver.cs b/Emby.Naming/Video/StubResolver.cs index 6241a46b03..079987fe8a 100644 --- a/Emby.Naming/Video/StubResolver.cs +++ b/Emby.Naming/Video/StubResolver.cs @@ -5,8 +5,18 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { + /// <summary> + /// Resolve if file is stub (.disc). + /// </summary> public static class StubResolver { + /// <summary> + /// Tries to resolve if file is stub (.disc). + /// </summary> + /// <param name="path">Path to file.</param> + /// <param name="options">NamingOptions containing StubFileExtensions and StubTypes.</param> + /// <param name="stubType">Stub type.</param> + /// <returns>True if file is a stub.</returns> public static bool TryResolveFile(string path, NamingOptions options, out string? stubType) { stubType = default; diff --git a/Emby.Naming/Video/StubTypeRule.cs b/Emby.Naming/Video/StubTypeRule.cs index df2d3c7d22..dfb3ac013d 100644 --- a/Emby.Naming/Video/StubTypeRule.cs +++ b/Emby.Naming/Video/StubTypeRule.cs @@ -1,7 +1,15 @@ namespace Emby.Naming.Video { + /// <summary> + /// Data class holding information about Stub type rule. + /// </summary> public class StubTypeRule { + /// <summary> + /// Initializes a new instance of the <see cref="StubTypeRule"/> class. + /// </summary> + /// <param name="token">Token.</param> + /// <param name="stubType">Stub type.</param> public StubTypeRule(string token, string stubType) { Token = token; diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index dda3225217..ee0e4d4659 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -9,15 +9,28 @@ using MediaBrowser.Model.IO; namespace Emby.Naming.Video { + /// <summary> + /// Resolves alternative versions and extras from list of video files. + /// </summary> public class VideoListResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="VideoListResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing CleanStringRegexes and VideoFlagDelimiters and passes options to <see cref="StackResolver"/> and <see cref="VideoResolver"/>.</param> public VideoListResolver(NamingOptions options) { _options = options; } + /// <summary> + /// Resolves alternative versions and extras from list of video files. + /// </summary> + /// <param name="files">List of related video files.</param> + /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param> + /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files togeather when related.</returns> public IEnumerable<VideoInfo> Resolve(List<FileSystemMetadata> files, bool supportMultiVersion = true) { var videoResolver = new VideoResolver(_options); diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 31b47cdf15..d7165d8d7f 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -5,10 +5,18 @@ using Emby.Naming.Common; namespace Emby.Naming.Video { + /// <summary> + /// Resolves <see cref="VideoFileInfo"/> from file path. + /// </summary> public class VideoResolver { private readonly NamingOptions _options; + /// <summary> + /// Initializes a new instance of the <see cref="VideoResolver"/> class. + /// </summary> + /// <param name="options"><see cref="NamingOptions"/> object containing VideoFileExtensions, StubFileExtensions, CleanStringRegexes and CleanDateTimeRegexes + /// and passes options in <see cref="StubResolver"/>, <see cref="FlagParser"/>, <see cref="Format3DParser"/> and <see cref="ExtraResolver"/>.</param> public VideoResolver(NamingOptions options) { _options = options; @@ -110,23 +118,44 @@ namespace Emby.Naming.Video extraRule: extraResult.Rule); } + /// <summary> + /// Determines if path is video file based on extension. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>True if is video file.</returns> public bool IsVideoFile(string path) { var extension = Path.GetExtension(path) ?? string.Empty; return _options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } + /// <summary> + /// Determines if path is video file stub based on extension. + /// </summary> + /// <param name="path">Path to file.</param> + /// <returns>True if is video file stub.</returns> public bool IsStubFile(string path) { var extension = Path.GetExtension(path) ?? string.Empty; return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } + /// <summary> + /// Tries to clean name of clutter. + /// </summary> + /// <param name="name">Raw name.</param> + /// <param name="newName">Clean name.</param> + /// <returns>True if cleaning of name was successful.</returns> public bool TryCleanString(string name, out ReadOnlySpan<char> newName) { return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } + /// <summary> + /// Tries to get name and year from raw name. + /// </summary> + /// <param name="name">Raw name.</param> + /// <returns>Returns <see cref="CleanDateTimeResult"/> with name and optional year.</returns> public CleanDateTimeResult CleanDateTime(string name) { return CleanDateTimeParser.Clean(name, _options.CleanDateTimeRegexes); diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs index 5152098908..f3abacb4f9 100644 --- a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -31,17 +31,12 @@ namespace Jellyfin.Naming.Tests.Subtitles [Theory] [InlineData("The Skin I Live In (2011).mp4")] + [InlineData("")] public void SubtitleParser_InvalidFileName_ReturnsNull(string input) { var parser = new SubtitleParser(_namingOptions); Assert.Null(parser.ParseFile(input)); } - - [Fact] - public void SubtitleParser_EmptyFileName_ThrowsArgumentException() - { - Assert.Throws<ArgumentException>(() => new SubtitleParser(_namingOptions).ParseFile(string.Empty)); - } } } From 195a6261c49f2f1376794a149ddec0a56cbe230a Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Tue, 10 Nov 2020 19:28:03 +0100 Subject: [PATCH 0282/1930] Dummy test case explanation. --- tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs index 57f382b382..12fc19bc48 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodePathParserTest.cs @@ -82,6 +82,10 @@ namespace Jellyfin.Naming.Tests.TV Assert.True(res!.IsStub); } + /* + * EpisodePathParser.cs:130 is currently unreachable, but the piece of code is useful and could be reached with addition of new EpisodeExpressions. + * In order to preserve it but achieve 100% code coverage the test case below with made up expressions and filename is used. + */ [Fact] public void EpisodePathParserTest_EmptyDateParsers() { From f5b301dea66c6dd88ced57c0dbedf21b54145b5c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 10 Nov 2020 11:48:21 -0700 Subject: [PATCH 0283/1930] Correct bad docs merge --- Jellyfin.Api/Controllers/ChannelsController.cs | 2 +- Jellyfin.Api/Controllers/PersonsController.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index eed54105da..ec9d7cdce1 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -183,7 +183,7 @@ namespace Jellyfin.Api.Controllers /// <param name="userId">Optional. User Id.</param> /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> /// <param name="limit">Optional. The maximum number of records to return.</param> - /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> + /// <param name="filters">Optional. Specify additional filters to apply.</param> /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param> /// <param name="channelIds">Optional. Specify one or more channel id's, comma delimited.</param> /// <response code="200">Latest channel items returned.</response> diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index ac02795081..6ac3e6417a 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -54,7 +54,7 @@ namespace Jellyfin.Api.Controllers /// <param name="limit">Optional. The maximum number of records to return.</param> /// <param name="searchTerm">The search term.</param> /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param> - /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> + /// <param name="filters">Optional. Specify additional filters to apply.</param> /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not. userId is required.</param> /// <param name="enableUserData">Optional, include user data.</param> /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> From dc3b3bcfb1881743c078d13a100dc8f751ce6dff Mon Sep 17 00:00:00 2001 From: David John Corpuz <djmcorpuz@gmail.com> Date: Tue, 10 Nov 2020 17:59:54 +0000 Subject: [PATCH 0284/1930] Translated using Weblate (Filipino) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fil/ --- .../Localization/Core/fil.json | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fil.json b/Emby.Server.Implementations/Localization/Core/fil.json index 1a3e188327..e5ca676a48 100644 --- a/Emby.Server.Implementations/Localization/Core/fil.json +++ b/Emby.Server.Implementations/Localization/Core/fil.json @@ -1,7 +1,7 @@ { "VersionNumber": "Bersyon {0}", "ValueSpecialEpisodeName": "Espesyal - {0}", - "ValueHasBeenAddedToLibrary": "Naidagdag na ang {0} sa iyong media library", + "ValueHasBeenAddedToLibrary": "Naidagdag na ang {0} sa iyong librerya ng medya", "UserStoppedPlayingItemWithValues": "Natapos ni {0} ang {1} sa {2}", "UserStartedPlayingItemWithValues": "Si {0} ay nagplaplay ng {1} sa {2}", "UserPolicyUpdatedWithName": "Ang user policy ay naiupdate para kay {0}", @@ -61,8 +61,8 @@ "Latest": "Pinakabago", "LabelRunningTimeValue": "Oras: {0}", "LabelIpAddressValue": "Ang IP Address ay {0}", - "ItemRemovedWithName": "Naitanggal ang {0} sa library", - "ItemAddedWithName": "Naidagdag ang {0} sa library", + "ItemRemovedWithName": "Naitanggal ang {0} sa librerya", + "ItemAddedWithName": "Naidagdag ang {0} sa librerya", "Inherit": "Manahin", "HeaderRecordingGroups": "Pagtatalang Grupo", "HeaderNextUp": "Susunod", @@ -90,12 +90,29 @@ "Application": "Aplikasyon", "AppDeviceValues": "Aplikasyon: {0}, Aparato: {1}", "Albums": "Albums", - "TaskRefreshLibrary": "Suriin ang nasa librerya", - "TaskRefreshChapterImagesDescription": "Gumawa ng larawan para sa mga pelikula na may kabanata", + "TaskRefreshLibrary": "Suriin and Librerya ng Medya", + "TaskRefreshChapterImagesDescription": "Gumawa ng larawan para sa mga pelikula na may kabanata.", "TaskRefreshChapterImages": "Kunin ang mga larawan ng kabanata", "TaskCleanCacheDescription": "Tanggalin ang mga cache file na hindi na kailangan ng systema.", "TasksChannelsCategory": "Palabas sa internet", "TasksLibraryCategory": "Librerya", "TasksMaintenanceCategory": "Pagpapanatili", - "HomeVideos": "Sariling pelikula" + "HomeVideos": "Sariling pelikula", + "TaskRefreshPeopleDescription": "Ini-update ang metadata para sa mga aktor at direktor sa iyong librerya ng medya.", + "TaskRefreshPeople": "I-refresh ang Tauhan", + "TaskDownloadMissingSubtitlesDescription": "Hinahanap sa internet ang mga nawawalang subtiles base sa metadata configuration.", + "TaskDownloadMissingSubtitles": "I-download and nawawalang subtitles", + "TaskRefreshChannelsDescription": "Ni-rerefresh ang impormasyon sa internet channels.", + "TaskRefreshChannels": "I-refresh ang Channels", + "TaskCleanTranscodeDescription": "Binubura ang transcode files na mas matanda ng isang araw.", + "TaskUpdatePluginsDescription": "Nag download at install ng updates sa plugins na naka configure para sa automatikong pag update.", + "TaskUpdatePlugins": "I-update ang Plugins", + "TaskCleanLogsDescription": "Binubura and files ng talaan na mas mantanda ng {0} araw.", + "TaskCleanTranscode": "Linisin and Direktoryo ng Transcode", + "TaskCleanLogs": "Linisin and Direktoryo ng Talaan", + "TaskRefreshLibraryDescription": "Sinusuri ang iyong librerya ng medya para sa bagong files at irefresh ang metadata.", + "TaskCleanCache": "Linisin and Direktoryo ng Cache", + "TasksApplicationCategory": "Application", + "TaskCleanActivityLog": "Linisin ang Tala ng Aktibidad", + "TaskCleanActivityLogDescription": "Tanggalin ang mga tala ng aktibidad na mas matanda sa naka configure na edad." } From 7104a37be1a9bea0106c8b291b6120de0b71dfa8 Mon Sep 17 00:00:00 2001 From: yodatak <mryodatak@gmail.com> Date: Tue, 10 Nov 2020 22:52:20 +0100 Subject: [PATCH 0285/1930] Bump dependencies to Fedora 33 Fedora 33 is out so Fedora 31 is unmaintened so its time to migrate the build to Fedora 33 ! --- deployment/Dockerfile.fedora.amd64 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64 index 01b99deb6d..f881890348 100644 --- a/deployment/Dockerfile.fedora.amd64 +++ b/deployment/Dockerfile.fedora.amd64 @@ -1,4 +1,4 @@ -FROM fedora:31 +FROM fedora:33 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist From 51ddf038dc3604b53488c618adb728f374816db1 Mon Sep 17 00:00:00 2001 From: Ted van den Brink <ted@digistate.nl> Date: Tue, 10 Nov 2020 22:44:05 +0000 Subject: [PATCH 0286/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index e102b92b90..e1e88cc9ba 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Internet Kanalen", "TasksApplicationCategory": "Applicatie", "TasksLibraryCategory": "Bibliotheek", - "TasksMaintenanceCategory": "Onderhoud" + "TasksMaintenanceCategory": "Onderhoud", + "TaskCleanActivityLogDescription": "Verwijder activiteiten logs ouder dan de ingestelde tijd.", + "TaskCleanActivityLog": "Leeg activiteiten logboek" } From 0b01acbe9172872f2685b115c219efd98619b4bc Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Wed, 11 Nov 2020 02:03:53 +0000 Subject: [PATCH 0287/1930] Apply suggestions from code review Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- .../Controllers/DynamicHlsController.cs | 4 +-- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 17 ++++++----- .../MediaEncoding/EncodingHelper.cs | 30 +++++++++---------- 3 files changed, 26 insertions(+), 25 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 6b1618421d..4cf4c24d77 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1565,7 +1565,7 @@ namespace Jellyfin.Api.Controllers args += " " + _encodingHelper.GetVideoQualityParam(state, codec, encodingOptions, "veryfast"); - // Unable to force key frames using these encoders, set key frames by GOP + // Unable to force key frames using these encoders, set key frames by GOP. if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) @@ -1587,7 +1587,7 @@ namespace Jellyfin.Api.Controllers args += " " + keyFrameArg + gopArg; } - // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now + // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now. if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) { args += " -bf 0"; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 4999a582e3..d6fa6e98d6 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -206,7 +206,7 @@ namespace Jellyfin.Api.Helpers if (state.VideoStream != null && state.VideoRequest != null) { - // Provide SDR HEVC entrance for backward compatibility + // Provide SDR HEVC entrance for backward compatibility. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) && !string.IsNullOrEmpty(state.VideoStream.VideoRange) && string.Equals(state.VideoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase) @@ -215,7 +215,7 @@ namespace Jellyfin.Api.Helpers var requestedVideoProfiles = state.GetRequestedProfiles("hevc"); if (requestedVideoProfiles != null && requestedVideoProfiles.Length > 0) { - // Force HEVC Main Profile and disable video stream copy + // Force HEVC Main Profile and disable video stream copy. state.OutputVideoCodec = "hevc"; var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(",", requestedVideoProfiles), "main"); sdrVideoUrl += "&AllowVideoStreamCopy=false"; @@ -232,7 +232,7 @@ namespace Jellyfin.Api.Helpers } } - // Provide Level 5.0 entrance for backward compatibility + // Provide Level 5.0 entrance for backward compatibility. // e.g. Apple A10 chips refuse the master playlist containing SDR HEVC Main Level 5.1 video, // but in fact it is capable of playing videos up to Level 6.1. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec) @@ -245,13 +245,13 @@ namespace Jellyfin.Api.Helpers var playlistCodecsField = new StringBuilder(); AppendPlaylistCodecsField(playlistCodecsField, state); - // Force the video level to 5.0 + // Force the video level to 5.0. var originalLevel = state.VideoStream.Level; state.VideoStream.Level = 150; var newPlaylistCodecsField = new StringBuilder(); AppendPlaylistCodecsField(newPlaylistCodecsField, state); - // Restore the video level + // Restore the video level. state.VideoStream.Level = originalLevel; var newPlaylist = ReplacePlaylistCodecsField(basicPlaylist, playlistCodecsField, newPlaylistCodecsField); builder.Append(newPlaylist); @@ -333,7 +333,7 @@ namespace Jellyfin.Api.Helpers } else { - // Currently we only encode to SDR + // Currently we only encode to SDR. builder.Append(",VIDEO-RANGE=SDR"); } } @@ -693,9 +693,10 @@ namespace Jellyfin.Api.Helpers private string ReplaceProfile(string url, string codec, string oldValue, string newValue) { + string profileStr = codec + "-profile="; return url.Replace( - codec + "-profile=" + oldValue, - codec + "-profile=" + newValue, + profileStr + oldValue, + profileStr + newValue, StringComparison.OrdinalIgnoreCase); } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 6e348f1e65..6255e1b61c 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -662,10 +662,10 @@ namespace MediaBrowser.Controller.MediaEncoding if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)) { - // Transcode to level 5.0 and lower for maximum compatibility - // level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it + // Transcode to level 5.0 and lower for maximum compatibility. + // Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it. // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels - // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880, + // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880. if (requestLevel >= 150) { return "150"; @@ -673,7 +673,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { - // Clients may direct play higher than level 41, but there's no reason to transcode higher + // Clients may direct play higher than level 41, but there's no reason to transcode higher. if (requestLevel >= 41) { return "41"; @@ -843,7 +843,7 @@ namespace MediaBrowser.Controller.MediaEncoding else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc) || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc) { - // following preset will be deprecated in ffmpeg 4.4, use p1~p7 instead + // following preset will be deprecated in ffmpeg 4.4, use p1~p7 instead. switch (encodingOptions.EncoderPreset) { case "veryslow": @@ -976,7 +976,7 @@ namespace MediaBrowser.Controller.MediaEncoding var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault(); profile = Regex.Replace(profile, @"\s+", String.Empty); - // only libx264 support encoding H264 High 10 Profile, otherwise force High Profile + // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) && profile != null && profile.IndexOf("high 10", StringComparison.OrdinalIgnoreCase) != -1) @@ -985,7 +985,7 @@ namespace MediaBrowser.Controller.MediaEncoding } // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case, - // which is compatible (and ugly) + // which is compatible (and ugly). if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && profile != null && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) @@ -993,7 +993,7 @@ namespace MediaBrowser.Controller.MediaEncoding profile = "constrained_baseline"; } - // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case + // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)) @@ -1003,7 +1003,7 @@ namespace MediaBrowser.Controller.MediaEncoding profile = "baseline"; } - // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile + // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile. if (!string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase) && profile != null && profile.IndexOf("main 10", StringComparison.OrdinalIgnoreCase) != -1) @@ -1027,7 +1027,7 @@ namespace MediaBrowser.Controller.MediaEncoding { level = NormalizeTranscodingLevel(state, level); - // libx264, QSV, AMF, VAAPI can adjust the given level to match the output + // libx264, QSV, AMF, VAAPI can adjust the given level to match the output. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)) { @@ -1035,7 +1035,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) { - // hevc_qsv use -level 51 instead of -level 153 + // hevc_qsv use -level 51 instead of -level 153. if (double.TryParse(level, NumberStyles.Any, _usCulture, out double hevcLevel)) { param += " -level " + hevcLevel / 3; @@ -1066,10 +1066,10 @@ namespace MediaBrowser.Controller.MediaEncoding if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) { - // libx265 only accept level option in -x265-params - // level option may cause libx265 to fail - // libx265 cannot adjust the given level, just throw an error - // TODO: set fine tuned params + // libx265 only accept level option in -x265-params. + // level option may cause libx265 to fail. + // libx265 cannot adjust the given level, just throw an error. + // TODO: set fine tuned params. param += " -x265-params:0 no-info=1"; } From 0c45faf100d226a00c07e785aa55e22ec55bda9c Mon Sep 17 00:00:00 2001 From: Sam Cross <samgcdev@gmail.com> Date: Wed, 11 Nov 2020 00:27:35 +0000 Subject: [PATCH 0288/1930] Translated using Weblate (English (United Kingdom)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/en_GB/ --- Emby.Server.Implementations/Localization/Core/en-GB.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/en-GB.json b/Emby.Server.Implementations/Localization/Core/en-GB.json index 57ff13219f..cd64cdde45 100644 --- a/Emby.Server.Implementations/Localization/Core/en-GB.json +++ b/Emby.Server.Implementations/Localization/Core/en-GB.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Internet Channels", "TasksApplicationCategory": "Application", "TasksLibraryCategory": "Library", - "TasksMaintenanceCategory": "Maintenance" + "TasksMaintenanceCategory": "Maintenance", + "TaskCleanActivityLogDescription": "Deletes activity log entries older than the configured age.", + "TaskCleanActivityLog": "Clean Activity Log" } From 57e5b59b93272bbbafeb1b57bdacc862c48f0996 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Wed, 11 Nov 2020 17:08:50 +0800 Subject: [PATCH 0289/1930] adjust bitrate limit for HLS audio codecs --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/StreamingHelpers.cs | 47 ++++++-- .../MediaEncoding/EncodingHelper.cs | 50 +++++--- .../Probing/ProbeResultNormalizer.cs | 112 +++++++++++++++++- .../Dlna/ResolutionNormalizer.cs | 8 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 72 +++++++++-- MediaBrowser.Model/Dlna/StreamInfo.cs | 2 +- 7 files changed, 245 insertions(+), 48 deletions(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index d6fa6e98d6..d2710bf40e 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -222,7 +222,7 @@ namespace Jellyfin.Api.Helpers EncodingHelper encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); var sdrOutputVideoBitrate = encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec) ?? 0; - var sdrOutputAudioBitrate = encodingHelper.GetAudioBitrateParam(state.VideoRequest.AudioBitRate, state.AudioStream) ?? 0; + var sdrOutputAudioBitrate = encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream) ?? 0; var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate; AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup); diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index f4ec29bdef..5bd347846d 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -183,7 +183,7 @@ namespace Jellyfin.Api.Helpers state.OutputContainer = (containerInternal ?? string.Empty).TrimStart('.'); - state.OutputAudioBitrate = encodingHelper.GetAudioBitrateParam(streamingRequest.AudioBitRate, state.AudioStream); + state.OutputAudioBitrate = encodingHelper.GetAudioBitrateParam(streamingRequest.AudioBitRate, streamingRequest.AudioCodec, state.AudioStream); state.OutputAudioCodec = streamingRequest.AudioCodec; @@ -196,20 +196,41 @@ namespace Jellyfin.Api.Helpers encodingHelper.TryStreamCopy(state); - if (state.OutputVideoBitrate.HasValue && !EncodingHelper.IsCopyCodec(state.OutputVideoCodec)) + if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec) && state.OutputVideoBitrate.HasValue) { - var resolution = ResolutionNormalizer.Normalize( - state.VideoStream?.BitRate, - state.VideoStream?.Width, - state.VideoStream?.Height, - state.OutputVideoBitrate.Value, - state.VideoStream?.Codec, - state.OutputVideoCodec, - state.VideoRequest.MaxWidth, - state.VideoRequest.MaxHeight); + var isVideoResolutionNotRequested = !state.VideoRequest.Width.HasValue + && !state.VideoRequest.Height.HasValue + && !state.VideoRequest.MaxWidth.HasValue + && !state.VideoRequest.MaxHeight.HasValue; - state.VideoRequest.MaxWidth = resolution.MaxWidth; - state.VideoRequest.MaxHeight = resolution.MaxHeight; + if (isVideoResolutionNotRequested + && state.VideoRequest.VideoBitRate.HasValue + && state.VideoStream.BitRate.HasValue + && state.VideoRequest.VideoBitRate.Value >= state.VideoStream.BitRate.Value) + { + // Don't downscale the resolution if the width/height/MaxWidth/MaxHeight is not requested, + // and the requested video bitrate is higher than source video bitrate. + if (state.VideoStream.Width.HasValue || state.VideoStream.Height.HasValue) + { + state.VideoRequest.MaxWidth = state.VideoStream?.Width; + state.VideoRequest.MaxHeight = state.VideoStream?.Height; + } + } + else + { + var resolution = ResolutionNormalizer.Normalize( + state.VideoStream?.BitRate, + state.VideoStream?.Width, + state.VideoStream?.Height, + state.OutputVideoBitrate.Value, + state.VideoStream?.Codec, + state.OutputVideoCodec, + state.VideoRequest.MaxWidth, + state.VideoRequest.MaxHeight); + + state.VideoRequest.MaxWidth = resolution.MaxWidth; + state.VideoRequest.MaxHeight = resolution.MaxHeight; + } } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 6255e1b61c..e8b4869ee9 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1390,7 +1390,7 @@ namespace MediaBrowser.Controller.MediaEncoding || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)) { - return .5; + return .6; } return 1; @@ -1424,36 +1424,48 @@ namespace MediaBrowser.Controller.MediaEncoding public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream) { - if (audioStream == null) - { - return null; - } - - if (request.AudioBitRate.HasValue) - { - // Don't encode any higher than this - return Math.Min(384000, request.AudioBitRate.Value); - } - - // Empty bitrate area is not allow on iOS - // Default audio bitrate to 128K if it is not being requested - // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options - return 128000; + return GetAudioBitrateParam(request.AudioBitRate, request.AudioCodec, audioStream); } - public int? GetAudioBitrateParam(int? audioBitRate, MediaStream audioStream) + public int? GetAudioBitrateParam(int? audioBitRate, string audioCodec, MediaStream audioStream) { if (audioStream == null) { return null; } - if (audioBitRate.HasValue) + if (audioBitRate.HasValue && string.IsNullOrEmpty(audioCodec)) { - // Don't encode any higher than this return Math.Min(384000, audioBitRate.Value); } + if (audioBitRate.HasValue && !string.IsNullOrEmpty(audioCodec)) + { + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase)) + { + if ((audioStream.Channels ?? 0) >= 6) + { + return Math.Min(640000, audioBitRate.Value); + } + + return Math.Min(384000, audioBitRate.Value); + } + + if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase)) + { + if ((audioStream.Channels ?? 0) >= 6) + { + return Math.Min(3584000, audioBitRate.Value); + } + + return Math.Min(1536000, audioBitRate.Value); + } + } + // Empty bitrate area is not allow on iOS // Default audio bitrate to 128K if it is not being requested // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index cdeefbbbdf..1b0d4d1af4 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -234,8 +234,8 @@ namespace MediaBrowser.MediaEncoding.Probing var channelsValue = channels.Value; - if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase) || - string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase)) { if (channelsValue <= 2) { @@ -248,6 +248,34 @@ namespace MediaBrowser.MediaEncoding.Probing } } + if (string.Equals(codec, "ac3", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase)) + { + if (channelsValue <= 2) + { + return 192000; + } + + if (channelsValue >= 5) + { + return 640000; + } + } + + if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "alac", StringComparison.OrdinalIgnoreCase)) + { + if (channelsValue <= 2) + { + return 960000; + } + + if (channelsValue >= 5) + { + return 2880000; + } + } + return null; } @@ -774,6 +802,35 @@ namespace MediaBrowser.MediaEncoding.Probing stream.BitRate = bitrate; } + // Extract bitrate info from tag "BPS" if possible. + if (!stream.BitRate.HasValue + && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase) + || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))) + { + var bps = GetBPSFromTags(streamInfo); + if (bps != null && bps > 0) + { + stream.BitRate = bps; + } + } + + // Get average bitrate info from tag "NUMBER_OF_BYTES" and "DURATION" if possible. + if (!stream.BitRate.HasValue + && (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase) + || string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))) + { + var durationInSeconds = GetRuntimeSecondsFromTags(streamInfo); + var bytes = GetNumberOfBytesFromTags(streamInfo); + if (durationInSeconds != null && bytes != null) + { + var bps = Convert.ToInt32(bytes * 8 / durationInSeconds); + if (bps > 0) + { + stream.BitRate = bps; + } + } + } + var disposition = streamInfo.Disposition; if (disposition != null) { @@ -963,6 +1020,57 @@ namespace MediaBrowser.MediaEncoding.Probing } } + private int? GetBPSFromTags(MediaStreamInfo streamInfo) + { + if (streamInfo != null && streamInfo.Tags != null) + { + var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS"); + if (!string.IsNullOrEmpty(bps)) + { + if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps)) + { + return parsedBps; + } + } + } + + return null; + } + + private double? GetRuntimeSecondsFromTags(MediaStreamInfo streamInfo) + { + if (streamInfo != null && streamInfo.Tags != null) + { + var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION"); + if (!string.IsNullOrEmpty(duration)) + { + if (TimeSpan.TryParse(duration, out var parsedDuration)) + { + return parsedDuration.TotalSeconds; + } + } + } + + return null; + } + + private long? GetNumberOfBytesFromTags(MediaStreamInfo streamInfo) + { + if (streamInfo != null && streamInfo.Tags != null) + { + var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng") ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES"); + if (!string.IsNullOrEmpty(numberOfBytes)) + { + if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes)) + { + return parsedBytes; + } + } + } + + return null; + } + private void SetSize(InternalMediaInfoResult data, MediaInfo info) { if (data.Format != null) diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index 102db3b44e..39439f1fa3 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -79,11 +79,11 @@ namespace MediaBrowser.Model.Dlna private static double GetVideoBitrateScaleFactor(string codec) { - if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || - string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) || - string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)) { - return .5; + return .6; } return 1; diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 4959a9b922..2e99fe5bf3 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -872,11 +872,34 @@ namespace MediaBrowser.Model.Dlna return playlistItem; } - private static int GetDefaultAudioBitrateIfUnknown(MediaStream audioStream) + private static int GetDefaultAudioBitrate(string audioCodec, int? audioChannels) { - if ((audioStream.Channels ?? 0) >= 6) + if (!string.IsNullOrEmpty(audioCodec)) { - return 384000; + // Default to a higher bitrate for stream copy + if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase)) + { + if ((audioChannels ?? 0) < 2) + { + return 128000; + } + + return (audioChannels ?? 0) >= 6 ? 640000 : 384000; + } + + if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase) + || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase)) + { + if ((audioChannels ?? 0) < 2) + { + return 768000; + } + + return (audioChannels ?? 0) >= 6 ? 3584000 : 1536000; + } } return 192000; @@ -897,14 +920,27 @@ namespace MediaBrowser.Model.Dlna } else { - if (targetAudioChannels.HasValue && audioStream.Channels.HasValue && targetAudioChannels.Value < audioStream.Channels.Value) + if (targetAudioChannels.HasValue + && audioStream.Channels.HasValue + && audioStream.Channels.Value > targetAudioChannels.Value) { - // Reduce the bitrate if we're downmixing - defaultBitrate = targetAudioChannels.Value < 2 ? 128000 : 192000; + // Reduce the bitrate if we're downmixing. + defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels); + } + else if (targetAudioChannels.HasValue + && audioStream.Channels.HasValue + && audioStream.Channels.Value <= targetAudioChannels.Value + && !string.IsNullOrEmpty(audioStream.Codec) + && targetAudioCodecs != null + && targetAudioCodecs.Length > 0 + && !Array.Exists(targetAudioCodecs, elem => string.Equals(audioStream.Codec, elem, StringComparison.OrdinalIgnoreCase))) + { + // Shift the bitrate if we're transcoding to a different audio codec. + defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, audioStream.Channels.Value); } else { - defaultBitrate = audioStream.BitRate ?? GetDefaultAudioBitrateIfUnknown(audioStream); + defaultBitrate = audioStream.BitRate ?? GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels); } // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate. @@ -938,8 +974,28 @@ namespace MediaBrowser.Model.Dlna { return 448000; } + else if (totalBitrate <= 4000000) + { + return 640000; + } + else if (totalBitrate <= 5000000) + { + return 768000; + } + else if (totalBitrate <= 10000000) + { + return 1536000; + } + else if (totalBitrate <= 15000000) + { + return 2304000; + } + else if (totalBitrate <= 20000000) + { + return 3584000; + } - return 640000; + return 7168000; } private (PlayMethod?, List<TranscodeReason>) GetVideoDirectPlayProfile( diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 9399d21f16..7b72a1303a 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -787,7 +787,7 @@ namespace MediaBrowser.Model.Dlna public int? GetTargetAudioChannels(string codec) { - var defaultValue = GlobalMaxAudioChannels; + var defaultValue = GlobalMaxAudioChannels ?? TranscodingMaxAudioChannels; var value = GetOption(codec, "audiochannels"); if (string.IsNullOrEmpty(value)) From 6987cb83570a6a822260691f009f4b3762d98942 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Wed, 11 Nov 2020 17:25:14 +0800 Subject: [PATCH 0290/1930] fix ci --- MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 1b0d4d1af4..d6b87477c4 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -823,7 +823,7 @@ namespace MediaBrowser.MediaEncoding.Probing var bytes = GetNumberOfBytesFromTags(streamInfo); if (durationInSeconds != null && bytes != null) { - var bps = Convert.ToInt32(bytes * 8 / durationInSeconds); + var bps = Convert.ToInt32(bytes * 8 / durationInSeconds, CultureInfo.InvariantCulture); if (bps > 0) { stream.BitRate = bps; From 0b954df7c2052be74792b1e7ec6c46855e36f4b2 Mon Sep 17 00:00:00 2001 From: Claus Vium <cvium@users.noreply.github.com> Date: Wed, 11 Nov 2020 10:49:00 +0100 Subject: [PATCH 0291/1930] Update Jellyfin.Api/Controllers/LibraryController.cs --- Jellyfin.Api/Controllers/LibraryController.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 99fbfb4026..0d5c1d2782 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -710,8 +710,7 @@ namespace Jellyfin.Api.Controllers var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - var dtoOptions = new DtoOptions() - .AddItemFields(fields) + var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request); var program = item as IHasProgramAttributes; From 11c74cb65cd936f0fece57357beb7a27741edc24 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Wed, 11 Nov 2020 19:04:58 +0800 Subject: [PATCH 0292/1930] fix for no audio stream video --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 5 +++++ .../MediaEncoding/EncodingHelper.cs | 5 +++++ .../MediaEncoding/EncodingJobInfo.cs | 10 ++++++++++ 3 files changed, 20 insertions(+) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 4cf4c24d77..0581928a0c 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1429,6 +1429,11 @@ namespace Jellyfin.Api.Controllers private string GetAudioArguments(StreamState state, EncodingOptions encodingOptions) { + if (state.AudioStream == null) + { + return string.Empty; + } + var audioCodec = _encodingHelper.GetAudioEncoder(state); if (!state.IsOutputVideo) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index e8b4869ee9..caf3ef1694 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1518,6 +1518,11 @@ namespace MediaBrowser.Controller.MediaEncoding /// <returns>System.Nullable{System.Int32}.</returns> public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec) { + if (audioStream == null) + { + return null; + } + var request = state.BaseRequest; var inputChannels = audioStream?.Channels; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 6e9362cd14..09e7889b9f 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -593,6 +593,11 @@ namespace MediaBrowser.Controller.MediaEncoding { get { + if (VideoStream == null) + { + return null; + } + if (EncodingHelper.IsCopyCodec(OutputVideoCodec)) { return VideoStream?.Codec; @@ -606,6 +611,11 @@ namespace MediaBrowser.Controller.MediaEncoding { get { + if (AudioStream == null) + { + return null; + } + if (EncodingHelper.IsCopyCodec(OutputAudioCodec)) { return AudioStream?.Codec; From 7375d703960d737d183288dde16963d23be61375 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 11 Nov 2020 07:17:19 -0700 Subject: [PATCH 0293/1930] Skip migration if user doesn't exist --- .../Routines/MigrateDisplayPreferencesDb.cs | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 7f57358ec0..a20ab6f384 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -9,6 +9,7 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Server.Implementations; using MediaBrowser.Controller; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; using Microsoft.Extensions.Logging; using SQLitePCL.pretty; @@ -26,6 +27,7 @@ namespace Jellyfin.Server.Migrations.Routines private readonly IServerApplicationPaths _paths; private readonly JellyfinDbProvider _provider; private readonly JsonSerializerOptions _jsonOptions; + private readonly IUserManager _userManager; /// <summary> /// Initializes a new instance of the <see cref="MigrateDisplayPreferencesDb"/> class. @@ -33,11 +35,17 @@ namespace Jellyfin.Server.Migrations.Routines /// <param name="logger">The logger.</param> /// <param name="paths">The server application paths.</param> /// <param name="provider">The database provider.</param> - public MigrateDisplayPreferencesDb(ILogger<MigrateDisplayPreferencesDb> logger, IServerApplicationPaths paths, JellyfinDbProvider provider) + /// <param name="userManager">The user manager.</param> + public MigrateDisplayPreferencesDb( + ILogger<MigrateDisplayPreferencesDb> logger, + IServerApplicationPaths paths, + JellyfinDbProvider provider, + IUserManager userManager) { _logger = logger; _paths = paths; _provider = provider; + _userManager = userManager; _jsonOptions = new JsonSerializerOptions(); _jsonOptions.Converters.Add(new JsonStringEnumConverter()); } @@ -86,11 +94,19 @@ namespace Jellyfin.Server.Migrations.Routines continue; } + var dtoUserId = new Guid(result[1].ToBlob()); + var existingUser = _userManager.GetUserById(dtoUserId); + if (existingUser == null) + { + _logger.LogWarning("User with ID {userId} does not exist in the database, skipping migration.", dtoUserId); + continue; + } + var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version) ? chromecastDict[version] : ChromecastVersion.Stable; - var displayPreferences = new DisplayPreferences(new Guid(result[1].ToBlob()), result[2].ToString()) + var displayPreferences = new DisplayPreferences(dtoUserId, result[2].ToString()) { IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null, ShowBackdrop = dto.ShowBackdrop, From 380359b495f234450b21eafd2e64fa84b1bf2dcb Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 11 Nov 2020 08:03:30 -0700 Subject: [PATCH 0294/1930] Add migration to readd plugin. --- Jellyfin.Server/Migrations/MigrationRunner.cs | 3 +- .../Routines/DownloadTheTvdbPlugin.cs | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index 844dae61f6..68815655b3 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -23,7 +23,8 @@ namespace Jellyfin.Server.Migrations typeof(Routines.AddDefaultPluginRepository), typeof(Routines.MigrateUserDb), typeof(Routines.ReaddDefaultPluginRepository), - typeof(Routines.MigrateDisplayPreferencesDb) + typeof(Routines.MigrateDisplayPreferencesDb), + typeof(Routines.DownloadTheTvdbPlugin) }; /// <summary> diff --git a/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs b/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs new file mode 100644 index 0000000000..0dfb27bc98 --- /dev/null +++ b/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs @@ -0,0 +1,63 @@ +using System; +using System.Linq; +using MediaBrowser.Common.Updates; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Migrations.Routines +{ + /// <summary> + /// Download TheTvdb plugin after update. + /// </summary> + public class DownloadTheTvdbPlugin : IMigrationRoutine + { + private readonly Guid _tvdbPluginId = new Guid("a677c0da-fac5-4cde-941a-7134223f14c8"); + private readonly IInstallationManager _installationManager; + private readonly ILogger<DownloadTheTvdbPlugin> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="DownloadTheTvdbPlugin"/> class. + /// </summary> + /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param> + /// <param name="logger">Instance of the <see cref="ILogger{DownloadTvdbPlugin}"/> interface.</param> + public DownloadTheTvdbPlugin(IInstallationManager installationManager, ILogger<DownloadTheTvdbPlugin> logger) + { + _installationManager = installationManager; + _logger = logger; + } + + /// <inheritdoc /> + public Guid Id => new Guid("42E45BB4-5D78-4EE2-8C45-9095216D4769"); + + /// <inheritdoc /> + public string Name => "DownloadTheTvdbPlugin"; + + /// <inheritdoc /> + public bool PerformOnNewInstall => false; + + /// <inheritdoc /> + public void Perform() + { + try + { + var packages = _installationManager.GetAvailablePackages().GetAwaiter().GetResult(); + var package = _installationManager.GetCompatibleVersions( + packages, + guid: _tvdbPluginId) + .FirstOrDefault(); + + if (package == null) + { + _logger.LogWarning("TheTVDB Plugin not found, skipping migration."); + return; + } + + _installationManager.InstallPackage(package).GetAwaiter().GetResult(); + _logger.LogInformation("TheTVDB Plugin installed, please restart Jellyfin."); + } + catch (Exception e) + { + _logger.LogWarning(e, "Unable to install TheTVDB Plugin."); + } + } + } +} \ No newline at end of file From caea2bb8623c37ef1162c6132dcfc36439bb2f1a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 11 Nov 2020 17:00:19 +0000 Subject: [PATCH 0295/1930] Update Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs Co-authored-by: Bond-009 <bond.009@outlook.com> --- Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 15bf92db1d..4f72c8ce15 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -140,7 +140,7 @@ namespace Emby.Server.Implementations.AppBase public virtual void RegisterConfiguration<T>() where T : IConfigurationFactory { - IConfigurationFactory factory = (IConfigurationFactory)Activator.CreateInstance(typeof(T)); + IConfigurationFactory factory = Activator.CreateInstance<T>(); if (_configurationFactories == null) { From d0cf60e145f7424e1bdef6f3f7e0d760d4d11096 Mon Sep 17 00:00:00 2001 From: Kayila <arekuanubis@gmail.com> Date: Wed, 11 Nov 2020 13:47:42 -0500 Subject: [PATCH 0296/1930] Fixes #4465 by adding the missing extras folders. --- MediaBrowser.Controller/Entities/BaseItem.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 2fc7d45c90..1d44a55114 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -87,6 +87,8 @@ namespace MediaBrowser.Controller.Entities public const string InterviewFolderName = "interviews"; public const string SceneFolderName = "scenes"; public const string SampleFolderName = "samples"; + public const string ShortsFolderName = "shorts"; + public const string FeaturettesFolderName = "featurettes"; public static readonly string[] AllExtrasTypesFolderNames = { ExtrasFolderName, @@ -94,7 +96,9 @@ namespace MediaBrowser.Controller.Entities DeletedScenesFolderName, InterviewFolderName, SceneFolderName, - SampleFolderName + SampleFolderName, + ShortsFolderName, + FeaturettesFolderName }; [JsonIgnore] From 51996cd34dface6c9d6a6fb969bd412ac8cb56f7 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 11 Nov 2020 19:04:22 +0000 Subject: [PATCH 0297/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index ae9218bcd1..e21d8c7d1b 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -56,8 +56,7 @@ namespace MediaBrowser.Common.Plugins /// Gets a value indicating whether the plugin can be uninstalled. /// </summary> public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) - .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture) - && !typeof(IPluginServiceRegistrator).IsAssignableFrom(this.GetType()); + .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture); /// <summary> /// Gets the plugin info. From 5bd0c2b69d0f4fccd09866a67c741742710372dc Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 12 Nov 2020 11:02:56 +0800 Subject: [PATCH 0298/1930] add an option to disable hevc encoding --- Jellyfin.Api/Helpers/StreamingHelpers.cs | 4 +- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 3 +- .../MediaEncoding/EncodingHelper.cs | 43 ++++++++++++++++++- .../Configuration/EncodingOptions.cs | 3 ++ 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 5bd347846d..be85d5eb83 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -165,7 +165,9 @@ namespace Jellyfin.Api.Helpers state.DirectStreamProvider = liveStreamInfo.Item2; } - encodingHelper.AttachMediaSourceInfo(state, mediaSource, url); + var encodingOptions = serverConfigurationManager.GetEncodingOptions(); + + encodingHelper.AttachMediaSourceInfo(state, encodingOptions, mediaSource, url); string? containerInternal = Path.GetExtension(state.RequestedUrl); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 0db1fabffe..f93c95fb55 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -770,8 +770,9 @@ namespace Jellyfin.Api.Helpers new LiveStreamRequest { OpenToken = state.MediaSource.OpenToken }, cancellationTokenSource.Token) .ConfigureAwait(false); + var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); - _encodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.RequestedUrl); + _encodingHelper.AttachMediaSourceInfo(state, encodingOptions, liveStreamResponse.MediaSource, state.RequestedUrl); if (state.VideoRequest != null) { diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index caf3ef1694..1074f876c7 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2631,6 +2631,7 @@ namespace MediaBrowser.Controller.MediaEncoding public void AttachMediaSourceInfo( EncodingJobInfo state, + EncodingOptions encodingOptions, MediaSourceInfo mediaSource, string requestedUrl) { @@ -2761,11 +2762,23 @@ namespace MediaBrowser.Controller.MediaEncoding request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i)) ?? state.SupportedAudioCodecs.FirstOrDefault(); } + + var supportedVideoCodecs = state.SupportedVideoCodecs; + if (request != null && supportedVideoCodecs != null && supportedVideoCodecs.Length > 0) + { + var supportedVideoCodecsList = supportedVideoCodecs.ToList(); + + ShiftVideoCodecsIfNeeded(supportedVideoCodecsList, encodingOptions); + + state.SupportedVideoCodecs = supportedVideoCodecsList.ToArray(); + + request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault(); + } } private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream) { - // Nothing to do here + // No need to shift if there is only one supported audio codec. if (audioCodecs.Count < 2) { return; @@ -2793,6 +2806,34 @@ namespace MediaBrowser.Controller.MediaEncoding } } + private void ShiftVideoCodecsIfNeeded(List<string> videoCodecs, EncodingOptions encodingOptions) + { + // Shift hevc/h265 to the end of list if hevc encoding is not allowed. + if (encodingOptions.AllowHevcEncoding) + { + return; + } + + // No need to shift if there is only one supported video codec. + if (videoCodecs.Count < 2) + { + return; + } + + var shiftVideoCodecs = new[] { "hevc", "h265" }; + if (videoCodecs.All(i => shiftVideoCodecs.Contains(i, StringComparer.OrdinalIgnoreCase))) + { + return; + } + + while (shiftVideoCodecs.Contains(videoCodecs[0], StringComparer.OrdinalIgnoreCase)) + { + var removed = shiftVideoCodecs[0]; + videoCodecs.RemoveAt(0); + videoCodecs.Add(removed); + } + } + private void NormalizeSubtitleEmbed(EncodingJobInfo state) { if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed) diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index 2cd637c5b0..2d46889724 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -63,6 +63,8 @@ namespace MediaBrowser.Model.Configuration public bool EnableHardwareEncoding { get; set; } + public bool AllowHevcEncoding { get; set; } + public bool EnableSubtitleExtraction { get; set; } public string[] HardwareDecodingCodecs { get; set; } @@ -94,6 +96,7 @@ namespace MediaBrowser.Model.Configuration EnableDecodingColorDepth10Hevc = true; EnableDecodingColorDepth10Vp9 = true; EnableHardwareEncoding = true; + AllowHevcEncoding = true; EnableSubtitleExtraction = true; HardwareDecodingCodecs = new string[] { "h264", "vc1" }; } From 0ac3af13ace6b1689ffd976219f7eb0d915501f9 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 12 Nov 2020 09:21:46 +0100 Subject: [PATCH 0299/1930] Semi-revert removal of Name for /Similar in openapi --- Jellyfin.Api/Controllers/LibraryController.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 0d5c1d2782..5469304400 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -681,12 +681,12 @@ namespace Jellyfin.Api.Controllers /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> /// <response code="200">Similar items returned.</response> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> containing the similar items.</returns> - [HttpGet("Artists/{itemId}/Similar")] + [HttpGet("Artists/{itemId}/Similar", Name = "GetSimilarArtists")] [HttpGet("Items/{itemId}/Similar")] - [HttpGet("Albums/{itemId}/Similar")] - [HttpGet("Shows/{itemId}/Similar")] - [HttpGet("Movies/{itemId}/Similar")] - [HttpGet("Trailers/{itemId}/Similar")] + [HttpGet("Albums/{itemId}/Similar", Name = "GetSimilarAlbums")] + [HttpGet("Shows/{itemId}/Similar", Name = "GetSimilarShows")] + [HttpGet("Movies/{itemId}/Similar", Name = "GetSimilarMovies")] + [HttpGet("Trailers/{itemId}/Similar", Name = "GetSimilarTrailers")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems( From 8e0909ef6f93d452a0c4f5c3be5b10f4027fae76 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 12 Nov 2020 10:13:56 +0100 Subject: [PATCH 0300/1930] Change OPTIONS to POST and call SaveConfiguration --- Jellyfin.Api/Controllers/PackageController.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 1d9de14d2d..d7c6a484a4 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -149,12 +149,13 @@ namespace Jellyfin.Api.Controllers /// <param name="repositoryInfos">The list of package repositories.</param> /// <response code="204">Package repositories saved.</response> /// <returns>A <see cref="NoContentResult"/>.</returns> - [HttpOptions("Repositories")] + [HttpPost("Repositories")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SetRepositories([FromBody] List<RepositoryInfo> repositoryInfos) { _serverConfigurationManager.Configuration.PluginRepositories = repositoryInfos; + _serverConfigurationManager.SaveConfiguration(); return NoContent(); } } From 496923719c405cd9b0386f7d31fcb204cdaeb9c4 Mon Sep 17 00:00:00 2001 From: martinek-stepan <68327580+martinek-stepan@users.noreply.github.com> Date: Thu, 12 Nov 2020 12:54:55 +0100 Subject: [PATCH 0301/1930] Apply suggestions from code review Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- Emby.Naming/AudioBook/AudioBookListResolver.cs | 6 +++--- Emby.Naming/Video/VideoListResolver.cs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index b203f99022..54c1fe5bd3 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -33,7 +33,7 @@ namespace Emby.Naming.AudioBook { var audioBookResolver = new AudioBookResolver(_options); - // File with empty fullname will be sorted out here + // File with empty fullname will be sorted out here. var audiobookFileInfos = files .Select(i => audioBookResolver.Resolve(i.FullName)) .OfType<AudioBookFileInfo>() @@ -139,8 +139,8 @@ namespace Emby.Naming.AudioBook private AudioBookFileInfo FindMainAudioBookFile(List<AudioBookFileInfo> files, string name) { - var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path) == name); - main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path) == "audiobook"); + var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name)); + main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook")); main ??= files.OrderBy(x => x.Container) .ThenBy(x => x.Path) .First(); diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index ee0e4d4659..1e18c4452d 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -147,7 +147,7 @@ namespace Emby.Naming.Video } // If there's only one video, accept all trailers - // Be lenient because people use all kinds of mishmash conventions with trailers + // Be lenient because people use all kinds of mishmash conventions with trailers. if (list.Count == 1) { var trailers = remainingFiles @@ -231,7 +231,7 @@ namespace Emby.Naming.Video testFilename = testFilename.Substring(folderName.Length).Trim(); return string.IsNullOrEmpty(testFilename) || testFilename[0] == '-' - || testFilename[0] == '_' + || testFilename[0].Equals( '_') || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); } From 3bca1181b3c91115e693dc83ba1f5fdd6ee38f7c Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Thu, 12 Nov 2020 13:16:33 +0100 Subject: [PATCH 0302/1930] Taken suggestions from code review and created test for ExtraRuleType.Regex instead of throwing exception there. --- Emby.Naming/AudioBook/AudioBookListResolver.cs | 5 +++-- Emby.Naming/Video/ExtraResolver.cs | 10 +--------- Emby.Naming/Video/VideoListResolver.cs | 4 ++-- .../Video/CleanDateTimeTests.cs | 4 +++- tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs | 14 +++++--------- 5 files changed, 14 insertions(+), 23 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 54c1fe5bd3..95817efc3e 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -73,6 +73,7 @@ namespace Emby.Naming.AudioBook var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber != null || x.PartNumber != null); var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber }); + var nameWithReplacedDots = nameParserResult.Name.Replace(" ", "."); foreach (var group in groupedBy) { @@ -86,9 +87,9 @@ namespace Emby.Naming.AudioBook foreach (var audioFile in group) { var name = Path.GetFileNameWithoutExtension(audioFile.Path); - if (name == "audiobook" || + if (name.Equals("audiobook") || name.Contains(nameParserResult.Name, StringComparison.OrdinalIgnoreCase) || - name.Contains(nameParserResult.Name.Replace(" ", "."), StringComparison.OrdinalIgnoreCase)) + name.Contains(nameWithReplacedDots, StringComparison.OrdinalIgnoreCase)) { alt.Add(audioFile); } diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index dd934d91b0..1d3b36a1ad 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Text.RegularExpressions; using Emby.Naming.Audio; using Emby.Naming.Common; @@ -52,11 +53,6 @@ namespace Emby.Naming.Video return result; } } - else - { - // Currently unreachable code if new rule.MediaType is desired add if clause with proper tests - throw new InvalidOperationException(); - } if (rule.RuleType == ExtraRuleType.Filename) { @@ -80,9 +76,6 @@ namespace Emby.Naming.Video } else if (rule.RuleType == ExtraRuleType.Regex) { - // Currently unreachable code if new rule.MediaType is desired add if clause with proper tests - throw new InvalidOperationException(); - /* var filename = Path.GetFileName(path); var regex = new Regex(rule.Token, RegexOptions.IgnoreCase); @@ -92,7 +85,6 @@ namespace Emby.Naming.Video result.ExtraType = rule.ExtraType; result.Rule = rule; } - */ } else if (rule.RuleType == ExtraRuleType.DirectoryName) { diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 1e18c4452d..2fd2d3e8b2 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -230,8 +230,8 @@ namespace Emby.Naming.Video testFilename = testFilename.Substring(folderName.Length).Trim(); return string.IsNullOrEmpty(testFilename) - || testFilename[0] == '-' - || testFilename[0].Equals( '_') + || testFilename[0].Equals('-') + || testFilename[0].Equals('_') || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs index ed971eed7b..15cb5c72fa 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanDateTimeTests.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using Emby.Naming.Common; using Emby.Naming.Video; using Xunit; @@ -51,6 +51,8 @@ namespace Jellyfin.Naming.Tests.Video [InlineData("My Movie 2013-12-09", "My Movie 2013-12-09", null)] [InlineData("My Movie 20131209", "My Movie 20131209", null)] [InlineData("My Movie 2013-12-09 2013", "My Movie 2013-12-09", 2013)] + [InlineData(null, null, null)] + [InlineData("", "", null)] public void CleanDateTimeTest(string input, string expectedName, int? expectedYear) { input = Path.GetFileName(input); diff --git a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs index 12a9b023bf..d34f65409f 100644 --- a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs @@ -95,18 +95,14 @@ namespace Jellyfin.Naming.Tests.Video } } - [Fact] - public void TestExtraInfo_InvalidRuleMediaType() - { - var options = new NamingOptions { VideoExtraRules = new[] { new ExtraRule(ExtraType.Unknown, ExtraRuleType.DirectoryName, " ", MediaType.Photo) } }; - Assert.Throws<InvalidOperationException>(() => GetExtraTypeParser(options).GetExtraInfo("sample.jpg")); - } - [Fact] public void TestExtraInfo_InvalidRuleType() { - var options = new NamingOptions { VideoExtraRules = new[] { new ExtraRule(ExtraType.Unknown, ExtraRuleType.Regex, " ", MediaType.Video) } }; - Assert.Throws<InvalidOperationException>(() => GetExtraTypeParser(options).GetExtraInfo("sample.mp4")); + var rule = new ExtraRule(ExtraType.Unknown, ExtraRuleType.Regex, @"([eE]x(tra)?\.\w+)", MediaType.Video); + var options = new NamingOptions { VideoExtraRules = new[] { rule } }; + var res = GetExtraTypeParser(options).GetExtraInfo("extra.mp4"); + + Assert.Equal(rule, res.Rule); } [Fact] From b66239fd521150078d96314e58c61d09ea2888ae Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Thu, 12 Nov 2020 13:18:22 +0100 Subject: [PATCH 0303/1930] One more missed suggestions (removing commented out code) --- Emby.Naming/Video/VideoListResolver.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 2fd2d3e8b2..19cc491cfb 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -37,7 +37,6 @@ namespace Emby.Naming.Video var videoInfos = files .Select(i => videoResolver.Resolve(i.FullName, i.IsDirectory)) - // .Where(i => i != null) .OfType<VideoFileInfo>() .ToList(); From 1d059bc76bf74673f29b66881d4a153c063c172e Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Thu, 12 Nov 2020 07:33:12 -0700 Subject: [PATCH 0304/1930] Update Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs --- .../Migrations/Routines/MigrateDisplayPreferencesDb.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index a20ab6f384..8992c281db 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -98,7 +98,7 @@ namespace Jellyfin.Server.Migrations.Routines var existingUser = _userManager.GetUserById(dtoUserId); if (existingUser == null) { - _logger.LogWarning("User with ID {userId} does not exist in the database, skipping migration.", dtoUserId); + _logger.LogWarning("User with ID {UserId} does not exist in the database, skipping migration.", dtoUserId); continue; } From 0c23b8cadf8d4163b0db664a8b2cfb717181eb02 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 12 Nov 2020 08:06:25 -0700 Subject: [PATCH 0305/1930] Don't throw exception when converting values using binder or JsonConverter --- .../CommaDelimitedArrayModelBinder.cs | 65 ++++++++++++++----- .../JsonCommaDelimitedArrayConverter.cs | 27 +++++++- .../CommaDelimitedArrayModelBinderTests.cs | 33 +++++----- 3 files changed, 89 insertions(+), 36 deletions(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index 4f012cab20..fd9f724b18 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging; namespace Jellyfin.Api.ModelBinders { @@ -11,6 +13,17 @@ namespace Jellyfin.Api.ModelBinders /// </summary> public class CommaDelimitedArrayModelBinder : IModelBinder { + private readonly ILogger<CommaDelimitedArrayModelBinder> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="CommaDelimitedArrayModelBinder"/> class. + /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger{CommaDelimitedArrayModelBinder}"/> interface.</param> + public CommaDelimitedArrayModelBinder(ILogger<CommaDelimitedArrayModelBinder> logger) + { + _logger = logger; + } + /// <inheritdoc/> public Task BindModelAsync(ModelBindingContext bindingContext) { @@ -20,16 +33,8 @@ namespace Jellyfin.Api.ModelBinders if (valueProviderResult.Length > 1) { - var result = Array.CreateInstance(elementType, valueProviderResult.Length); - - for (int i = 0; i < valueProviderResult.Length; i++) - { - var value = converter.ConvertFromString(valueProviderResult.Values[i].Trim()); - - result.SetValue(value, i); - } - - bindingContext.Result = ModelBindingResult.Success(result); + var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter); + bindingContext.Result = ModelBindingResult.Success(typedValues); } else { @@ -37,13 +42,8 @@ namespace Jellyfin.Api.ModelBinders if (value != null) { - var values = Array.ConvertAll( - value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries), - x => converter.ConvertFromString(x?.Trim())); - - var typedValues = Array.CreateInstance(elementType, values.Length); - values.CopyTo(typedValues, 0); - + var splitValues = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); + var typedValues = GetParsedResult(splitValues, elementType, converter); bindingContext.Result = ModelBindingResult.Success(typedValues); } else @@ -55,5 +55,36 @@ namespace Jellyfin.Api.ModelBinders return Task.CompletedTask; } + + private Array GetParsedResult(IReadOnlyList<string> values, Type elementType, TypeConverter converter) + { + var parsedValues = new object?[values.Count]; + var convertedCount = 0; + for (var i = 0; i < values.Count; i++) + { + try + { + parsedValues[i] = converter.ConvertFromString(values[i]?.Trim()); + convertedCount++; + } + catch (FormatException e) + { + _logger.LogWarning(e, "Error converting value."); + } + } + + var typedValues = Array.CreateInstance(elementType, convertedCount); + var typedValueIndex = 0; + for (var i = 0; i < parsedValues.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; + } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index bf7048c370..b24a497613 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -32,13 +32,34 @@ namespace MediaBrowser.Common.Json.Converters return Array.Empty<T>(); } - var entries = new T[stringEntries.Length]; + var parsedValues = new object[stringEntries.Length]; + var convertedCount = 0; for (var i = 0; i < stringEntries.Length; i++) { - entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i].Trim()); + try + { + parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim()); + convertedCount++; + } + catch (FormatException) + { + // TODO log when upgraded to .Net5 + // _logger.LogWarning(e, "Error converting value."); + } } - return entries; + var typedValues = new T[convertedCount]; + var typedValueIndex = 0; + for (var i = 0; i < stringEntries.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; } return JsonSerializer.Deserialize<T[]>(ref reader, options); diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs index 89c7d62f79..82c7f6427d 100644 --- a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs +++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using Jellyfin.Api.ModelBinders; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Primitives; using Moq; using Xunit; @@ -21,7 +22,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamString = "lol,xd"; var queryParamType = typeof(string[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), @@ -46,7 +47,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamString = "42,0"; var queryParamType = typeof(int[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), @@ -71,7 +72,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamString = "How,Much"; var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), @@ -96,7 +97,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamString = "How,,Much"; var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), @@ -122,7 +123,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamString2 = "Much"; var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), @@ -150,7 +151,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamValues = Array.Empty<TestType>(); var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), @@ -172,13 +173,13 @@ namespace Jellyfin.Api.Tests.ModelBinders } [Fact] - public async Task BindModelAsync_ThrowsIfCommaDelimitedEnumArrayQueryIsInvalid() + public async Task BindModelAsync_EnumArrayQuery_BindValidOnly() { var queryParamName = "test"; var queryParamString = "🔥,😢"; var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), @@ -189,20 +190,20 @@ namespace Jellyfin.Api.Tests.ModelBinders bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); bindingContextMock.SetupProperty(b => b.Result); - Func<Task> act = async () => await modelBinder.BindModelAsync(bindingContextMock.Object); - - await Assert.ThrowsAsync<FormatException>(act); + await modelBinder.BindModelAsync(bindingContextMock.Object); + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Empty((TestType[])bindingContextMock.Object.Result.Model); } [Fact] - public async Task BindModelAsync_ThrowsIfCommaDelimitedEnumArrayQueryIsInvalid2() + public async Task BindModelAsync_EnumArrayQuery_BindValidOnly_2() { var queryParamName = "test"; var queryParamString1 = "How"; var queryParamString2 = "😱"; var queryParamType = typeof(TestType[]); - var modelBinder = new CommaDelimitedArrayModelBinder(); + var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( new BindingSource(string.Empty, string.Empty, false, false), @@ -217,9 +218,9 @@ namespace Jellyfin.Api.Tests.ModelBinders bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); bindingContextMock.SetupProperty(b => b.Result); - Func<Task> act = async () => await modelBinder.BindModelAsync(bindingContextMock.Object); - - await Assert.ThrowsAsync<FormatException>(act); + await modelBinder.BindModelAsync(bindingContextMock.Object); + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Single((TestType[])bindingContextMock.Object.Result.Model); } } } From d91a099c9e04cb39d1b8e387dba0b44dde64342d Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 12 Nov 2020 23:10:57 +0800 Subject: [PATCH 0306/1930] allow transcoding 8ch(7.1 layout) in aac --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1074f876c7..1ae896df0f 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1545,6 +1545,11 @@ namespace MediaBrowser.Controller.MediaEncoding // libmp3lame currently only supports two channel output transcoderChannelLimit = 2; } + else if (codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1) + { + // aac is able to handle 8ch(7.1 layout) + transcoderChannelLimit = 8; + } else { // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels From 73f9a6d7d057a9fd0a3ab24a52bd82e768f39705 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 12 Nov 2020 08:29:42 -0700 Subject: [PATCH 0307/1930] Convert array property to IReadOnlyList --- .../LiveTv/LiveTvManager.cs | 2 +- Jellyfin.Api/Extensions/DtoExtensions.cs | 10 ++++++---- .../Models/LibraryDtos/LibraryOptionsResultDto.cs | 15 ++++++--------- .../Models/LibraryDtos/LibraryTypeOptionsDto.cs | 15 ++++++--------- .../Models/LiveTvDtos/ChannelMappingOptionsDto.cs | 6 +++--- Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs | 7 +++---- .../Models/MediaInfoDtos/OpenLiveStreamDto.cs | 7 +++---- MediaBrowser.Controller/Dto/DtoOptions.cs | 5 +++-- MediaBrowser.Controller/LiveTv/ILiveTvManager.cs | 2 +- MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs | 3 ++- 10 files changed, 34 insertions(+), 38 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 9c7d624ee1..5b9c5761ef 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1429,7 +1429,7 @@ namespace Emby.Server.Implementations.LiveTv return result; } - public Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> tuples, ItemFields[] fields, User user = null) + public Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> tuples, IReadOnlyList<ItemFields> fields, User user = null) { var programTuples = new List<Tuple<BaseItemDto, string, string>>(); var hasChannelImage = fields.Contains(ItemFields.ChannelImage); diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index 6dee9db380..f2abd515d3 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using System.Linq; using Jellyfin.Api.Helpers; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -43,7 +45,7 @@ namespace Jellyfin.Api.Extensions client.IndexOf("media center", StringComparison.OrdinalIgnoreCase) != -1 || client.IndexOf("classic", StringComparison.OrdinalIgnoreCase) != -1) { - int oldLen = dtoOptions.Fields.Length; + int oldLen = dtoOptions.Fields.Count; var arr = new ItemFields[oldLen + 1]; dtoOptions.Fields.CopyTo(arr, 0); arr[oldLen] = ItemFields.RecursiveItemCount; @@ -61,7 +63,7 @@ namespace Jellyfin.Api.Extensions client.IndexOf("samsung", StringComparison.OrdinalIgnoreCase) != -1 || client.IndexOf("androidtv", StringComparison.OrdinalIgnoreCase) != -1) { - int oldLen = dtoOptions.Fields.Length; + int oldLen = dtoOptions.Fields.Count; var arr = new ItemFields[oldLen + 1]; dtoOptions.Fields.CopyTo(arr, 0); arr[oldLen] = ItemFields.ChildCount; @@ -90,7 +92,7 @@ namespace Jellyfin.Api.Extensions bool? enableImages, bool? enableUserData, int? imageTypeLimit, - ImageType[] enableImageTypes) + IReadOnlyList<ImageType> enableImageTypes) { dtoOptions.EnableImages = enableImages ?? true; @@ -104,7 +106,7 @@ namespace Jellyfin.Api.Extensions dtoOptions.EnableUserData = enableUserData.Value; } - if (enableImageTypes.Length != 0) + if (enableImageTypes.Count != 0) { dtoOptions.ImageTypes = enableImageTypes; } diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs index 33eda33cb9..7de44aa659 100644 --- a/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs +++ b/Jellyfin.Api/Models/LibraryDtos/LibraryOptionsResultDto.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using System; +using System.Collections.Generic; namespace Jellyfin.Api.Models.LibraryDtos { @@ -10,25 +11,21 @@ namespace Jellyfin.Api.Models.LibraryDtos /// <summary> /// Gets or sets the metadata savers. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataSavers", Justification = "Imported from ServiceStack")] - public LibraryOptionInfoDto[] MetadataSavers { get; set; } = null!; + public IReadOnlyList<LibraryOptionInfoDto> MetadataSavers { get; set; } = Array.Empty<LibraryOptionInfoDto>(); /// <summary> /// Gets or sets the metadata readers. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataReaders", Justification = "Imported from ServiceStack")] - public LibraryOptionInfoDto[] MetadataReaders { get; set; } = null!; + public IReadOnlyList<LibraryOptionInfoDto> MetadataReaders { get; set; } = Array.Empty<LibraryOptionInfoDto>(); /// <summary> /// Gets or sets the subtitle fetchers. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SubtitleFetchers", Justification = "Imported from ServiceStack")] - public LibraryOptionInfoDto[] SubtitleFetchers { get; set; } = null!; + public IReadOnlyList<LibraryOptionInfoDto> SubtitleFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>(); /// <summary> /// Gets or sets the type options. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "TypeOptions", Justification = "Imported from ServiceStack")] - public LibraryTypeOptionsDto[] TypeOptions { get; set; } = null!; + public IReadOnlyList<LibraryTypeOptionsDto> TypeOptions { get; set; } = Array.Empty<LibraryTypeOptionsDto>(); } } diff --git a/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs index ad031e95e5..20f45196d2 100644 --- a/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs +++ b/Jellyfin.Api/Models/LibraryDtos/LibraryTypeOptionsDto.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using System; +using System.Collections.Generic; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; @@ -17,25 +18,21 @@ namespace Jellyfin.Api.Models.LibraryDtos /// <summary> /// Gets or sets the metadata fetchers. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "MetadataFetchers", Justification = "Imported from ServiceStack")] - public LibraryOptionInfoDto[] MetadataFetchers { get; set; } = null!; + public IReadOnlyList<LibraryOptionInfoDto> MetadataFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>(); /// <summary> /// Gets or sets the image fetchers. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "ImageFetchers", Justification = "Imported from ServiceStack")] - public LibraryOptionInfoDto[] ImageFetchers { get; set; } = null!; + public IReadOnlyList<LibraryOptionInfoDto> ImageFetchers { get; set; } = Array.Empty<LibraryOptionInfoDto>(); /// <summary> /// Gets or sets the supported image types. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "SupportedImageTypes", Justification = "Imported from ServiceStack")] - public ImageType[] SupportedImageTypes { get; set; } = null!; + public IReadOnlyList<ImageType> SupportedImageTypes { get; set; } = Array.Empty<ImageType>(); /// <summary> /// Gets or sets the default image options. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "DefaultImageOptions", Justification = "Imported from ServiceStack")] - public ImageOption[] DefaultImageOptions { get; set; } = null!; + public IReadOnlyList<ImageOption> DefaultImageOptions { get; set; } = Array.Empty<ImageOption>(); } } diff --git a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs index 970d8acdbc..f43822da77 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/ChannelMappingOptionsDto.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; @@ -25,8 +26,7 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// <summary> /// Gets or sets list of mappings. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:DontReturnArrays", MessageId = "Mappings", Justification = "Imported from ServiceStack")] - public NameValuePair[] Mappings { get; set; } = null!; + public IReadOnlyList<NameValuePair> Mappings { get; set; } = Array.Empty<NameValuePair>(); /// <summary> /// Gets or sets provider name. diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index aa98651922..5ca4408d18 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using MediaBrowser.Common.Json.Converters; @@ -143,8 +144,7 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// Optional. /// </summary> [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "EnableImageTypes", Justification = "Imported from ServiceStack")] - public ImageType[] EnableImageTypes { get; set; } = Array.Empty<ImageType>(); + public IReadOnlyList<ImageType> EnableImageTypes { get; set; } = Array.Empty<ImageType>(); /// <summary> /// Gets or sets include user data. @@ -169,7 +169,6 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// Optional. /// </summary> [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] - [SuppressMessage("Microsoft.Performance", "CA1819:ReturnArrays", MessageId = "Fields", Justification = "Imported from ServiceStack")] - public ItemFields[] Fields { get; set; } = Array.Empty<ItemFields>(); + public IReadOnlyList<ItemFields> Fields { get; set; } = Array.Empty<ItemFields>(); } } diff --git a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs index f797a38076..b0b3de8553 100644 --- a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs +++ b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs @@ -1,4 +1,5 @@ -using System.Diagnostics.CodeAnalysis; +using System; +using System.Collections.Generic; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.MediaInfo; @@ -17,8 +18,6 @@ namespace Jellyfin.Api.Models.MediaInfoDtos /// <summary> /// Gets or sets the device play protocols. /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1819:DontReturnArrays", MessageId = "DevicePlayProtocols", Justification = "Imported from ServiceStack")] - [SuppressMessage("Microsoft.Performance", "SA1011:ClosingBracketsSpace", MessageId = "DevicePlayProtocols", Justification = "Imported from ServiceStack")] - public MediaProtocol[]? DirectPlayProtocols { get; set; } + public IReadOnlyList<MediaProtocol> DirectPlayProtocols { get; set; } = Array.Empty<MediaProtocol>(); } } diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs index 76f20ace2a..3567837507 100644 --- a/MediaBrowser.Controller/Dto/DtoOptions.cs +++ b/MediaBrowser.Controller/Dto/DtoOptions.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using System.Linq; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -15,9 +16,9 @@ namespace MediaBrowser.Controller.Dto ItemFields.RefreshState }; - public ItemFields[] Fields { get; set; } + public IReadOnlyList<ItemFields> Fields { get; set; } - public ImageType[] ImageTypes { get; set; } + public IReadOnlyList<ImageType> ImageTypes { get; set; } public int ImageTypeLimit { get; set; } diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs index 6c365caa46..54495c1c40 100644 --- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs +++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs @@ -225,7 +225,7 @@ namespace MediaBrowser.Controller.LiveTv /// <param name="fields">The fields.</param> /// <param name="user">The user.</param> /// <returns>Task.</returns> - Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, ItemFields[] fields, User user = null); + Task AddInfoToProgramDto(IReadOnlyCollection<(BaseItem, BaseItemDto)> programs, IReadOnlyList<ItemFields> fields, User user = null); /// <summary> /// Saves the tuner host. diff --git a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs index a8ea405e28..36a2407067 100644 --- a/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs +++ b/MediaBrowser.Model/MediaInfo/LiveStreamRequest.cs @@ -2,6 +2,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using MediaBrowser.Model.Dlna; namespace MediaBrowser.Model.MediaInfo @@ -55,6 +56,6 @@ namespace MediaBrowser.Model.MediaInfo public bool EnableDirectStream { get; set; } - public MediaProtocol[] DirectPlayProtocols { get; set; } + public IReadOnlyList<MediaProtocol> DirectPlayProtocols { get; set; } } } From 4bfcc8b0d15a76d9d33e038cc4e5590fc1016750 Mon Sep 17 00:00:00 2001 From: martinek-stepan <68327580+martinek-stepan@users.noreply.github.com> Date: Thu, 12 Nov 2020 16:51:52 +0100 Subject: [PATCH 0308/1930] Update Emby.Naming/AudioBook/AudioBookListResolver.cs Use StringComparison.OrdinalIgnoreCase when comparing names Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- Emby.Naming/AudioBook/AudioBookListResolver.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index 95817efc3e..e9ea9b7a5d 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -140,8 +140,8 @@ namespace Emby.Naming.AudioBook private AudioBookFileInfo FindMainAudioBookFile(List<AudioBookFileInfo> files, string name) { - var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name)); - main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook")); + var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name, StringComparison.OrdinalIgnoreCase)); + main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook", StringComparison.OrdinalIgnoreCase)); main ??= files.OrderBy(x => x.Container) .ThenBy(x => x.Path) .First(); From 5c40ad0530c10808317db742c39c2023bf9600f7 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 12 Nov 2020 09:44:10 -0700 Subject: [PATCH 0309/1930] Remove conditional access. --- Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index fd9f724b18..1b16a39ced 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -64,7 +64,7 @@ namespace Jellyfin.Api.ModelBinders { try { - parsedValues[i] = converter.ConvertFromString(values[i]?.Trim()); + parsedValues[i] = converter.ConvertFromString(values[i].Trim()); convertedCount++; } catch (FormatException e) From 83ac7d267428c74e4fe5161991feb2a6ca089578 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 08:02:45 -0700 Subject: [PATCH 0310/1930] Fix ci condition --- .ci/azure-pipelines-api-client.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml index 03102121ff..1c447fd977 100644 --- a/.ci/azure-pipelines-api-client.yml +++ b/.ci/azure-pipelines-api-client.yml @@ -9,6 +9,7 @@ jobs: - job: GenerateApiClients displayName: 'Generate Api Clients' + condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') dependsOn: Test pool: @@ -37,7 +38,6 @@ jobs: ## Generate npm api client - task: CmdLine@2 displayName: 'Build stable typescript axios client' - condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') inputs: script: "bash ./apiclient/templates/typescript/axios/generate.sh $(System.ArtifactsDirectory)" @@ -51,7 +51,6 @@ jobs: ## Publish npm packages - task: Npm@1 displayName: 'Publish stable typescript axios client' - condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') inputs: command: publish publishRegistry: useExternalRegistry From 38885ffd744e1b9d15fae80167ea67c94127acdd Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 08:31:02 -0700 Subject: [PATCH 0311/1930] Fix nullability errors in MediaBrowser.LocalMetadata --- MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs | 2 +- MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs | 2 +- MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs | 8 +++++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs index 914db53059..84c3ed8b0b 100644 --- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs @@ -486,7 +486,7 @@ namespace MediaBrowser.LocalMetadata.Images return false; } - private FileSystemMetadata GetImage(IEnumerable<FileSystemMetadata> files, string name) + private FileSystemMetadata? GetImage(IEnumerable<FileSystemMetadata> files, string name) { return files.FirstOrDefault(i => !i.IsDirectory && string.Equals(name, _fileSystem.GetFileNameWithoutExtension(i), StringComparison.OrdinalIgnoreCase) && i.Length > 0); } diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 4ac2498400..5d3ab30d39 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -683,7 +683,7 @@ namespace MediaBrowser.LocalMetadata.Parsers default: { string readerName = reader.Name; - if (_validProviderIds!.TryGetValue(readerName, out string providerIdValue)) + if (_validProviderIds!.TryGetValue(readerName, out string? providerIdValue)) { var id = reader.ReadElementContentAsString(); if (!string.IsNullOrWhiteSpace(id)) diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 7a4823e1b8..11ad69d914 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -127,7 +127,13 @@ namespace MediaBrowser.LocalMetadata.Savers private void SaveToFile(Stream stream, string path) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); + var directory = Path.GetDirectoryName(path); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + Directory.CreateDirectory(directory); // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); From 57b1e93411a19f1f6ea95131bdbeea4f9765df89 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 08:32:24 -0700 Subject: [PATCH 0312/1930] Fix nullability errors in Jellyfin.Server.Implementations --- .../Users/DefaultPasswordResetProvider.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index 6cb13cd23e..ced25524ee 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -54,12 +54,17 @@ namespace Jellyfin.Server.Implementations.Users var usersReset = new List<string>(); foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*")) { - SerializablePasswordReset spr; + SerializablePasswordReset? spr; await using (var str = File.OpenRead(resetFile)) { spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false); } + if (spr == null) + { + throw new NullReferenceException(nameof(spr)); + } + if (spr.ExpirationDate < DateTime.UtcNow) { File.Delete(resetFile); From a02514a114dbca0b966578759fb347f8e6174c2b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 08:34:34 -0700 Subject: [PATCH 0313/1930] Fix nullability errors in Jellyfin.Drawing.Skia --- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index 6a9dbdae42..ad066c524a 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -227,8 +227,13 @@ namespace Jellyfin.Drawing.Skia } var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path)); + var directory = Path.GetDirectoryName(tempPath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } - Directory.CreateDirectory(Path.GetDirectoryName(tempPath)); + Directory.CreateDirectory(directory); File.Copy(path, tempPath, true); return tempPath; @@ -493,7 +498,13 @@ namespace Jellyfin.Drawing.Skia // If all we're doing is resizing then we can stop now if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) { - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + var outputDirectory = Path.GetDirectoryName(outputPath); + if (outputDirectory == null) + { + throw new NullReferenceException(nameof(outputDirectory)); + } + + Directory.CreateDirectory(outputDirectory); using var outputStream = new SKFileWStream(outputPath); using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); resizedBitmap.Encode(outputStream, skiaOutputFormat, quality); @@ -540,7 +551,13 @@ namespace Jellyfin.Drawing.Skia DrawIndicator(canvas, width, height, options); } - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + var directory = Path.GetDirectoryName(outputPath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + Directory.CreateDirectory(directory); using (var outputStream = new SKFileWStream(outputPath)) { using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels())) From f3e74cb42192142fee81a4042984f64480b39826 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 08:35:32 -0700 Subject: [PATCH 0314/1930] Fix nullability errors in Emby.Notifications --- Emby.Notifications/NotificationEntryPoint.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Notifications/NotificationEntryPoint.cs b/Emby.Notifications/NotificationEntryPoint.cs index 7116d52b11..7433d3c8ae 100644 --- a/Emby.Notifications/NotificationEntryPoint.cs +++ b/Emby.Notifications/NotificationEntryPoint.cs @@ -83,7 +83,7 @@ namespace Emby.Notifications return Task.CompletedTask; } - private async void OnAppHostHasPendingRestartChanged(object sender, EventArgs e) + private async void OnAppHostHasPendingRestartChanged(object? sender, EventArgs e) { var type = NotificationType.ServerRestartRequired.ToString(); @@ -99,7 +99,7 @@ namespace Emby.Notifications await SendNotification(notification, null).ConfigureAwait(false); } - private async void OnActivityManagerEntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e) + private async void OnActivityManagerEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) { var entry = e.Argument; @@ -132,7 +132,7 @@ namespace Emby.Notifications return _config.GetConfiguration<NotificationOptions>("notifications"); } - private async void OnAppHostHasUpdateAvailableChanged(object sender, EventArgs e) + private async void OnAppHostHasUpdateAvailableChanged(object? sender, EventArgs e) { if (!_appHost.HasUpdateAvailable) { @@ -151,7 +151,7 @@ namespace Emby.Notifications await SendNotification(notification, null).ConfigureAwait(false); } - private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e) + private void OnLibraryManagerItemAdded(object? sender, ItemChangeEventArgs e) { if (!FilterItem(e.Item)) { @@ -197,7 +197,7 @@ namespace Emby.Notifications return item.SourceType == SourceType.Library; } - private async void LibraryUpdateTimerCallback(object state) + private async void LibraryUpdateTimerCallback(object? state) { List<BaseItem> items; From e82829c444a235d56aeafb60ad4424ee0d92b8b8 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:01:55 -0700 Subject: [PATCH 0315/1930] Fix nullability errors in MediaBrowser.MediaEncoding --- MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index 21b5d0c5be..bc940d0b8d 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -178,7 +178,7 @@ namespace MediaBrowser.MediaEncoding.Attachments process.Start(); - var ranToCompletion = await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); + var ranToCompletion = await ProcessExtensions.WaitForExitAsync(process, cancellationToken).ConfigureAwait(false); if (!ranToCompletion) { From e8675a6c24ebb86ce4a48f208f439f42267bf8e6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:03:44 -0700 Subject: [PATCH 0316/1930] Fix nullability errors in Jellyfin.Server --- Jellyfin.Server/Formatters/CssOutputFormatter.cs | 3 ++- Jellyfin.Server/Formatters/XmlOutputFormatter.cs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Formatters/CssOutputFormatter.cs b/Jellyfin.Server/Formatters/CssOutputFormatter.cs index b3771b7fe6..e8dd48e4e6 100644 --- a/Jellyfin.Server/Formatters/CssOutputFormatter.cs +++ b/Jellyfin.Server/Formatters/CssOutputFormatter.cs @@ -30,7 +30,8 @@ namespace Jellyfin.Server.Formatters /// <returns>Write stream task.</returns> public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - return context.HttpContext.Response.WriteAsync(context.Object?.ToString()); + var stringResponse = context.Object?.ToString(); + return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse); } } } diff --git a/Jellyfin.Server/Formatters/XmlOutputFormatter.cs b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs index 01d99d7c87..be0baea2d2 100644 --- a/Jellyfin.Server/Formatters/XmlOutputFormatter.cs +++ b/Jellyfin.Server/Formatters/XmlOutputFormatter.cs @@ -26,7 +26,8 @@ namespace Jellyfin.Server.Formatters /// <inheritdoc /> public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - return context.HttpContext.Response.WriteAsync(context.Object?.ToString()); + var stringResponse = context.Object?.ToString(); + return stringResponse == null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse); } } } From 01355e049855a21b69e7e258599c3fa35965375a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:04:31 -0700 Subject: [PATCH 0317/1930] Fix nullability errors in Jellyfin.Api (part 1) --- .../Controllers/DynamicHlsController.cs | 12 +++++++- .../Controllers/EnvironmentController.cs | 5 ++++ Jellyfin.Api/Controllers/GenresController.cs | 2 +- .../Controllers/HlsSegmentController.cs | 5 ++++ .../Controllers/ImageByNameController.cs | 2 +- Jellyfin.Api/Controllers/ImageController.cs | 3 +- .../Controllers/ItemLookupController.cs | 21 ++++++++++++-- Jellyfin.Api/Controllers/LibraryController.cs | 6 ++-- Jellyfin.Api/Controllers/LiveTvController.cs | 2 +- .../Controllers/MusicGenresController.cs | 4 +-- Jellyfin.Api/Controllers/PackageController.cs | 5 ++++ .../Controllers/RemoteImageController.cs | 28 +++++++++++++++---- Jellyfin.Api/Controllers/SearchController.cs | 2 +- .../Controllers/VideoHlsController.cs | 8 +++++- Jellyfin.Api/Helpers/AudioHelper.cs | 8 +++++- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 11 ++++++-- .../Helpers/FileStreamResponseHelpers.cs | 4 +-- Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs | 6 ++-- Jellyfin.Api/Helpers/HlsHelpers.cs | 4 +++ Jellyfin.Api/Helpers/ProgressiveFileCopier.cs | 5 ++++ Jellyfin.Api/Helpers/StreamingHelpers.cs | 4 +++ Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 26 +++++++++++------ .../Models/PlaybackDtos/TranscodingJobDto.cs | 4 +-- .../PlaybackDtos/TranscodingThrottler.cs | 2 +- .../ActivityLogWebSocketListener.cs | 2 +- .../ScheduledTasksWebSocketListener.cs | 6 ++-- .../SessionInfoWebSocketListener.cs | 14 +++++----- .../Subtitles/SubtitleEncoder.cs | 2 +- MediaBrowser.Model/Net/MimeTypes.cs | 6 ++-- 29 files changed, 155 insertions(+), 54 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index e07690e110..b0d5a7cd84 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1347,7 +1347,13 @@ namespace Jellyfin.Api.Controllers var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); + var directory = Path.GetDirectoryName(outputPath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) @@ -1566,6 +1572,10 @@ namespace Jellyfin.Api.Controllers private string GetSegmentPath(StreamState state, string playlist, int index) { var folder = Path.GetDirectoryName(playlist); + if (folder == null) + { + throw new NullReferenceException(nameof(folder)); + } var filename = Path.GetFileNameWithoutExtension(playlist); diff --git a/Jellyfin.Api/Controllers/EnvironmentController.cs b/Jellyfin.Api/Controllers/EnvironmentController.cs index ce88b0b995..8de217bbfa 100644 --- a/Jellyfin.Api/Controllers/EnvironmentController.cs +++ b/Jellyfin.Api/Controllers/EnvironmentController.cs @@ -103,6 +103,11 @@ namespace Jellyfin.Api.Controllers if (validatePathDto.ValidateWritable) { + if (validatePathDto.Path == null) + { + throw new NullReferenceException(nameof(validatePathDto.Path)); + } + var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString()); try { diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index f6e0772ec1..9c009d7847 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -177,7 +177,7 @@ namespace Jellyfin.Api.Controllers return _dtoService.GetBaseItemDto(item, dtoOptions); } - private T GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) + private T? GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) where T : BaseItem, new() { var result = libraryManager.GetItemList(new InternalItemsQuery diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 054e586ce3..2cee0e9ef2 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -136,6 +136,11 @@ namespace Jellyfin.Api.Controllers string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1); + if (playlistPath == null) + { + throw new NullReferenceException(nameof(playlistPath)); + } + return GetFileResult(file, playlistPath); } diff --git a/Jellyfin.Api/Controllers/ImageByNameController.cs b/Jellyfin.Api/Controllers/ImageByNameController.cs index 980c3273dd..198dbc51fc 100644 --- a/Jellyfin.Api/Controllers/ImageByNameController.cs +++ b/Jellyfin.Api/Controllers/ImageByNameController.cs @@ -161,7 +161,7 @@ namespace Jellyfin.Api.Controllers /// <param name="theme">Theme to search.</param> /// <param name="name">File name to search for.</param> /// <returns>A <see cref="FileStreamResult"/> containing the image contents on success, or a <see cref="NotFoundResult"/> if the image could not be found.</returns> - private ActionResult GetImageFile(string basePath, string? theme, string? name) + private ActionResult GetImageFile(string basePath, string theme, string? name) { var themeFolder = Path.Combine(basePath, theme); if (Directory.Exists(themeFolder)) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 4a67c1aede..76e53b9a53 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Mime; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; @@ -1268,7 +1269,7 @@ namespace Jellyfin.Api.Controllers Response.Headers.Add(key, value); } - Response.ContentType = imageContentType; + Response.ContentType = imageContentType ?? MediaTypeNames.Text.Plain; Response.Headers.Add(HeaderNames.Age, Convert.ToInt64((DateTime.UtcNow - dateImageModified).TotalSeconds).ToString(CultureInfo.InvariantCulture)); Response.Headers.Add(HeaderNames.Vary, HeaderNames.Accept); diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index ab73aa4286..b6cb797167 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -334,10 +334,21 @@ namespace Jellyfin.Api.Controllers private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath) { using var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false); + if (result.Content.Headers.ContentType?.MediaType == null) + { + throw new NullReferenceException(nameof(result.Content.Headers.ContentType)); + } + var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; var fullCachePath = GetFullCachePath(urlHash + "." + ext); - Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); + var directory = Path.GetDirectoryName(fullCachePath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + Directory.CreateDirectory(directory); using (var stream = result.Content) { await using var fileStream = new FileStream( @@ -351,7 +362,13 @@ namespace Jellyfin.Api.Controllers await stream.CopyToAsync(fileStream).ConfigureAwait(false); } - Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); + if (pointerCacheDirectory == null) + { + throw new NullReferenceException(nameof(pointerCacheDirectory)); + } + + Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false); } diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 8a872ae133..60bbc5022a 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -455,7 +455,7 @@ namespace Jellyfin.Api.Controllers : null; var dtoOptions = new DtoOptions().AddClientFields(Request); - BaseItem parent = item.GetParent(); + BaseItem? parent = item.GetParent(); while (parent != null) { @@ -466,7 +466,7 @@ namespace Jellyfin.Api.Controllers baseItemDtos.Add(_dtoService.GetBaseItemDto(parent, dtoOptions, user)); - parent = parent.GetParent(); + parent = parent?.GetParent(); } return baseItemDtos; @@ -854,7 +854,7 @@ namespace Jellyfin.Api.Controllers return _libraryManager.GetItemsResult(query).TotalRecordCount; } - private BaseItem TranslateParentItem(BaseItem item, User user) + private BaseItem? TranslateParentItem(BaseItem item, User user) { return item.GetParent() is AggregateFolder ? _libraryManager.GetUserRootFolder().GetChildren(user, true) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 31253cbbcd..384a487055 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1078,7 +1078,7 @@ namespace Jellyfin.Api.Controllers var client = _httpClientFactory.CreateClient(NamedClient.Default); // https://json.schedulesdirect.org/20141201/available/countries // Can't dispose the response as it's required up the call chain. - var response = await client.GetAsync("https://json.schedulesdirect.org/20141201/available/countries") + var response = await client.GetAsync(new Uri("https://json.schedulesdirect.org/20141201/available/countries")) .ConfigureAwait(false); return File(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), MediaTypeNames.Application.Json); diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index e434f190ac..989c383fdc 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -140,7 +140,7 @@ namespace Jellyfin.Api.Controllers { var dtoOptions = new DtoOptions().AddClientFields(Request); - MusicGenre item; + MusicGenre? item; if (genreName.IndexOf(BaseItem.SlugChar, StringComparison.OrdinalIgnoreCase) != -1) { @@ -161,7 +161,7 @@ namespace Jellyfin.Api.Controllers return _dtoService.GetBaseItemDto(item, dtoOptions); } - private T GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) + private T? GetItemFromSlugName<T>(ILibraryManager libraryManager, string name, DtoOptions dtoOptions) where T : BaseItem, new() { var result = libraryManager.GetItemList(new InternalItemsQuery diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 1d9de14d2d..a104af4e63 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -54,6 +54,11 @@ namespace Jellyfin.Api.Controllers string.IsNullOrEmpty(assemblyGuid) ? default : Guid.Parse(assemblyGuid)) .FirstOrDefault(); + if (result == null) + { + return NotFound(); + } + return result; } diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index 5f095443b9..ad76b39847 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -157,9 +157,9 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] - public async Task<ActionResult> GetRemoteImage([FromQuery, Required] string imageUrl) + public async Task<ActionResult> GetRemoteImage([FromQuery, Required] Uri imageUrl) { - var urlHash = imageUrl.GetMD5(); + var urlHash = imageUrl.ToString().GetMD5(); var pointerCachePath = GetFullCachePath(urlHash.ToString()); string? contentPath = null; @@ -245,17 +245,35 @@ namespace Jellyfin.Api.Controllers /// <param name="urlHash">The URL hash.</param> /// <param name="pointerCachePath">The pointer cache path.</param> /// <returns>Task.</returns> - private async Task DownloadImage(string url, Guid urlHash, string pointerCachePath) + private async Task DownloadImage(Uri url, Guid urlHash, string pointerCachePath) { var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); using var response = await httpClient.GetAsync(url).ConfigureAwait(false); + if (response.Content.Headers.ContentType?.MediaType == null) + { + throw new NullReferenceException(nameof(response.Content.Headers.ContentType)); + } + var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); var fullCachePath = GetFullCachePath(urlHash + "." + ext); - Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); + var fullCacheDirectory = Path.GetDirectoryName(fullCachePath); + if (fullCacheDirectory == null) + { + throw new NullReferenceException(nameof(fullCacheDirectory)); + } + + Directory.CreateDirectory(fullCacheDirectory); await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); - Directory.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); + + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); + if (pointerCacheDirectory == null) + { + throw new NullReferenceException(nameof(pointerCacheDirectory)); + } + + Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None) .ConfigureAwait(false); } diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs index 62c870cb1f..e75f0d06bb 100644 --- a/Jellyfin.Api/Controllers/SearchController.cs +++ b/Jellyfin.Api/Controllers/SearchController.cs @@ -260,7 +260,7 @@ namespace Jellyfin.Api.Controllers } } - private T GetParentWithImage<T>(BaseItem item, ImageType type) + private T? GetParentWithImage<T>(BaseItem item, ImageType type) where T : BaseItem { return item.GetParents().OfType<T>().FirstOrDefault(i => i.HasImage(type)); diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index d7bcf79c1f..517239966f 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -361,7 +361,13 @@ namespace Jellyfin.Api.Controllers var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; - var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; + var directory = Path.GetDirectoryName(outputPath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; var segmentFormat = format.TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs index a3f2d88ce5..c6d577b193 100644 --- a/Jellyfin.Api/Helpers/AudioHelper.cs +++ b/Jellyfin.Api/Helpers/AudioHelper.cs @@ -1,4 +1,5 @@ -using System.Net.Http; +using System; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; @@ -98,6 +99,11 @@ namespace Jellyfin.Api.Helpers TranscodingJobType transcodingJobType, StreamingRequestDto streamingRequest) { + if (_httpContextAccessor.HttpContext == null) + { + throw new NullReferenceException(nameof(_httpContextAccessor.HttpContext)); + } + bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head; var cancellationTokenSource = new CancellationTokenSource(); diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index ea012f8376..20bca731fd 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -113,7 +113,7 @@ namespace Jellyfin.Api.Helpers StreamingRequestDto streamingRequest, bool enableAdaptiveBitrateStreaming) { - var isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == WebRequestMethods.Http.Head; + var isHeadRequest = _httpContextAccessor.HttpContext?.Request.Method == WebRequestMethods.Http.Head; var cancellationTokenSource = new CancellationTokenSource(); return await GetMasterPlaylistInternal( streamingRequest, @@ -130,6 +130,11 @@ namespace Jellyfin.Api.Helpers TranscodingJobType transcodingJobType, CancellationTokenSource cancellationTokenSource) { + if (_httpContextAccessor.HttpContext == null) + { + throw new NullReferenceException(nameof(_httpContextAccessor.HttpContext)); + } + using var state = await StreamingHelpers.GetStreamingState( streamingRequest, _httpContextAccessor.HttpContext.Request, @@ -487,14 +492,14 @@ namespace Jellyfin.Api.Helpers if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase)) { - string profile = state.GetRequestedProfiles("h264").FirstOrDefault(); + string? profile = state.GetRequestedProfiles("h264").FirstOrDefault(); return HlsCodecStringHelpers.GetH264String(profile, level); } if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)) { - string profile = state.GetRequestedProfiles("h265").FirstOrDefault(); + string? profile = state.GetRequestedProfiles("h265").FirstOrDefault(); return HlsCodecStringHelpers.GetH265String(profile, level); } diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index 366301d3ee..20c94cddad 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -37,8 +37,8 @@ namespace Jellyfin.Api.Helpers } // Can't dispose the response as it's required up the call chain. - var response = await httpClient.GetAsync(state.MediaPath).ConfigureAwait(false); - var contentType = response.Content.Headers.ContentType.ToString(); + var response = await httpClient.GetAsync(new Uri(state.MediaPath)).ConfigureAwait(false); + var contentType = response.Content.Headers.ContentType?.ToString(); httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none"; diff --git a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs index 95f1906ef0..1bd3d67ff2 100644 --- a/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsCodecStringHelpers.cs @@ -23,7 +23,7 @@ namespace Jellyfin.Api.Helpers /// </summary> /// <param name="profile">AAC profile.</param> /// <returns>AAC codec string.</returns> - public static string GetAACString(string profile) + public static string GetAACString(string? profile) { StringBuilder result = new StringBuilder("mp4a", 9); @@ -46,7 +46,7 @@ namespace Jellyfin.Api.Helpers /// <param name="profile">H.264 profile.</param> /// <param name="level">H.264 level.</param> /// <returns>H.264 string.</returns> - public static string GetH264String(string profile, int level) + public static string GetH264String(string? profile, int level) { StringBuilder result = new StringBuilder("avc1", 11); @@ -80,7 +80,7 @@ namespace Jellyfin.Api.Helpers /// <param name="profile">H.265 profile.</param> /// <param name="level">H.265 level.</param> /// <returns>H.265 string.</returns> - public static string GetH265String(string profile, int level) + public static string GetH265String(string? profile, int level) { // The h265 syntax is a bit of a mystery at the time this comment was written. // This is what I've found through various sources: diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 2424966973..16fbac7ae2 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -45,6 +45,10 @@ namespace Jellyfin.Api.Helpers while (!reader.EndOfStream) { var line = await reader.ReadLineAsync().ConfigureAwait(false); + if (line == null) + { + throw new NullReferenceException(nameof(line)); + } if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) { diff --git a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs index e00ed33042..65c03c710b 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs @@ -90,6 +90,11 @@ namespace Jellyfin.Api.Helpers allowAsyncFileRead = true; } + if (_path == null) + { + throw new NullReferenceException(nameof(_path)); + } + await using var inputStream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions); var eofCount = 0; diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index f4ec29bdef..1d102071c2 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -83,6 +83,10 @@ namespace Jellyfin.Api.Helpers } streamingRequest.StreamOptions = ParseStreamOptions(httpRequest.Query); + if (httpRequest.Path.Value == null) + { + throw new NullReferenceException(nameof(httpRequest.Path)); + } var url = httpRequest.Path.Value.Split('.').Last(); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 0db1fabffe..b72e33af38 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -102,7 +102,7 @@ namespace Jellyfin.Api.Helpers /// </summary> /// <param name="playSessionId">Playback session id.</param> /// <returns>The transcoding job.</returns> - public TranscodingJobDto GetTranscodingJob(string playSessionId) + public TranscodingJobDto? GetTranscodingJob(string playSessionId) { lock (_activeTranscodingJobs) { @@ -116,7 +116,7 @@ namespace Jellyfin.Api.Helpers /// <param name="path">Path to the transcoding file.</param> /// <param name="type">The <see cref="TranscodingJobType"/>.</param> /// <returns>The transcoding job.</returns> - public TranscodingJobDto GetTranscodingJob(string path, TranscodingJobType type) + public TranscodingJobDto? GetTranscodingJob(string path, TranscodingJobType type) { lock (_activeTranscodingJobs) { @@ -193,9 +193,13 @@ namespace Jellyfin.Api.Helpers /// Called when [transcode kill timer stopped]. /// </summary> /// <param name="state">The state.</param> - private async void OnTranscodeKillTimerStopped(object state) + private async void OnTranscodeKillTimerStopped(object? state) { - var job = (TranscodingJobDto)state; + var job = (TranscodingJobDto?)state; + if (job == null) + { + throw new NullReferenceException(nameof(job)); + } if (!job.HasExited && job.Type != TranscodingJobType.Progressive) { @@ -489,7 +493,13 @@ namespace Jellyfin.Api.Helpers CancellationTokenSource cancellationTokenSource, string? workingDirectory = null) { - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + var directory = Path.GetDirectoryName(outputPath); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + + Directory.CreateDirectory(directory); await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false); @@ -523,7 +533,7 @@ namespace Jellyfin.Api.Helpers RedirectStandardInput = true, FileName = _mediaEncoder.EncoderPath, Arguments = commandLineArguments, - WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? null : workingDirectory, + WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? string.Empty : workingDirectory, ErrorDialog = false }, EnableRaisingEvents = true @@ -827,7 +837,7 @@ namespace Jellyfin.Api.Helpers { lock (_transcodingLocks) { - if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim result)) + if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result)) { result = new SemaphoreSlim(1, 1); _transcodingLocks[outputPath] = result; @@ -837,7 +847,7 @@ namespace Jellyfin.Api.Helpers } } - private void OnPlaybackProgress(object sender, PlaybackProgressEventArgs e) + private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e) { if (!string.IsNullOrWhiteSpace(e.PlaySessionId)) { diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs index b9507a4e50..9edc19bb6d 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos /// Start kill timer. /// </summary> /// <param name="callback">Callback action.</param> - public void StartKillTimer(Action<object> callback) + public void StartKillTimer(Action<object?> callback) { StartKillTimer(callback, PingTimeout); } @@ -206,7 +206,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos /// </summary> /// <param name="callback">Callback action.</param> /// <param name="intervalMs">Callback interval.</param> - public void StartKillTimer(Action<object> callback, int intervalMs) + public void StartKillTimer(Action<object?> callback, int intervalMs) { if (HasExited) { diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs index b5e42ea299..872a468245 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs @@ -101,7 +101,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos return _config.GetConfiguration<EncodingOptions>("encoding"); } - private async void TimerCallback(object state) + private async void TimerCallback(object? state) { if (_job.HasExited) { diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index 77d55828d1..ce54651166 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -56,7 +56,7 @@ namespace Jellyfin.Api.WebSocketListeners base.Dispose(dispose); } - private void OnEntryCreated(object sender, GenericEventArgs<ActivityLogEntry> e) + private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) { SendData(true); } diff --git a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs index 80314b9236..94df23e569 100644 --- a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs @@ -64,19 +64,19 @@ namespace Jellyfin.Api.WebSocketListeners base.Dispose(dispose); } - private void OnTaskCompleted(object sender, TaskCompletionEventArgs e) + private void OnTaskCompleted(object? sender, TaskCompletionEventArgs e) { SendData(true); e.Task.TaskProgress -= OnTaskProgress; } - private void OnTaskExecuting(object sender, GenericEventArgs<IScheduledTaskWorker> e) + private void OnTaskExecuting(object? sender, GenericEventArgs<IScheduledTaskWorker> e) { SendData(true); e.Argument.TaskProgress += OnTaskProgress; } - private void OnTaskProgress(object sender, GenericEventArgs<double> e) + private void OnTaskProgress(object? sender, GenericEventArgs<double> e) { SendData(false); } diff --git a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs index 1cf43a0053..d996ac69f9 100644 --- a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs @@ -66,37 +66,37 @@ namespace Jellyfin.Api.WebSocketListeners base.Dispose(dispose); } - private async void OnSessionManagerSessionActivity(object sender, SessionEventArgs e) + private async void OnSessionManagerSessionActivity(object? sender, SessionEventArgs e) { await SendData(false).ConfigureAwait(false); } - private async void OnSessionManagerCapabilitiesChanged(object sender, SessionEventArgs e) + private async void OnSessionManagerCapabilitiesChanged(object? sender, SessionEventArgs e) { await SendData(true).ConfigureAwait(false); } - private async void OnSessionManagerPlaybackProgress(object sender, PlaybackProgressEventArgs e) + private async void OnSessionManagerPlaybackProgress(object? sender, PlaybackProgressEventArgs e) { await SendData(!e.IsAutomated).ConfigureAwait(false); } - private async void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e) + private async void OnSessionManagerPlaybackStopped(object? sender, PlaybackStopEventArgs e) { await SendData(true).ConfigureAwait(false); } - private async void OnSessionManagerPlaybackStart(object sender, PlaybackProgressEventArgs e) + private async void OnSessionManagerPlaybackStart(object? sender, PlaybackProgressEventArgs e) { await SendData(true).ConfigureAwait(false); } - private async void OnSessionManagerSessionEnded(object sender, SessionEventArgs e) + private async void OnSessionManagerSessionEnded(object? sender, SessionEventArgs e) { await SendData(true).ConfigureAwait(false); } - private async void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) + private async void OnSessionManagerSessionStarted(object? sender, SessionEventArgs e) { await SendData(true).ConfigureAwait(false); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 0a9958b9eb..8b3c6b2e63 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -758,7 +758,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles case MediaProtocol.Http: { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetAsync(path, cancellationToken) + .GetAsync(new Uri(path), cancellationToken) .ConfigureAwait(false); return await response.Content.ReadAsStreamAsync().ConfigureAwait(false); } diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs index afe7351d32..55c0e6c9a6 100644 --- a/MediaBrowser.Model/Net/MimeTypes.cs +++ b/MediaBrowser.Model/Net/MimeTypes.cs @@ -210,9 +210,9 @@ namespace MediaBrowser.Model.Net return enableStreamDefault ? "application/octet-stream" : null; } - public static string? ToExtension(string mimeType) + public static string? ToExtension(string? mimeType) { - if (mimeType.Length == 0) + if (string.IsNullOrEmpty(mimeType)) { throw new ArgumentException("String can't be empty.", nameof(mimeType)); } @@ -220,7 +220,7 @@ namespace MediaBrowser.Model.Net // handle text/html; charset=UTF-8 mimeType = mimeType.Split(';')[0]; - if (_extensionLookup.TryGetValue(mimeType, out string result)) + if (_extensionLookup.TryGetValue(mimeType, out string? result)) { return result; } From 445eec7f5f8710179a425b3b6afa3d4d54ce03da Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:21:22 -0700 Subject: [PATCH 0318/1930] Fix nullability errors in Jellyfin.Api.Tests --- .../Auth/CustomAuthenticationHandlerTests.cs | 8 +++---- .../BrandingServiceTests.cs | 4 ++-- .../CommaDelimitedArrayModelBinderTests.cs | 24 +++++++++---------- tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs | 2 +- tests/Jellyfin.Api.Tests/TestHelpers.cs | 2 +- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index a46d94457f..90c4916668 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -81,7 +81,7 @@ namespace Jellyfin.Api.Tests.Auth var authenticateResult = await _sut.AuthenticateAsync(); Assert.False(authenticateResult.Succeeded); - Assert.Equal(errorMessage, authenticateResult.Failure.Message); + Assert.Equal(errorMessage, authenticateResult.Failure?.Message); } [Fact] @@ -100,7 +100,7 @@ namespace Jellyfin.Api.Tests.Auth var authorizationInfo = SetupUser(); var authenticateResult = await _sut.AuthenticateAsync(); - Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username)); + Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Name, authorizationInfo.User.Username)); } [Theory] @@ -112,7 +112,7 @@ namespace Jellyfin.Api.Tests.Auth var authenticateResult = await _sut.AuthenticateAsync(); var expectedRole = authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User; - Assert.True(authenticateResult.Principal.HasClaim(ClaimTypes.Role, expectedRole)); + Assert.True(authenticateResult.Principal?.HasClaim(ClaimTypes.Role, expectedRole)); } [Fact] @@ -121,7 +121,7 @@ namespace Jellyfin.Api.Tests.Auth SetupUser(); var authenticatedResult = await _sut.AuthenticateAsync(); - Assert.Equal(_scheme.Name, authenticatedResult.Ticket.AuthenticationScheme); + Assert.Equal(_scheme.Name, authenticatedResult.Ticket?.AuthenticationScheme); } private AuthorizationInfo SetupUser(bool isAdmin = false) diff --git a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs b/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs index 6fc287420b..1cbe94c5b9 100644 --- a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs +++ b/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs @@ -25,7 +25,7 @@ namespace Jellyfin.Api.Tests // Assert response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString()); + Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString()); var responseBody = await response.Content.ReadAsStreamAsync(); _ = await JsonSerializer.DeserializeAsync<BrandingOptions>(responseBody); } @@ -43,7 +43,7 @@ namespace Jellyfin.Api.Tests // Assert response.EnsureSuccessStatusCode(); - Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType.ToString()); + Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType?.ToString()); } } } diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs index 89c7d62f79..6f3bd91329 100644 --- a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs +++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs @@ -17,7 +17,7 @@ namespace Jellyfin.Api.Tests.ModelBinders public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedStringArrayQuery() { var queryParamName = "test"; - var queryParamValues = new[] { "lol", "xd" }; + IReadOnlyList<string> queryParamValues = new[] { "lol", "xd" }; var queryParamString = "lol,xd"; var queryParamType = typeof(string[]); @@ -35,14 +35,14 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((string[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<string>?)bindingContextMock.Object?.Result.Model, queryParamValues); } [Fact] public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedIntArrayQuery() { var queryParamName = "test"; - var queryParamValues = new[] { 42, 0 }; + IReadOnlyList<int> queryParamValues = new[] { 42, 0 }; var queryParamString = "42,0"; var queryParamType = typeof(int[]); @@ -60,14 +60,14 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((int[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<int>?)bindingContextMock.Object.Result.Model, queryParamValues); } [Fact] public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQuery() { var queryParamName = "test"; - var queryParamValues = new[] { TestType.How, TestType.Much }; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; var queryParamString = "How,Much"; var queryParamType = typeof(TestType[]); @@ -85,14 +85,14 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((TestType[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); } [Fact] public async Task BindModelAsync_CorrectlyBindsValidCommaDelimitedEnumArrayQueryWithDoubleCommas() { var queryParamName = "test"; - var queryParamValues = new[] { TestType.How, TestType.Much }; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; var queryParamString = "How,,Much"; var queryParamType = typeof(TestType[]); @@ -110,14 +110,14 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((TestType[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); } [Fact] public async Task BindModelAsync_CorrectlyBindsValidEnumArrayQuery() { var queryParamName = "test"; - var queryParamValues = new[] { TestType.How, TestType.Much }; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; var queryParamString1 = "How"; var queryParamString2 = "Much"; var queryParamType = typeof(TestType[]); @@ -140,14 +140,14 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((TestType[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); } [Fact] public async Task BindModelAsync_CorrectlyBindsEmptyEnumArrayQuery() { var queryParamName = "test"; - var queryParamValues = Array.Empty<TestType>(); + IReadOnlyList<TestType> queryParamValues = Array.Empty<TestType>(); var queryParamType = typeof(TestType[]); var modelBinder = new CommaDelimitedArrayModelBinder(); @@ -168,7 +168,7 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Equal((TestType[])bindingContextMock.Object.Result.Model, queryParamValues); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); } [Fact] diff --git a/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs b/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs index 3a85b55141..03ab56d1f4 100644 --- a/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs +++ b/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs @@ -30,7 +30,7 @@ namespace Jellyfin.Api.Tests // Assert response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString()); + Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString()); // Write out for publishing var responseBody = await response.Content.ReadAsStringAsync(); diff --git a/tests/Jellyfin.Api.Tests/TestHelpers.cs b/tests/Jellyfin.Api.Tests/TestHelpers.cs index c4ce398859..f27cdf7b63 100644 --- a/tests/Jellyfin.Api.Tests/TestHelpers.cs +++ b/tests/Jellyfin.Api.Tests/TestHelpers.cs @@ -60,7 +60,7 @@ namespace Jellyfin.Api.Tests .Returns(user); httpContextAccessorMock - .Setup(h => h.HttpContext.Connection.RemoteIpAddress) + .Setup(h => h.HttpContext!.Connection.RemoteIpAddress) .Returns(new IPAddress(0)); return new ClaimsPrincipal(identity); From 6353cb507d591d5060c00d925f4e1ac6fc7a6916 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:21:28 -0700 Subject: [PATCH 0319/1930] Fix nullability errors in Jellyfin.Server --- Jellyfin.Server/Filters/FileResponseFilter.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Filters/FileResponseFilter.cs b/Jellyfin.Server/Filters/FileResponseFilter.cs index 8ea35c2818..7ad9466c17 100644 --- a/Jellyfin.Server/Filters/FileResponseFilter.cs +++ b/Jellyfin.Server/Filters/FileResponseFilter.cs @@ -26,22 +26,22 @@ namespace Jellyfin.Server.Filters if (attribute is ProducesFileAttribute producesFileAttribute) { // Get operation response values. - var (_, value) = operation.Responses + var response = operation.Responses .FirstOrDefault(o => o.Key.Equals(SuccessCode, StringComparison.Ordinal)); // Operation doesn't have a response. - if (value == null) + if (response.Value == null) { continue; } // Clear existing responses. - value.Content.Clear(); + response.Value.Content.Clear(); // Add all content-types as file. foreach (var contentType in producesFileAttribute.GetContentTypes()) { - value.Content.Add(contentType, _openApiMediaType); + response.Value.Content.Add(contentType, _openApiMediaType); } break; From d5e2369dd6ac308e518a5a36a744a1a2dac45f70 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:36:17 -0700 Subject: [PATCH 0320/1930] Fix nullability errors in MediaBrowser.Model --- MediaBrowser.Model/Entities/ProviderIdsExtensions.cs | 2 +- MediaBrowser.Model/Net/MimeTypes.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 9c11fe0ad2..1782b42e21 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Model.Entities return null; } - instance.ProviderIds.TryGetValue(name, out string id); + instance.ProviderIds.TryGetValue(name, out string? id); return id; } diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs index 55c0e6c9a6..902db1e9e5 100644 --- a/MediaBrowser.Model/Net/MimeTypes.cs +++ b/MediaBrowser.Model/Net/MimeTypes.cs @@ -177,7 +177,7 @@ namespace MediaBrowser.Model.Net var ext = Path.GetExtension(path); - if (_mimeTypeLookup.TryGetValue(ext, out string result)) + if (_mimeTypeLookup.TryGetValue(ext, out string? result)) { return result; } From 7bf320922c095b67293c05b8d2e0ed79f1db78d7 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:41:18 -0700 Subject: [PATCH 0321/1930] Fix nullability errors in Emby.Server.Implementations --- .../AppBase/ConfigurationHelper.cs | 10 ++++++++-- .../Cryptography/CryptographyProvider.cs | 5 +++++ .../Session/WebSocketController.cs | 7 ++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 4c9ab33a7c..e19ce5edf8 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -35,7 +35,8 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception) { - configuration = Activator.CreateInstance(type); + var instanceConfiguration = Activator.CreateInstance(type); + configuration = instanceConfiguration ?? throw new NullReferenceException(nameof(instanceConfiguration)); } using var stream = new MemoryStream(buffer?.Length ?? 0); @@ -48,8 +49,13 @@ namespace Emby.Server.Implementations.AppBase // If the file didn't exist before, or if something has changed, re-save if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer)) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); + var directory = Path.GetDirectoryName(path); + if (directory == null) + { + throw new NullReferenceException(nameof(directory)); + } + Directory.CreateDirectory(directory); // Save it after load in case we got new items using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index fd302d1365..a48b6f3563 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -81,6 +81,11 @@ namespace Emby.Server.Implementations.Cryptography } using var h = HashAlgorithm.Create(hashMethod); + if (h == null) + { + throw new NullReferenceException(nameof(h)); + } + if (salt.Length == 0) { return h.ComputeHash(bytes); diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index b986ffa1cd..7559ccb782 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -55,8 +55,13 @@ namespace Emby.Server.Implementations.Session connection.Closed += OnConnectionClosed; } - private void OnConnectionClosed(object sender, EventArgs e) + private void OnConnectionClosed(object? sender, EventArgs e) { + if (sender == null) + { + throw new NullReferenceException(nameof(sender)); + } + var connection = (IWebSocketConnection)sender; _logger.LogDebug("Removing websocket from session {Session}", _session.Id); _sockets.Remove(connection); From 3c8800604e9e31688154dffcd161cc3bdbfc456a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 09:48:26 -0700 Subject: [PATCH 0322/1930] Update test sdk --- .ci/azure-pipelines-abi.yml | 2 +- .ci/azure-pipelines-test.yml | 4 ++-- Jellyfin.Server/Properties/launchSettings.json | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml index b558d2a6f0..14df7e7c8d 100644 --- a/.ci/azure-pipelines-abi.yml +++ b/.ci/azure-pipelines-abi.yml @@ -7,7 +7,7 @@ parameters: default: "ubuntu-latest" - name: DotNetSdkVersion type: string - default: 3.1.100 + default: 5.0.100 jobs: - job: CompatibilityCheck diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index 6a36698b56..4ceda978a6 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -10,7 +10,7 @@ parameters: default: "tests/**/*Tests.csproj" - name: DotNetSdkVersion type: string - default: 3.1.100 + default: 5.0.100 jobs: - job: Test @@ -94,5 +94,5 @@ jobs: displayName: 'Publish OpenAPI Artifact' condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) inputs: - targetPath: "tests/Jellyfin.Api.Tests/bin/Release/netcoreapp3.1/openapi.json" + targetPath: "tests/Jellyfin.Api.Tests/bin/Release/net5.0/openapi.json" artifactName: 'OpenAPI Spec' diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json index 20d432afc4..61a1723bd2 100644 --- a/Jellyfin.Server/Properties/launchSettings.json +++ b/Jellyfin.Server/Properties/launchSettings.json @@ -6,7 +6,8 @@ "applicationUrl": "http://localhost:8096", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "commandLineArgs": "--webdir C:\\Users\\Cody\\Code\\Jellyfin\\jellyfin-web\\dist" }, "Jellyfin.Server (nowebclient)": { "commandName": "Project", From 1acbceaade9339b48abfc7a276bb4eba68ec9d02 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 10:24:40 -0700 Subject: [PATCH 0323/1930] Disable warning on AD0001 --- Jellyfin.Api/Jellyfin.Api.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 2836f7b0ae..da6e5fa2d4 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -10,6 +10,8 @@ <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> + <!-- https://github.com/microsoft/ApplicationInsights-dotnet/issues/2047 --> + <NoWarn>AD0001</NoWarn> </PropertyGroup> <ItemGroup> From ec5781504ea445f06554afa7853028bca9b75ec0 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 10:29:26 -0700 Subject: [PATCH 0324/1930] Disable warning on AD0001 --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index bcddea281c..f3052f5445 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -53,6 +53,8 @@ <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors Condition=" '$(Configuration)' == 'Release'">true</TreatWarningsAsErrors> + <!-- https://github.com/microsoft/ApplicationInsights-dotnet/issues/2047 --> + <NoWarn>AD0001</NoWarn> </PropertyGroup> <!-- Code Analyzers--> From e8b98265b0d0e66fe7ef6b8a0acb28725b86ebe6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 10:40:09 -0700 Subject: [PATCH 0325/1930] Upgrade Jellyfin.Model.Tests to net5.0 --- tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index e933851366..64d51e0638 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> From be312f992d92433e3e7619e264889d1a0afadf26 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 10:57:34 -0700 Subject: [PATCH 0326/1930] Update to net5 --- Jellyfin.Server/Properties/launchSettings.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json index 61a1723bd2..20d432afc4 100644 --- a/Jellyfin.Server/Properties/launchSettings.json +++ b/Jellyfin.Server/Properties/launchSettings.json @@ -6,8 +6,7 @@ "applicationUrl": "http://localhost:8096", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - }, - "commandLineArgs": "--webdir C:\\Users\\Cody\\Code\\Jellyfin\\jellyfin-web\\dist" + } }, "Jellyfin.Server (nowebclient)": { "commandName": "Project", From 5f52a58e785fa4ae06fa07a93b81c1e7547ac9f3 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 11:14:44 -0700 Subject: [PATCH 0327/1930] Convert NullReferenceException to ResourceNotFoundException --- Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | 5 +++-- .../Cryptography/CryptographyProvider.cs | 3 ++- Emby.Server.Implementations/Session/WebSocketController.cs | 3 ++- Jellyfin.Api/Controllers/DynamicHlsController.cs | 5 +++-- Jellyfin.Api/Controllers/EnvironmentController.cs | 3 ++- Jellyfin.Api/Controllers/HlsSegmentController.cs | 3 ++- Jellyfin.Api/Controllers/ItemLookupController.cs | 6 +++--- Jellyfin.Api/Controllers/RemoteImageController.cs | 6 +++--- Jellyfin.Api/Controllers/VideoHlsController.cs | 3 ++- Jellyfin.Api/Helpers/AudioHelper.cs | 3 ++- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/HlsHelpers.cs | 3 ++- Jellyfin.Api/Helpers/ProgressiveFileCopier.cs | 3 ++- Jellyfin.Api/Helpers/StreamingHelpers.cs | 2 +- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 5 +++-- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 7 ++++--- .../Users/DefaultPasswordResetProvider.cs | 2 +- MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs | 3 ++- 18 files changed, 40 insertions(+), 27 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index e19ce5edf8..8cca5cc779 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -3,6 +3,7 @@ using System; using System.IO; using System.Linq; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase @@ -36,7 +37,7 @@ namespace Emby.Server.Implementations.AppBase catch (Exception) { var instanceConfiguration = Activator.CreateInstance(type); - configuration = instanceConfiguration ?? throw new NullReferenceException(nameof(instanceConfiguration)); + configuration = instanceConfiguration ?? throw new ResourceNotFoundException(nameof(instanceConfiguration)); } using var stream = new MemoryStream(buffer?.Length ?? 0); @@ -52,7 +53,7 @@ namespace Emby.Server.Implementations.AppBase var directory = Path.GetDirectoryName(path); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index a48b6f3563..8d7f73b3cf 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Security.Cryptography; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Cryptography; using static MediaBrowser.Common.Cryptography.Constants; @@ -83,7 +84,7 @@ namespace Emby.Server.Implementations.Cryptography using var h = HashAlgorithm.Create(hashMethod); if (h == null) { - throw new NullReferenceException(nameof(h)); + throw new ResourceNotFoundException(nameof(h)); } if (salt.Length == 0) diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index 7559ccb782..78f83e337f 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Net; @@ -59,7 +60,7 @@ namespace Emby.Server.Implementations.Session { if (sender == null) { - throw new NullReferenceException(nameof(sender)); + throw new ResourceNotFoundException(nameof(sender)); } var connection = (IWebSocketConnection)sender; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index b0d5a7cd84..64bea999fa 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -14,6 +14,7 @@ using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; @@ -1350,7 +1351,7 @@ namespace Jellyfin.Api.Controllers var directory = Path.GetDirectoryName(outputPath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); @@ -1574,7 +1575,7 @@ namespace Jellyfin.Api.Controllers var folder = Path.GetDirectoryName(playlist); if (folder == null) { - throw new NullReferenceException(nameof(folder)); + throw new ResourceNotFoundException(nameof(folder)); } var filename = Path.GetFileNameWithoutExtension(playlist); diff --git a/Jellyfin.Api/Controllers/EnvironmentController.cs b/Jellyfin.Api/Controllers/EnvironmentController.cs index 8de217bbfa..6dd5362547 100644 --- a/Jellyfin.Api/Controllers/EnvironmentController.cs +++ b/Jellyfin.Api/Controllers/EnvironmentController.cs @@ -5,6 +5,7 @@ using System.IO; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Models.EnvironmentDtos; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.IO; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -105,7 +106,7 @@ namespace Jellyfin.Api.Controllers { if (validatePathDto.Path == null) { - throw new NullReferenceException(nameof(validatePathDto.Path)); + throw new ResourceNotFoundException(nameof(validatePathDto.Path)); } var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString()); diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 2cee0e9ef2..fe1ffacb01 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -8,6 +8,7 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; @@ -138,7 +139,7 @@ namespace Jellyfin.Api.Controllers if (playlistPath == null) { - throw new NullReferenceException(nameof(playlistPath)); + throw new ResourceNotFoundException(nameof(playlistPath)); } return GetFileResult(file, playlistPath); diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index b6cb797167..b14840f80c 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -336,7 +336,7 @@ namespace Jellyfin.Api.Controllers using var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false); if (result.Content.Headers.ContentType?.MediaType == null) { - throw new NullReferenceException(nameof(result.Content.Headers.ContentType)); + throw new ResourceNotFoundException(nameof(result.Content.Headers.ContentType)); } var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; @@ -345,7 +345,7 @@ namespace Jellyfin.Api.Controllers var directory = Path.GetDirectoryName(fullCachePath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); @@ -365,7 +365,7 @@ namespace Jellyfin.Api.Controllers var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); if (pointerCacheDirectory == null) { - throw new NullReferenceException(nameof(pointerCacheDirectory)); + throw new ResourceNotFoundException(nameof(pointerCacheDirectory)); } Directory.CreateDirectory(pointerCacheDirectory); diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index ad76b39847..2566f574c4 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -251,7 +251,7 @@ namespace Jellyfin.Api.Controllers using var response = await httpClient.GetAsync(url).ConfigureAwait(false); if (response.Content.Headers.ContentType?.MediaType == null) { - throw new NullReferenceException(nameof(response.Content.Headers.ContentType)); + throw new ResourceNotFoundException(nameof(response.Content.Headers.ContentType)); } var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); @@ -260,7 +260,7 @@ namespace Jellyfin.Api.Controllers var fullCacheDirectory = Path.GetDirectoryName(fullCachePath); if (fullCacheDirectory == null) { - throw new NullReferenceException(nameof(fullCacheDirectory)); + throw new ResourceNotFoundException(nameof(fullCacheDirectory)); } Directory.CreateDirectory(fullCacheDirectory); @@ -270,7 +270,7 @@ namespace Jellyfin.Api.Controllers var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); if (pointerCacheDirectory == null) { - throw new NullReferenceException(nameof(pointerCacheDirectory)); + throw new ResourceNotFoundException(nameof(pointerCacheDirectory)); } Directory.CreateDirectory(pointerCacheDirectory); diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 517239966f..c47876beba 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -11,6 +11,7 @@ using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; @@ -364,7 +365,7 @@ namespace Jellyfin.Api.Controllers var directory = Path.GetDirectoryName(outputPath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs index c6d577b193..21ec2d32f9 100644 --- a/Jellyfin.Api/Helpers/AudioHelper.cs +++ b/Jellyfin.Api/Helpers/AudioHelper.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -101,7 +102,7 @@ namespace Jellyfin.Api.Helpers { if (_httpContextAccessor.HttpContext == null) { - throw new NullReferenceException(nameof(_httpContextAccessor.HttpContext)); + throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext)); } bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 20bca731fd..e7fac50c64 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -132,7 +132,7 @@ namespace Jellyfin.Api.Helpers { if (_httpContextAccessor.HttpContext == null) { - throw new NullReferenceException(nameof(_httpContextAccessor.HttpContext)); + throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext)); } using var state = await StreamingHelpers.GetStreamingState( diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 16fbac7ae2..707d1cd104 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -47,7 +48,7 @@ namespace Jellyfin.Api.Helpers var line = await reader.ReadLineAsync().ConfigureAwait(false); if (line == null) { - throw new NullReferenceException(nameof(line)); + throw new ResourceNotFoundException(nameof(line)); } if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) diff --git a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs index 65c03c710b..8bddf00d5f 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.PlaybackDtos; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Library; using MediaBrowser.Model.IO; @@ -92,7 +93,7 @@ namespace Jellyfin.Api.Helpers if (_path == null) { - throw new NullReferenceException(nameof(_path)); + throw new ResourceNotFoundException(nameof(_path)); } await using var inputStream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions); diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 1d102071c2..04b1077277 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -85,7 +85,7 @@ namespace Jellyfin.Api.Helpers streamingRequest.StreamOptions = ParseStreamOptions(httpRequest.Query); if (httpRequest.Path.Value == null) { - throw new NullReferenceException(nameof(httpRequest.Path)); + throw new ResourceNotFoundException(nameof(httpRequest.Path)); } var url = httpRequest.Path.Value.Split('.').Last(); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index b72e33af38..4ec0c576aa 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -12,6 +12,7 @@ using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using Jellyfin.Data.Enums; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -198,7 +199,7 @@ namespace Jellyfin.Api.Helpers var job = (TranscodingJobDto?)state; if (job == null) { - throw new NullReferenceException(nameof(job)); + throw new ResourceNotFoundException(nameof(job)); } if (!job.HasExited && job.Type != TranscodingJobType.Progressive) @@ -496,7 +497,7 @@ namespace Jellyfin.Api.Helpers var directory = Path.GetDirectoryName(outputPath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index ad066c524a..1570d247b8 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using BlurHashSharp.SkiaSharp; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Drawing; @@ -230,7 +231,7 @@ namespace Jellyfin.Drawing.Skia var directory = Path.GetDirectoryName(tempPath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); @@ -501,7 +502,7 @@ namespace Jellyfin.Drawing.Skia var outputDirectory = Path.GetDirectoryName(outputPath); if (outputDirectory == null) { - throw new NullReferenceException(nameof(outputDirectory)); + throw new ResourceNotFoundException(nameof(outputDirectory)); } Directory.CreateDirectory(outputDirectory); @@ -554,7 +555,7 @@ namespace Jellyfin.Drawing.Skia var directory = Path.GetDirectoryName(outputPath); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index ced25524ee..465fb09cd8 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -62,7 +62,7 @@ namespace Jellyfin.Server.Implementations.Users if (spr == null) { - throw new NullReferenceException(nameof(spr)); + throw new ResourceNotFoundException(nameof(spr)); } if (spr.ExpirationDate < DateTime.UtcNow) diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 11ad69d914..da04203e03 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Xml; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -130,7 +131,7 @@ namespace MediaBrowser.LocalMetadata.Savers var directory = Path.GetDirectoryName(path); if (directory == null) { - throw new NullReferenceException(nameof(directory)); + throw new ResourceNotFoundException(nameof(directory)); } Directory.CreateDirectory(directory); From 95ebb9a55ace6c544fa7fa15d0a255a5cee752a8 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 11:24:46 -0700 Subject: [PATCH 0328/1930] Use null coalescing when possible --- .../AppBase/ConfigurationHelper.cs | 6 +----- .../Cryptography/CryptographyProvider.cs | 7 +------ .../Session/WebSocketController.cs | 7 +------ .../Controllers/DynamicHlsController.cs | 13 ++---------- .../Controllers/HlsSegmentController.cs | 8 ++----- .../Controllers/ItemLookupController.cs | 13 ++---------- .../Controllers/RemoteImageController.cs | 14 ++----------- .../Controllers/VideoHlsController.cs | 7 +------ Jellyfin.Api/Helpers/HlsHelpers.cs | 7 ++----- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 14 ++----------- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 21 +++---------------- .../Users/DefaultPasswordResetProvider.cs | 8 ++----- .../Savers/BaseXmlSaver.cs | 7 +------ 13 files changed, 22 insertions(+), 110 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 8cca5cc779..b0a14f43d8 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -50,11 +50,7 @@ namespace Emby.Server.Implementations.AppBase // If the file didn't exist before, or if something has changed, re-save if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer)) { - var directory = Path.GetDirectoryName(path); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } + var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path)); Directory.CreateDirectory(directory); // Save it after load in case we got new items diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 8d7f73b3cf..42db183963 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -81,12 +81,7 @@ namespace Emby.Server.Implementations.Cryptography throw new CryptographicException($"Requested hash method is not supported: {hashMethod}"); } - using var h = HashAlgorithm.Create(hashMethod); - if (h == null) - { - throw new ResourceNotFoundException(nameof(h)); - } - + using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException(nameof(hashMethod)); if (salt.Length == 0) { return h.ComputeHash(bytes); diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index 78f83e337f..5268ea1b93 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -58,12 +58,7 @@ namespace Emby.Server.Implementations.Session private void OnConnectionClosed(object? sender, EventArgs e) { - if (sender == null) - { - throw new ResourceNotFoundException(nameof(sender)); - } - - var connection = (IWebSocketConnection)sender; + var connection = sender as IWebSocketConnection ?? throw new ResourceNotFoundException(nameof(sender)); _logger.LogDebug("Removing websocket from session {Session}", _session.Id); _sockets.Remove(connection); connection.Closed -= OnConnectionClosed; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 64bea999fa..783deebdce 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1348,11 +1348,7 @@ namespace Jellyfin.Api.Controllers var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var directory = Path.GetDirectoryName(outputPath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } + var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); @@ -1572,12 +1568,7 @@ namespace Jellyfin.Api.Controllers private string GetSegmentPath(StreamState state, string playlist, int index) { - var folder = Path.GetDirectoryName(playlist); - if (folder == null) - { - throw new ResourceNotFoundException(nameof(folder)); - } - + var folder = Path.GetDirectoryName(playlist) ?? throw new ResourceNotFoundException(nameof(playlist)); var filename = Path.GetFileNameWithoutExtension(playlist); return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer)); diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index fe1ffacb01..b9adcd3806 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -135,12 +135,8 @@ namespace Jellyfin.Api.Controllers var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath) .FirstOrDefault(i => string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) - && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1); - - if (playlistPath == null) - { - throw new ResourceNotFoundException(nameof(playlistPath)); - } + && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1) + ?? throw new ResourceNotFoundException(nameof(transcodeFolderPath)); return GetFileResult(file, playlistPath); } diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index b14840f80c..a0d9bfb543 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -342,12 +342,7 @@ namespace Jellyfin.Api.Controllers var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; var fullCachePath = GetFullCachePath(urlHash + "." + ext); - var directory = Path.GetDirectoryName(fullCachePath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath)); Directory.CreateDirectory(directory); using (var stream = result.Content) { @@ -362,11 +357,7 @@ namespace Jellyfin.Api.Controllers await stream.CopyToAsync(fileStream).ConfigureAwait(false); } - var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); - if (pointerCacheDirectory == null) - { - throw new ResourceNotFoundException(nameof(pointerCacheDirectory)); - } + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath)); Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index 2566f574c4..b4a9e5582d 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -257,22 +257,12 @@ namespace Jellyfin.Api.Controllers var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); var fullCachePath = GetFullCachePath(urlHash + "." + ext); - var fullCacheDirectory = Path.GetDirectoryName(fullCachePath); - if (fullCacheDirectory == null) - { - throw new ResourceNotFoundException(nameof(fullCacheDirectory)); - } - + var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath)); Directory.CreateDirectory(fullCacheDirectory); await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); - var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); - if (pointerCacheDirectory == null) - { - throw new ResourceNotFoundException(nameof(pointerCacheDirectory)); - } - + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath)); Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None) .ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index c47876beba..cc538f15e2 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -362,12 +362,7 @@ namespace Jellyfin.Api.Controllers var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; - var directory = Path.GetDirectoryName(outputPath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; var segmentFormat = format.TrimStart('.'); diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 707d1cd104..bcf0da319c 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -45,11 +45,8 @@ namespace Jellyfin.Api.Helpers while (!reader.EndOfStream) { - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (line == null) - { - throw new ResourceNotFoundException(nameof(line)); - } + var line = await reader.ReadLineAsync().ConfigureAwait(false) + ?? throw new ResourceNotFoundException(nameof(reader)); if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) { diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 4ec0c576aa..8466241838 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -196,12 +196,7 @@ namespace Jellyfin.Api.Helpers /// <param name="state">The state.</param> private async void OnTranscodeKillTimerStopped(object? state) { - var job = (TranscodingJobDto?)state; - if (job == null) - { - throw new ResourceNotFoundException(nameof(job)); - } - + var job = state as TranscodingJobDto ?? throw new ResourceNotFoundException(nameof(state)); if (!job.HasExited && job.Type != TranscodingJobType.Progressive) { var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds; @@ -494,12 +489,7 @@ namespace Jellyfin.Api.Helpers CancellationTokenSource cancellationTokenSource, string? workingDirectory = null) { - var directory = Path.GetDirectoryName(outputPath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); Directory.CreateDirectory(directory); await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false); diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index 1570d247b8..0c90d04a75 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -228,12 +228,7 @@ namespace Jellyfin.Drawing.Skia } var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path)); - var directory = Path.GetDirectoryName(tempPath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException(nameof(tempPath)); Directory.CreateDirectory(directory); File.Copy(path, tempPath, true); @@ -499,12 +494,7 @@ namespace Jellyfin.Drawing.Skia // If all we're doing is resizing then we can stop now if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) { - var outputDirectory = Path.GetDirectoryName(outputPath); - if (outputDirectory == null) - { - throw new ResourceNotFoundException(nameof(outputDirectory)); - } - + var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); Directory.CreateDirectory(outputDirectory); using var outputStream = new SKFileWStream(outputPath); using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); @@ -552,12 +542,7 @@ namespace Jellyfin.Drawing.Skia DrawIndicator(canvas, width, height, options); } - var directory = Path.GetDirectoryName(outputPath); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); Directory.CreateDirectory(directory); using (var outputStream = new SKFileWStream(outputPath)) { diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index 465fb09cd8..7f24904049 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -57,12 +57,8 @@ namespace Jellyfin.Server.Implementations.Users SerializablePasswordReset? spr; await using (var str = File.OpenRead(resetFile)) { - spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false); - } - - if (spr == null) - { - throw new ResourceNotFoundException(nameof(spr)); + spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false) + ?? throw new ResourceNotFoundException(nameof(spr)); } if (spr.ExpirationDate < DateTime.UtcNow) diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index da04203e03..2c9c9ccaa1 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -128,12 +128,7 @@ namespace MediaBrowser.LocalMetadata.Savers private void SaveToFile(Stream stream, string path) { - var directory = Path.GetDirectoryName(path); - if (directory == null) - { - throw new ResourceNotFoundException(nameof(directory)); - } - + var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path)); Directory.CreateDirectory(directory); // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); From 8c0778e82743d999367ad560aefee636db460afb Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 03:47:54 +0800 Subject: [PATCH 0329/1930] switch ffmpeg to hls muxer for live streaming segment muxer cannot make fMP4 init file. '-strict -2' option doesn't work with segment muxer for flac remuxing. --- .../Controllers/DynamicHlsController.cs | 85 ++++---- .../Controllers/VideoHlsController.cs | 199 ++++++++++++++---- Jellyfin.Api/Helpers/HlsHelpers.cs | 70 +++++- 3 files changed, 274 insertions(+), 80 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 0581928a0c..d4ae124b9a 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -41,6 +41,9 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] public class DynamicHlsController : BaseJellyfinApiController { + private const string DefaultEncoderPreset = "veryfast"; + private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private readonly ILibraryManager _libraryManager; private readonly IUserManager _userManager; private readonly IDlnaManager _dlnaManager; @@ -56,8 +59,7 @@ namespace Jellyfin.Api.Controllers private readonly ILogger<DynamicHlsController> _logger; private readonly EncodingHelper _encodingHelper; private readonly DynamicHlsHelper _dynamicHlsHelper; - - private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private readonly EncodingOptions _encodingOptions; /// <summary> /// Initializes a new instance of the <see cref="DynamicHlsController"/> class. @@ -92,6 +94,8 @@ namespace Jellyfin.Api.Controllers ILogger<DynamicHlsController> logger, DynamicHlsHelper dynamicHlsHelper) { + _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); + _libraryManager = libraryManager; _userManager = userManager; _dlnaManager = dlnaManager; @@ -106,8 +110,7 @@ namespace Jellyfin.Api.Controllers _transcodingJobHelper = transcodingJobHelper; _logger = logger; _dynamicHlsHelper = dynamicHlsHelper; - - _encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); + _encodingOptions = serverConfigurationManager.GetEncodingOptions(); } /// <summary> @@ -1255,7 +1258,7 @@ namespace Jellyfin.Api.Controllers if (segmentId == -1) { - _logger.LogDebug("Starting transcoding because fmp4 header file is being requested"); + _logger.LogDebug("Starting transcoding because fmp4 init file is being requested"); startTranscoding = true; segmentId = 0; } @@ -1291,11 +1294,10 @@ namespace Jellyfin.Api.Controllers streamingRequest.StartTimeTicks = GetStartPositionTicks(state, segmentId); state.WaitForPath = segmentPath; - var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); job = await _transcodingJobHelper.StartFfMpeg( state, playlistPath, - GetCommandLineArguments(playlistPath, encodingOptions, state, true, segmentId), + GetCommandLineArguments(playlistPath, state, true, segmentId), Request, _transcodingJobType, cancellationTokenSource).ConfigureAwait(false); @@ -1351,11 +1353,10 @@ namespace Jellyfin.Api.Controllers return result.ToArray(); } - private string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding, int startNumber) + private string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding, int startNumber) { - var videoCodec = _encodingHelper.GetVideoEncoder(state, encodingOptions); - - var threads = _encodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); + var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); + var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); if (state.BaseRequest.BreakOnNonKeyFrames) { @@ -1367,11 +1368,9 @@ namespace Jellyfin.Api.Controllers state.BaseRequest.BreakOnNonKeyFrames = false; } - var inputModifier = _encodingHelper.GetInputModifier(state, encodingOptions); - // If isEncoding is true we're actually starting ffmpeg var startNumberParam = isEncoding ? startNumber.ToString(CultureInfo.InvariantCulture) : "0"; - + var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); @@ -1379,7 +1378,7 @@ namespace Jellyfin.Api.Controllers var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); var outputTsArg = outputPrefix + "%d" + outputExtension; - var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var segmentFormat = outputExtension.TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) { segmentFormat = "mpegts"; @@ -1406,19 +1405,19 @@ namespace Jellyfin.Api.Controllers _logger.LogError("Invalid HLS segment container: " + segmentFormat); } - var maxMuxingQueueSize = encodingOptions.MaxMuxingQueueSize > 128 - ? encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture) + var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128 + ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture) : "128"; return string.Format( CultureInfo.InvariantCulture, "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts 0 -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"", inputModifier, - _encodingHelper.GetInputArgument(state, encodingOptions), + _encodingHelper.GetInputArgument(state, _encodingOptions), threads, mapArgs, - GetVideoArguments(state, encodingOptions, startNumber), - GetAudioArguments(state, encodingOptions), + GetVideoArguments(state, startNumber), + GetAudioArguments(state), maxMuxingQueueSize, state.SegmentLength.ToString(CultureInfo.InvariantCulture), segmentFormat, @@ -1427,7 +1426,12 @@ namespace Jellyfin.Api.Controllers outputPath).Trim(); } - private string GetAudioArguments(StreamState state, EncodingOptions encodingOptions) + /// <summary> + /// Gets the audio arguments for transcoding. + /// </summary> + /// <param name="state">The <see cref="StreamState"/>.</param> + /// <returns>The command line arguments for audio transcoding.</returns> + private string GetAudioArguments(StreamState state) { if (state.AudioStream == null) { @@ -1468,7 +1472,7 @@ namespace Jellyfin.Api.Controllers if (EncodingHelper.IsCopyCodec(audioCodec)) { - var videoCodec = _encodingHelper.GetVideoEncoder(state, encodingOptions); + var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec)) { @@ -1499,23 +1503,34 @@ namespace Jellyfin.Api.Controllers args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture); } - args += " " + _encodingHelper.GetAudioFilterParam(state, encodingOptions, true); + args += " " + _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true); return args; } - private string GetVideoArguments(StreamState state, EncodingOptions encodingOptions, int startNumber) + /// <summary> + /// Gets the video arguments for transcoding. + /// </summary> + /// <param name="state">The <see cref="StreamState"/>.</param> + /// <param name="startNumber">The first number in the hls sequence.</param> + /// <returns>The command line arguments for video transcoding.</returns> + private string GetVideoArguments(StreamState state, int startNumber) { + if (state.VideoStream == null) + { + return string.Empty; + } + if (!state.IsOutputVideo) { return string.Empty; } - var codec = _encodingHelper.GetVideoEncoder(state, encodingOptions); + var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); var args = "-codec:v:0 " + codec; - // Prefer hvc1 to hev1 + // Prefer hvc1 to hev1. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) @@ -1529,7 +1544,7 @@ namespace Jellyfin.Api.Controllers // args += " -mpegts_m2ts_mode 1"; // } - // See if we can save come cpu cycles by avoiding encoding + // See if we can save come cpu cycles by avoiding encoding. if (EncodingHelper.IsCopyCodec(codec)) { if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) @@ -1553,22 +1568,21 @@ namespace Jellyfin.Api.Controllers state.SegmentLength); var framerate = state.VideoStream?.RealFrameRate; - if (framerate.HasValue) { // This is to make sure keyframe interval is limited to our segment, // as forcing keyframes is not enough. // Example: we encoded half of desired length, then codec detected // scene cut and inserted a keyframe; next forced keyframe would - // be created outside of segment, which breaks seeking - // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe + // be created outside of segment, which breaks seeking. + // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe. gopArg = string.Format( CultureInfo.InvariantCulture, " -g {0} -keyint_min {0} -sc_threshold 0", Math.Ceiling(state.SegmentLength * framerate.Value)); } - args += " " + _encodingHelper.GetVideoQualityParam(state, codec, encodingOptions, "veryfast"); + args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); // Unable to force key frames using these encoders, set key frames by GOP. if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) @@ -1602,16 +1616,15 @@ namespace Jellyfin.Api.Controllers var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; - // This is for graphical subs if (hasGraphicalSubs) { - args += _encodingHelper.GetGraphicalSubtitleParam(state, encodingOptions, codec); + // Graphical subs overlay and resolution params. + args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec); } - - // Add resolution params, if specified else { - args += _encodingHelper.GetOutputSizeParam(state, encodingOptions, codec); + // Resolution params. + args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec); } // -start_at_zero is necessary to use with -ss when seeking, diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index d7bcf79c1f..7676b23316 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; @@ -37,7 +38,7 @@ namespace Jellyfin.Api.Controllers public class VideoHlsController : BaseJellyfinApiController { private const string DefaultEncoderPreset = "superfast"; - private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls; + private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; private readonly EncodingHelper _encodingHelper; private readonly IDlnaManager _dlnaManager; @@ -290,30 +291,30 @@ namespace Jellyfin.Api.Controllers _dlnaManager, _deviceManager, _transcodingJobHelper, - TranscodingJobType, + _transcodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); TranscodingJobDto? job = null; - var playlist = state.OutputFilePath; + var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8"); - if (!System.IO.File.Exists(playlist)) + if (!System.IO.File.Exists(playlistPath)) { - var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlist); + var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlistPath); await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false); try { - if (!System.IO.File.Exists(playlist)) + if (!System.IO.File.Exists(playlistPath)) { // If the playlist doesn't already exist, startup ffmpeg try { job = await _transcodingJobHelper.StartFfMpeg( state, - playlist, - GetCommandLineArguments(playlist, state), + playlistPath, + GetCommandLineArguments(playlistPath, state), Request, - TranscodingJobType, + _transcodingJobType, cancellationTokenSource) .ConfigureAwait(false); job.IsLiveOutput = true; @@ -327,7 +328,7 @@ namespace Jellyfin.Api.Controllers minSegments = state.MinSegments; if (minSegments > 0) { - await HlsHelpers.WaitForMinimumSegmentCount(playlist, minSegments, _logger, cancellationTokenSource.Token).ConfigureAwait(false); + await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationTokenSource.Token).ConfigureAwait(false); } } } @@ -337,14 +338,14 @@ namespace Jellyfin.Api.Controllers } } - job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlist, TranscodingJobType); + job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); if (job != null) { _transcodingJobHelper.OnTranscodeEndRequest(job); } - var playlistText = HlsHelpers.GetLivePlaylistText(playlist, state.SegmentLength); + var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state); return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8")); } @@ -360,14 +361,43 @@ namespace Jellyfin.Api.Controllers var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); - var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; - var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; + var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var segmentFormat = format.TrimStart('.'); + var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); + var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), outputFileNameWithoutExtension); + var outputExtension = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer); + var outputTsArg = outputPrefix + "%d" + outputExtension; + + var segmentFormat = outputExtension.TrimStart('.'); if (string.Equals(segmentFormat, "ts", StringComparison.OrdinalIgnoreCase)) { segmentFormat = "mpegts"; } + else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) + { + var outputFmp4HeaderArg = string.Empty; + var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + if (isWindows) + { + // on Windows, the path of fmp4 header file needs to be configured + outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\""; + } + else + { + // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder + outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""; + } + + segmentFormat = "fmp4" + outputFmp4HeaderArg; + } + else + { + _logger.LogError("Invalid HLS segment container: " + segmentFormat); + } + + var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128 + ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture) + : "128"; var baseUrlParam = string.Format( CultureInfo.InvariantCulture, @@ -376,20 +406,19 @@ namespace Jellyfin.Api.Controllers return string.Format( CultureInfo.InvariantCulture, - "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -f segment -max_delay 5000000 -avoid_negative_ts disabled -start_at_zero -segment_time {6} {7} -individual_header_trailer 0 -segment_format {8} -segment_list_entry_prefix {9} -segment_list_type m3u8 -segment_start_number 0 -segment_list \"{10}\" -y \"{11}\"", + "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts 0 -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number 0 -hls_base_url {9} -hls_playlist_type event -hls_segment_filename \"{10}\" -y \"{11}\"", inputModifier, _encodingHelper.GetInputArgument(state, _encodingOptions), threads, _encodingHelper.GetMapArgs(state), GetVideoArguments(state), GetAudioArguments(state), + maxMuxingQueueSize, state.SegmentLength.ToString(CultureInfo.InvariantCulture), - string.Empty, segmentFormat, baseUrlParam, - outputPath, - outputTsArg) - .Trim(); + outputTsArg, + outputPath).Trim(); } /// <summary> @@ -399,14 +428,49 @@ namespace Jellyfin.Api.Controllers /// <returns>The command line arguments for audio transcoding.</returns> private string GetAudioArguments(StreamState state) { - var codec = _encodingHelper.GetAudioEncoder(state); - - if (EncodingHelper.IsCopyCodec(codec)) + if (state.AudioStream == null) { - return "-codec:a:0 copy"; + return string.Empty; } - var args = "-codec:a:0 " + codec; + var audioCodec = _encodingHelper.GetAudioEncoder(state); + + if (!state.IsOutputVideo) + { + if (EncodingHelper.IsCopyCodec(audioCodec)) + { + return "-acodec copy -strict -2"; + } + + var audioTranscodeParams = new List<string>(); + + audioTranscodeParams.Add("-acodec " + audioCodec); + + if (state.OutputAudioBitrate.HasValue) + { + audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture)); + } + + if (state.OutputAudioChannels.HasValue) + { + audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture)); + } + + if (state.OutputAudioSampleRate.HasValue) + { + audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)); + } + + audioTranscodeParams.Add("-vn"); + return string.Join(' ', audioTranscodeParams); + } + + if (EncodingHelper.IsCopyCodec(audioCodec)) + { + return "-codec:a:0 copy -strict -2"; + } + + var args = "-codec:a:0 " + audioCodec; var channels = state.OutputAudioChannels; @@ -439,6 +503,11 @@ namespace Jellyfin.Api.Controllers /// <returns>The command line arguments for video transcoding.</returns> private string GetVideoArguments(StreamState state) { + if (state.VideoStream == null) + { + return string.Empty; + } + if (!state.IsOutputVideo) { return string.Empty; @@ -448,17 +517,25 @@ namespace Jellyfin.Api.Controllers var args = "-codec:v:0 " + codec; + // Prefer hvc1 to hev1. + if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)) + { + args += " -tag:v:0 hvc1"; + } + // if (state.EnableMpegtsM2TsMode) // { // args += " -mpegts_m2ts_mode 1"; // } - // See if we can save come cpu cycles by avoiding encoding - if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase)) + // See if we can save come cpu cycles by avoiding encoding. + if (EncodingHelper.IsCopyCodec(codec)) { - // if h264_mp4toannexb is ever added, do not use it for live tv - if (state.VideoStream != null && - !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) + // If h264_mp4toannexb is ever added, do not use it for live tv. + if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.VideoStream); if (!string.IsNullOrEmpty(bitStreamArgs)) @@ -469,25 +546,73 @@ namespace Jellyfin.Api.Controllers } else { + var gopArg = string.Empty; var keyFrameArg = string.Format( CultureInfo.InvariantCulture, " -force_key_frames \"expr:gte(t,n_forced*{0})\"", state.SegmentLength.ToString(CultureInfo.InvariantCulture)); + var framerate = state.VideoStream?.RealFrameRate; + if (framerate.HasValue) + { + // This is to make sure keyframe interval is limited to our segment, + // as forcing keyframes is not enough. + // Example: we encoded half of desired length, then codec detected + // scene cut and inserted a keyframe; next forced keyframe would + // be created outside of segment, which breaks seeking. + // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe. + gopArg = string.Format( + CultureInfo.InvariantCulture, + " -g {0} -keyint_min {0} -sc_threshold 0", + Math.Ceiling(state.SegmentLength * framerate.Value)); + } + + args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); + + // Unable to force key frames using these encoders, set key frames by GOP. + if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + args += " " + gopArg; + } + else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) + { + args += " " + keyFrameArg; + } + else + { + args += " " + keyFrameArg + gopArg; + } + + // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now. + if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) + { + args += " -bf 0"; + } + var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; - args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset) + keyFrameArg; - - // Add resolution params, if specified - if (!hasGraphicalSubs) + if (hasGraphicalSubs) { + // Graphical subs overlay and resolution params. + args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec); + } + else + { + // Resolution params. args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec); } - // This is for internal graphical subs - if (hasGraphicalSubs) + if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)) { - args += _encodingHelper.GetGraphicalSubtitleParam(state, _encodingOptions, codec); + args += " -start_at_zero"; } } diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 2424966973..0bbe92baad 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -1,8 +1,10 @@ using System; using System.Globalization; using System.IO; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -69,25 +71,79 @@ namespace Jellyfin.Api.Helpers } } + /// <summary> + /// Gets the extension of segment container. + /// </summary> + /// <param name="segmentContainer">The name of the segment container.</param> + /// <returns>The string text of extension.</returns> + public static string GetSegmentFileExtension(string? segmentContainer) + { + if (!string.IsNullOrWhiteSpace(segmentContainer)) + { + return "." + segmentContainer; + } + + return ".ts"; + } + + /// <summary> + /// Gets the #EXT-X-MAP string. + /// </summary> + /// <param name="outputPath">The output path of the file.</param> + /// <param name="state">The <see cref="StreamState"/>.</param> + /// <param name="isOsDepends">Get a normal string or depends on OS.</param> + /// <returns>The string text of #EXT-X-MAP.</returns> + public static string GetFmp4InitFileName(string outputPath, StreamState state, bool isOsDepends) + { + var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); + var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), outputFileNameWithoutExtension); + var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); + + // on Linux/Unix + // #EXT-X-MAP:URI="prefix-1.mp4" + var fmp4InitFileName = outputFileNameWithoutExtension + "-1" + outputExtension; + if (!isOsDepends) + { + return fmp4InitFileName; + } + + var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + if (isWindows) + { + // on Windows + // #EXT-X-MAP:URI="X:\transcodes\prefix-1.mp4" + fmp4InitFileName = outputPrefix + "-1" + outputExtension; + } + + return fmp4InitFileName; + } + /// <summary> /// Gets the hls playlist text. /// </summary> /// <param name="path">The path to the playlist file.</param> - /// <param name="segmentLength">The segment length.</param> + /// <param name="state">The <see cref="StreamState"/>.</param> /// <returns>The playlist text as a string.</returns> - public static string GetLivePlaylistText(string path, int segmentLength) + public static string GetLivePlaylistText(string path, StreamState state) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var reader = new StreamReader(stream); var text = reader.ReadToEnd(); - text = text.Replace("#EXTM3U", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT", StringComparison.InvariantCulture); + var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) + { + var fmp4InitFileName = GetFmp4InitFileName(path, state, true); + var baseUrlParam = string.Format( + CultureInfo.InvariantCulture, + "hls/{0}/", + Path.GetFileNameWithoutExtension(path)); + var newFmp4InitFileName = baseUrlParam + GetFmp4InitFileName(path, state, false); - var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(CultureInfo.InvariantCulture); - - text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength - 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); - // text = text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(CultureInfo.InvariantCulture), newDuration, StringComparison.OrdinalIgnoreCase); + // Replace fMP4 init file URI. + text = text.Replace(fmp4InitFileName, newFmp4InitFileName, StringComparison.InvariantCulture); + } return text; } From 563a6fb3c7cd933059995cac710f46287774d401 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sun, 8 Nov 2020 18:08:59 +0100 Subject: [PATCH 0330/1930] Minor changes to group-wait in SyncPlay --- .../SyncPlay/GroupController.cs | 10 ++++ .../SyncPlay/GroupStates/WaitingGroupState.cs | 53 +++++++++++++------ .../SyncPlay/ISyncPlayStateContext.cs | 12 +++++ 3 files changed, 58 insertions(+), 17 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 01e1166171..ffd65d7f8a 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -28,6 +28,16 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> public long DefaultPing { get; } = 500; + /// <summary> + /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds. + /// </summary> + public long TimeSyncOffset { get; } = 2000; + + /// <summary> + /// Gets the maximum offset error accepted for position reported by clients, in milliseconds. + /// </summary> + public long MaxPlaybackOffset { get; } = 500; + /// <summary> /// The logger. /// </summary> diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs index 8e970751f1..bc3cc49182 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs @@ -423,28 +423,42 @@ namespace MediaBrowser.Controller.SyncPlay return; } - var requestTicks = context.SanitizePositionTicks(request.PositionTicks); + // Compute elapsed time between the client reported time and now. + // Elapsed time is used to estimate the client position when playback is unpaused. + // Ideally, the request is received and handled without major delays. + // However, to avoid waiting indefinitely when a client is not reporting a correct time, + // the elapsed time is ignored after a certain threshold. var currentTime = DateTime.UtcNow; - var elapsedTime = currentTime - request.When; + var elapsedTime = currentTime.Subtract(request.When); + var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks; + if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks) + { + _logger.LogWarning("HandleRequest: {0} in group {1}, {2} is not time syncing properly. Ignoring elapsed time.", + request.GetRequestType(), context.GroupId.ToString(), session.Id); + + elapsedTime = TimeSpan.Zero; + } + + // Ignore elapsed time if client is paused. if (!request.IsPlaying) { elapsedTime = TimeSpan.Zero; } + var requestTicks = context.SanitizePositionTicks(request.PositionTicks); var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime; var delayTicks = context.PositionTicks - clientPosition.Ticks; + var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks; - if (delayTicks > TimeSpan.FromSeconds(5).Ticks) - { - // The client is really behind, other participants will have to wait a lot of time... - _logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); - } + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} at {3} (delay of {4} seconds).", + request.GetRequestType(), context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); if (ResumePlaying) { // Handle case where session reported as ready but in reality // it has no clue of the real position nor the playback state. - if (!request.IsPlaying && Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) { + if (!request.IsPlaying && Math.Abs(delayTicks) > maxPlaybackOffsetTicks) + { // Session not ready at all. context.SetBuffering(session, true); @@ -455,7 +469,8 @@ namespace MediaBrowser.Controller.SyncPlay // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", + request.GetRequestType(), context.GroupId.ToString(), session.Id); return; } @@ -470,7 +485,8 @@ namespace MediaBrowser.Controller.SyncPlay command.When = context.DateToUTCString(pauseAtTime); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - _logger.LogDebug("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogInformation("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready in {3} seconds.", + request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -489,7 +505,8 @@ namespace MediaBrowser.Controller.SyncPlay context.SendCommand(session, filter, command, cancellationToken); - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogInformation("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume in {3} seconds.", + request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -502,7 +519,8 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogWarning("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time. {3} seconds to recover.", + request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } // Change state. @@ -513,12 +531,11 @@ namespace MediaBrowser.Controller.SyncPlay } else { - // Check that session is really ready, tollerate half second difference to account for player imperfections. - if (Math.Abs(context.PositionTicks - requestTicks) > TimeSpan.FromSeconds(0.5).Ticks) + // Check that session is really ready, tollerate player imperfections under a certain threshold. + if (Math.Abs(context.PositionTicks - requestTicks) > maxPlaybackOffsetTicks) { // Session still not ready. context.SetBuffering(session, true); - // Session is seeking to wrong position, correcting. var command = context.NewSyncPlayCommand(SendCommandType.Seek); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); @@ -526,7 +543,8 @@ namespace MediaBrowser.Controller.SyncPlay // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogWarning("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", + request.GetRequestType(), context.GroupId.ToString(), session.Id); return; } else { // Session is ready. @@ -550,7 +568,8 @@ namespace MediaBrowser.Controller.SyncPlay pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); } - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", + request.GetRequestType(), context.GroupId.ToString(), session.Id); } } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs index 13d38a02bb..4aac2a8818 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs @@ -17,6 +17,18 @@ namespace MediaBrowser.Controller.SyncPlay /// <value>The default ping value used for sessions, in milliseconds.</value> long DefaultPing { get; } + /// <summary> + /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds. + /// </summary> + /// <value>The maximum offset error accepted, in milliseconds.</value> + long TimeSyncOffset { get; } + + /// <summary> + /// Gets the maximum offset error accepted for position reported by clients, in milliseconds. + /// </summary> + /// <value>The maximum offset error accepted, in milliseconds.</value> + long MaxPlaybackOffset { get; } + /// <summary> /// Gets the group identifier. /// </summary> From f1e129f17afb1ddbea7f1018f81a7af87cbfada7 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 03:57:37 +0800 Subject: [PATCH 0331/1930] minor changes --- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 7676b23316..7b50b47b1c 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -410,7 +410,7 @@ namespace Jellyfin.Api.Controllers inputModifier, _encodingHelper.GetInputArgument(state, _encodingOptions), threads, - _encodingHelper.GetMapArgs(state), + mapArgs, GetVideoArguments(state), GetAudioArguments(state), maxMuxingQueueSize, From 536b0548730466d7b1e51178146c004af8801ae8 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 04:06:24 +0800 Subject: [PATCH 0332/1930] add experimental flag for flac --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1ae896df0f..0bc5308b6b 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -64,7 +64,7 @@ namespace MediaBrowser.Controller.MediaEncoding { // Only use alternative encoders for video files. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully - // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this. + // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this. if (state.VideoType == VideoType.VideoFile) { var hwType = encodingOptions.HardwareAccelerationType; @@ -441,6 +441,12 @@ namespace MediaBrowser.Controller.MediaEncoding return "libopus"; } + if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase)) + { + // flac is experimental in mp4 muxer + return "flac -strict -2"; + } + return codec.ToLowerInvariant(); } From 24ac5cc353dd5b9930d43a5659d97037644fa58a Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 13:18:31 -0700 Subject: [PATCH 0333/1930] Update Emby.Server.Implementations/AppBase/ConfigurationHelper.cs Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index b0a14f43d8..6c425c7fb4 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -36,8 +36,7 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception) { - var instanceConfiguration = Activator.CreateInstance(type); - configuration = instanceConfiguration ?? throw new ResourceNotFoundException(nameof(instanceConfiguration)); + configuration = Activator.CreateInstance(type) ?? throw new ResourceNotFoundException(nameof(type)); } using var stream = new MemoryStream(buffer?.Length ?? 0); From 5845bf93cb7e55f22f42378e55f0da4b02ba0a46 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 14:52:22 -0700 Subject: [PATCH 0334/1930] Fix plugin update exception --- Emby.Server.Implementations/ApplicationHost.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 9d5b651d99..f3bd95d805 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -996,6 +996,12 @@ namespace Emby.Server.Implementations { var minimumVersion = new Version(0, 0, 0, 1); var versions = new List<LocalPlugin>(); + if (!Directory.Exists(path)) + { + // Plugin path doesn't exist, don't try to enumerate subfolders. + return Enumerable.Empty<LocalPlugin>(); + } + var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); foreach (var dir in directories) From 5d4144b8a6d29cbbc37275878ae439678ff2cc45 Mon Sep 17 00:00:00 2001 From: Relja U <andrew.browncloud@gmail.com> Date: Fri, 13 Nov 2020 20:19:38 +0000 Subject: [PATCH 0335/1930] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- Emby.Server.Implementations/Localization/Core/sr.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 2b1eccfaf3..8da92f3099 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -112,5 +112,7 @@ "TasksChannelsCategory": "Интернет канали", "TasksApplicationCategory": "Апликација", "TasksLibraryCategory": "Библиотека", - "TasksMaintenanceCategory": "Одржавање" + "TasksMaintenanceCategory": "Одржавање", + "TaskCleanActivityLogDescription": "Брише историју активности старију од конфигурисаног броја година.", + "TaskCleanActivityLog": "Очисти историју активности" } From 722adda47737d6da261e51819fa41d5e6a46e021 Mon Sep 17 00:00:00 2001 From: Oatavandi <oatavandi@gmail.com> Date: Fri, 13 Nov 2020 17:46:08 +0000 Subject: [PATCH 0336/1930] Translated using Weblate (Tamil) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ta/ --- Emby.Server.Implementations/Localization/Core/ta.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index 8089fc3042..e8cd23d5d1 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -112,5 +112,7 @@ "UserOnlineFromDevice": "{1} இருந்து {0} ஆன்லைன்", "HomeVideos": "முகப்பு வீடியோக்கள்", "UserStoppedPlayingItemWithValues": "{0} {2} இல் {1} முடித்துவிட்டது", - "UserStartedPlayingItemWithValues": "{0} {2}இல் {1} ஐ இயக்குகிறது" + "UserStartedPlayingItemWithValues": "{0} {2}இல் {1} ஐ இயக்குகிறது", + "TaskCleanActivityLogDescription": "உள்ளமைக்கப்பட்ட வயதை விட பழைய செயல்பாட்டு பதிவு உள்ளீடுகளை நீக்குகிறது.", + "TaskCleanActivityLog": "செயல்பாட்டு பதிவை அழி" } From 73d2cb1c2a3a7cd1a30840a2b52921a3b81c6809 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 13 Nov 2020 18:04:06 -0700 Subject: [PATCH 0337/1930] Updated based on review feedback --- .../AppBase/ConfigurationHelper.cs | 4 ++-- .../Cryptography/CryptographyProvider.cs | 2 +- .../Session/WebSocketController.cs | 2 +- Jellyfin.Api/Controllers/DynamicHlsController.cs | 4 ++-- Jellyfin.Api/Controllers/HlsSegmentController.cs | 2 +- Jellyfin.Api/Controllers/ItemLookupController.cs | 4 ++-- Jellyfin.Api/Controllers/RemoteImageController.cs | 4 ++-- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- Jellyfin.Api/Helpers/HlsHelpers.cs | 9 ++++++--- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 4 ++-- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 6 +++--- .../Users/DefaultPasswordResetProvider.cs | 2 +- MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs | 2 +- 13 files changed, 25 insertions(+), 22 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 6c425c7fb4..77819c7649 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.AppBase } catch (Exception) { - configuration = Activator.CreateInstance(type) ?? throw new ResourceNotFoundException(nameof(type)); + configuration = Activator.CreateInstance(type) ?? throw new ArgumentException($"Provided path ({type}) is not valid.", nameof(type)); } using var stream = new MemoryStream(buffer?.Length ?? 0); @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.AppBase // If the file didn't exist before, or if something has changed, re-save if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer)) { - var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path)); + var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); Directory.CreateDirectory(directory); // Save it after load in case we got new items diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 42db183963..12a9e44e70 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -81,7 +81,7 @@ namespace Emby.Server.Implementations.Cryptography throw new CryptographicException($"Requested hash method is not supported: {hashMethod}"); } - using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException(nameof(hashMethod)); + using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException($"Unknown hash method: {hashMethod}."); if (salt.Length == 0) { return h.ComputeHash(bytes); diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index 5268ea1b93..f9c6a13c69 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -58,7 +58,7 @@ namespace Emby.Server.Implementations.Session private void OnConnectionClosed(object? sender, EventArgs e) { - var connection = sender as IWebSocketConnection ?? throw new ResourceNotFoundException(nameof(sender)); + var connection = sender as IWebSocketConnection ?? throw new ArgumentException($"{nameof(sender)} is not of type {nameof(IWebSocketConnection)}", nameof(sender)); _logger.LogDebug("Removing websocket from session {Session}", _session.Id); _sockets.Remove(connection); connection.Closed -= OnConnectionClosed; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 783deebdce..6e59da798c 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1348,7 +1348,7 @@ namespace Jellyfin.Api.Controllers var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; - var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); + var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); @@ -1568,7 +1568,7 @@ namespace Jellyfin.Api.Controllers private string GetSegmentPath(StreamState state, string playlist, int index) { - var folder = Path.GetDirectoryName(playlist) ?? throw new ResourceNotFoundException(nameof(playlist)); + var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not valid.", nameof(playlist)); var filename = Path.GetFileNameWithoutExtension(playlist); return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer)); diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index b9adcd3806..3b75e8d431 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -136,7 +136,7 @@ namespace Jellyfin.Api.Controllers .FirstOrDefault(i => string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1) - ?? throw new ResourceNotFoundException(nameof(transcodeFolderPath)); + ?? throw new ResourceNotFoundException($"Provided path ({transcodeFolderPath}) is not valid."); return GetFileResult(file, playlistPath); } diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index a0d9bfb543..a7c1a63882 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -342,7 +342,7 @@ namespace Jellyfin.Api.Controllers var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; var fullCachePath = GetFullCachePath(urlHash + "." + ext); - var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath)); + var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid."); Directory.CreateDirectory(directory); using (var stream = result.Content) { @@ -357,7 +357,7 @@ namespace Jellyfin.Api.Controllers await stream.CopyToAsync(fileStream).ConfigureAwait(false); } - var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath)); + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath)); Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index b4a9e5582d..c2bfab175a 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -257,12 +257,12 @@ namespace Jellyfin.Api.Controllers var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); var fullCachePath = GetFullCachePath(urlHash + "." + ext); - var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath)); + var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid."); Directory.CreateDirectory(fullCacheDirectory); await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); - var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath)); + var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath)); Directory.CreateDirectory(pointerCacheDirectory); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None) .ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index cc538f15e2..389dc8a088 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -362,7 +362,7 @@ namespace Jellyfin.Api.Controllers var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; - var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); + var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; var segmentFormat = format.TrimStart('.'); diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index bcf0da319c..7fd784806e 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -3,7 +3,6 @@ using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Extensions; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -45,8 +44,12 @@ namespace Jellyfin.Api.Helpers while (!reader.EndOfStream) { - var line = await reader.ReadLineAsync().ConfigureAwait(false) - ?? throw new ResourceNotFoundException(nameof(reader)); + var line = await reader.ReadLineAsync().ConfigureAwait(false); + if (line == null) + { + // Nothing currently in buffer. + continue; + } if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) { diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 8466241838..168dc27a83 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Helpers /// <param name="state">The state.</param> private async void OnTranscodeKillTimerStopped(object? state) { - var job = state as TranscodingJobDto ?? throw new ResourceNotFoundException(nameof(state)); + var job = state as TranscodingJobDto ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJobDto)}", nameof(state)); if (!job.HasExited && job.Type != TranscodingJobType.Progressive) { var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds; @@ -489,7 +489,7 @@ namespace Jellyfin.Api.Helpers CancellationTokenSource cancellationTokenSource, string? workingDirectory = null) { - var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); + var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); Directory.CreateDirectory(directory); await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false); diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index 0c90d04a75..ee60748c71 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -228,7 +228,7 @@ namespace Jellyfin.Drawing.Skia } var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path)); - var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException(nameof(tempPath)); + var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException($"Provided path ({tempPath}) is not valid."); Directory.CreateDirectory(directory); File.Copy(path, tempPath, true); @@ -494,7 +494,7 @@ namespace Jellyfin.Drawing.Skia // If all we're doing is resizing then we can stop now if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) { - var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); + var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); Directory.CreateDirectory(outputDirectory); using var outputStream = new SKFileWStream(outputPath); using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); @@ -542,7 +542,7 @@ namespace Jellyfin.Drawing.Skia DrawIndicator(canvas, width, height, options); } - var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath)); + var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); Directory.CreateDirectory(directory); using (var outputStream = new SKFileWStream(outputPath)) { diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index 7f24904049..e71d419e0c 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Server.Implementations.Users await using (var str = File.OpenRead(resetFile)) { spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false) - ?? throw new ResourceNotFoundException(nameof(spr)); + ?? throw new ResourceNotFoundException($"Provided path ({resetFile}) is not valid."); } if (spr.ExpirationDate < DateTime.UtcNow) diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 2c9c9ccaa1..396206658d 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -128,7 +128,7 @@ namespace MediaBrowser.LocalMetadata.Savers private void SaveToFile(Stream stream, string path) { - var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path)); + var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); Directory.CreateDirectory(directory); // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); From 32bb73acbb071a8329c485738176711dac4e1bcb Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 14:22:15 +0800 Subject: [PATCH 0338/1930] add aac_adtstoasc bitstream filter for mpegts to mp4 conversion --- .../Controllers/DynamicHlsController.cs | 29 +++++++++++++++++-- .../Controllers/VideoHlsController.cs | 28 ++++++++++++++++-- .../MediaEncoding/EncodingHelper.cs | 16 ++++++++-- 3 files changed, 66 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index d4ae124b9a..10c2d3fecc 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1444,7 +1444,19 @@ namespace Jellyfin.Api.Controllers { if (EncodingHelper.IsCopyCodec(audioCodec)) { - return "-acodec copy -strict -2"; + var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var bitStreamArgs = string.Empty; + + // Apply aac_adtstoasc bitstream filter when media source is in mpegts. + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) + && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) + { + bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); + bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + } + + return "-acodec copy -strict -2" + bitStreamArgs; } var audioTranscodeParams = new List<string>(); @@ -1473,13 +1485,24 @@ namespace Jellyfin.Api.Controllers if (EncodingHelper.IsCopyCodec(audioCodec)) { var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); + var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var bitStreamArgs = string.Empty; + + // Apply aac_adtstoasc bitstream filter when media source is in mpegts. + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) + && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) + { + bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); + bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + } if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec)) { - return "-codec:a:0 copy -strict -2 -copypriorss:a:0 0"; + return "-codec:a:0 copy -strict -2 -copypriorss:a:0 0" + bitStreamArgs; } - return "-codec:a:0 copy -strict -2"; + return "-codec:a:0 copy -strict -2" + bitStreamArgs; } var args = "-codec:a:0 " + audioCodec; diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 7b50b47b1c..21c042f4b6 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -439,7 +439,19 @@ namespace Jellyfin.Api.Controllers { if (EncodingHelper.IsCopyCodec(audioCodec)) { - return "-acodec copy -strict -2"; + var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var bitStreamArgs = string.Empty; + + // Apply aac_adtstoasc bitstream filter when media source is in mpegts. + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) + && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) + { + bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); + bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + } + + return "-acodec copy -strict -2" + bitStreamArgs; } var audioTranscodeParams = new List<string>(); @@ -467,7 +479,19 @@ namespace Jellyfin.Api.Controllers if (EncodingHelper.IsCopyCodec(audioCodec)) { - return "-codec:a:0 copy -strict -2"; + var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var bitStreamArgs = string.Empty; + + // Apply aac_adtstoasc bitstream filter when media source is in mpegts. + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) + && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) + || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) + { + bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); + bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + } + + return "-acodec copy -strict -2" + bitStreamArgs; } var args = "-codec:a:0 " + audioCodec; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 0bc5308b6b..a8252d4734 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -596,10 +596,17 @@ namespace MediaBrowser.Controller.MediaEncoding || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1; } - // TODO This is auto inserted into the mpegts mux so it might not be needed - // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb + public bool IsAAC(MediaStream stream) + { + var codec = stream.Codec ?? string.Empty; + + return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1; + } + public string GetBitStreamArgs(MediaStream stream) { + // TODO This is auto inserted into the mpegts mux so it might not be needed + // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb if (IsH264(stream)) { return "-bsf:v h264_mp4toannexb"; @@ -608,6 +615,11 @@ namespace MediaBrowser.Controller.MediaEncoding { return "-bsf:v hevc_mp4toannexb"; } + else if (IsAAC(stream)) + { + // convert adts header(mpegts) to asc header(mp4) + return "-bsf:a aac_adtstoasc"; + } else { return null; From fc89b7e6416ed750725154104b37f32496435555 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 15:46:17 +0800 Subject: [PATCH 0339/1930] minor changes --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 2 ++ Jellyfin.Api/Controllers/VideoHlsController.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 10c2d3fecc..643c6073c1 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1579,6 +1579,8 @@ namespace Jellyfin.Api.Controllers } } + args += " -start_at_zero"; + // args += " -flags -global_header"; } else diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 21c042f4b6..4ae61fbd36 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -567,6 +567,8 @@ namespace Jellyfin.Api.Controllers args += " " + bitStreamArgs; } } + + args += " -start_at_zero"; } else { From 06670351ae6be1d3c47a25fe14b2f253cc6ab3e7 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 10:19:41 +0000 Subject: [PATCH 0340/1930] Apply suggestions from code review Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 4 ++-- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 643c6073c1..625275171e 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1453,7 +1453,7 @@ namespace Jellyfin.Api.Controllers || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) { bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; } return "-acodec copy -strict -2" + bitStreamArgs; @@ -1494,7 +1494,7 @@ namespace Jellyfin.Api.Controllers || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) { bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; } if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec)) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 4ae61fbd36..93bb3a9038 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -448,7 +448,7 @@ namespace Jellyfin.Api.Controllers || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) { bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; + bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;; } return "-acodec copy -strict -2" + bitStreamArgs; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index a8252d4734..b181a6ee6d 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -605,7 +605,7 @@ namespace MediaBrowser.Controller.MediaEncoding public string GetBitStreamArgs(MediaStream stream) { - // TODO This is auto inserted into the mpegts mux so it might not be needed + // TODO This is auto inserted into the mpegts mux so it might not be needed. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb if (IsH264(stream)) { @@ -617,7 +617,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (IsAAC(stream)) { - // convert adts header(mpegts) to asc header(mp4) + // Convert adts header(mpegts) to asc header(mp4). return "-bsf:a aac_adtstoasc"; } else From 750eaa9d276fda77512ec30c09d20371174aa13a Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 18:30:20 +0800 Subject: [PATCH 0341/1930] fix ci --- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 93bb3a9038..1ced08617a 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -448,7 +448,7 @@ namespace Jellyfin.Api.Controllers || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) { bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;; + bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; } return "-acodec copy -strict -2" + bitStreamArgs; From 1dbc91978ece81628c339d1dc3b53f6d250cb005 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Fri, 13 Nov 2020 15:13:32 +0100 Subject: [PATCH 0342/1930] Address requested changes and fix some warnings --- .../SyncPlay/GroupController.cs | 247 +++++++------ .../SyncPlay/GroupStates/IdleGroupState.cs | 122 ------- .../SyncPlay/SyncPlayManager.cs | 27 +- .../Controllers/SyncPlayController.cs | 12 +- .../GroupStates/AbstractGroupState.cs | 130 ++++--- .../SyncPlay/GroupStates/IdleGroupState.cs | 126 +++++++ .../SyncPlay/GroupStates/PausedGroupState.cs | 70 ++-- .../SyncPlay/GroupStates/PlayingGroupState.cs | 84 ++--- .../SyncPlay/GroupStates/WaitingGroupState.cs | 242 ++++++------ ...cPlayController.cs => IGroupController.cs} | 9 +- .../SyncPlay/IGroupPlaybackRequest.cs | 27 ++ .../{ISyncPlayState.cs => IGroupState.cs} | 52 +-- ...yStateContext.cs => IGroupStateContext.cs} | 17 +- .../SyncPlay/IPlaybackGroupRequest.cs | 23 -- .../SyncPlay/ISyncPlayManager.cs | 6 +- .../PlaybackRequest/IgnoreWaitGroupRequest.cs | 30 -- .../PlaybackRequest/PauseGroupRequest.cs | 24 -- .../RemoveFromPlaylistGroupRequest.cs | 30 -- .../PlaybackRequest/StopGroupRequest.cs | 24 -- .../PlaybackRequest/UnpauseGroupRequest.cs | 24 -- .../BufferGroupRequest.cs | 15 +- .../IgnoreWaitGroupRequest.cs | 27 ++ .../MovePlaylistItemGroupRequest.cs | 13 +- .../NextTrackGroupRequest.cs | 13 +- .../PlaybackRequests/PauseGroupRequest.cs | 21 ++ .../PingGroupRequest.cs | 13 +- .../PlayGroupRequest.cs | 18 +- .../PreviousTrackGroupRequest.cs | 13 +- .../QueueGroupRequest.cs | 18 +- .../ReadyGroupRequest.cs | 15 +- .../RemoveFromPlaylistGroupRequest.cs | 28 ++ .../SeekGroupRequest.cs | 13 +- .../SetPlaylistItemGroupRequest.cs} | 13 +- .../SetRepeatModeGroupRequest.cs | 13 +- .../SetShuffleModeGroupRequest.cs | 13 +- .../PlaybackRequests/StopGroupRequest.cs | 21 ++ .../PlaybackRequests/UnpauseGroupRequest.cs | 21 ++ .../SyncPlay/Queue/PlayQueueManager.cs | 343 ++++++++++-------- MediaBrowser.Model/SyncPlay/GroupInfoDto.cs | 2 +- .../{GroupState.cs => GroupStateType.cs} | 5 +- .../SyncPlay/GroupStateUpdate.cs | 4 +- MediaBrowser.Model/SyncPlay/GroupUpdate.cs | 1 + .../SyncPlay/PlayQueueUpdate.cs | 4 +- .../SyncPlay/PlaybackRequestType.cs | 1 + 44 files changed, 977 insertions(+), 997 deletions(-) delete mode 100644 Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs rename {Emby.Server.Implementations => MediaBrowser.Controller}/SyncPlay/GroupStates/AbstractGroupState.cs (51%) create mode 100644 MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs rename {Emby.Server.Implementations => MediaBrowser.Controller}/SyncPlay/GroupStates/PausedGroupState.cs (54%) rename {Emby.Server.Implementations => MediaBrowser.Controller}/SyncPlay/GroupStates/PlayingGroupState.cs (53%) rename {Emby.Server.Implementations => MediaBrowser.Controller}/SyncPlay/GroupStates/WaitingGroupState.cs (67%) rename MediaBrowser.Controller/SyncPlay/{ISyncPlayController.cs => IGroupController.cs} (94%) create mode 100644 MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs rename MediaBrowser.Controller/SyncPlay/{ISyncPlayState.cs => IGroupState.cs} (75%) rename MediaBrowser.Controller/SyncPlay/{ISyncPlayStateContext.cs => IGroupStateContext.cs} (93%) delete mode 100644 MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs delete mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/BufferGroupRequest.cs (69%) create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/MovePlaylistItemGroupRequest.cs (62%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/NextTrackGroupRequest.cs (54%) create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/PingGroupRequest.cs (53%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/PlayGroupRequest.cs (61%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/PreviousTrackGroupRequest.cs (55%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/QueueGroupRequest.cs (54%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/ReadyGroupRequest.cs (70%) create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/SeekGroupRequest.cs (54%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest/SetCurrentItemGroupRequest.cs => PlaybackRequests/SetPlaylistItemGroupRequest.cs} (56%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/SetRepeatModeGroupRequest.cs (53%) rename MediaBrowser.Controller/SyncPlay/{PlaybackRequest => PlaybackRequests}/SetShuffleModeGroupRequest.cs (53%) create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs rename MediaBrowser.Model/SyncPlay/{GroupState.cs => GroupStateType.cs} (95%) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index ffd65d7f8a..5a3c707dbf 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -16,28 +16,13 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay { /// <summary> - /// Class SyncPlayGroupController. + /// Class GroupController. /// </summary> /// <remarks> /// Class is not thread-safe, external locking is required when accessing methods. /// </remarks> - public class SyncPlayGroupController : ISyncPlayGroupController, ISyncPlayStateContext + public class GroupController : IGroupController, IGroupStateContext { - /// <summary> - /// Gets the default ping value used for sessions. - /// </summary> - public long DefaultPing { get; } = 500; - - /// <summary> - /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds. - /// </summary> - public long TimeSyncOffset { get; } = 2000; - - /// <summary> - /// Gets the maximum offset error accepted for position reported by clients, in milliseconds. - /// </summary> - public long MaxPlaybackOffset { get; } = 500; - /// <summary> /// The logger. /// </summary> @@ -67,7 +52,46 @@ namespace Emby.Server.Implementations.SyncPlay /// Internal group state. /// </summary> /// <value>The group's state.</value> - private ISyncPlayState State; + private IGroupState _state; + + /// <summary> + /// Initializes a new instance of the <see cref="GroupController" /> class. + /// </summary> + /// <param name="logger">The logger.</param> + /// <param name="userManager">The user manager.</param> + /// <param name="sessionManager">The session manager.</param> + /// <param name="libraryManager">The library manager.</param> + /// <param name="syncPlayManager">The SyncPlay manager.</param> + public GroupController( + ILogger logger, + IUserManager userManager, + ISessionManager sessionManager, + ILibraryManager libraryManager, + ISyncPlayManager syncPlayManager) + { + _logger = logger; + _userManager = userManager; + _sessionManager = sessionManager; + _libraryManager = libraryManager; + _syncPlayManager = syncPlayManager; + + _state = new IdleGroupState(_logger); + } + + /// <summary> + /// Gets the default ping value used for sessions. + /// </summary> + public long DefaultPing { get; } = 500; + + /// <summary> + /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds. + /// </summary> + public long TimeSyncOffset { get; } = 2000; + + /// <summary> + /// Gets the maximum offset error accepted for position reported by clients, in milliseconds. + /// </summary> + public long MaxPlaybackOffset { get; } = 500; /// <summary> /// Gets the group identifier. @@ -88,7 +112,7 @@ namespace Emby.Server.Implementations.SyncPlay public PlayQueueManager PlayQueue { get; } = new PlayQueueManager(); /// <summary> - /// Gets or sets the runtime ticks of current playing item. + /// Gets the runtime ticks of current playing item. /// </summary> /// <value>The runtime ticks of current playing item.</value> public long RunTimeTicks { get; private set; } @@ -112,30 +136,6 @@ namespace Emby.Server.Implementations.SyncPlay public Dictionary<string, GroupMember> Participants { get; } = new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase); - /// <summary> - /// Initializes a new instance of the <see cref="SyncPlayGroupController" /> class. - /// </summary> - /// <param name="logger">The logger.</param> - /// <param name="userManager">The user manager.</param> - /// <param name="sessionManager">The session manager.</param> - /// <param name="libraryManager">The library manager.</param> - /// <param name="syncPlayManager">The SyncPlay manager.</param> - public SyncPlayGroupController( - ILogger logger, - IUserManager userManager, - ISessionManager sessionManager, - ILibraryManager libraryManager, - ISyncPlayManager syncPlayManager) - { - _logger = logger; - _userManager = userManager; - _sessionManager = sessionManager; - _libraryManager = libraryManager; - _syncPlayManager = syncPlayManager; - - State = new IdleGroupState(_logger); - } - /// <summary> /// Adds the session to the group. /// </summary> @@ -167,34 +167,32 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="from">The current session.</param> /// <param name="type">The filtering type.</param> /// <returns>The array of sessions matching the filter.</returns> - private SessionInfo[] FilterSessions(SessionInfo from, SyncPlayBroadcastType type) + private IEnumerable<SessionInfo> FilterSessions(SessionInfo from, SyncPlayBroadcastType type) { - switch (type) + return type switch { - case SyncPlayBroadcastType.CurrentSession: - return new SessionInfo[] { from }; - case SyncPlayBroadcastType.AllGroup: - return Participants - .Values - .Select(session => session.Session) - .ToArray(); - case SyncPlayBroadcastType.AllExceptCurrentSession: - return Participants - .Values - .Select(session => session.Session) - .Where(session => !session.Id.Equals(from.Id)) - .ToArray(); - case SyncPlayBroadcastType.AllReady: - return Participants - .Values - .Where(session => !session.IsBuffering) - .Select(session => session.Session) - .ToArray(); - default: - return Array.Empty<SessionInfo>(); - } + SyncPlayBroadcastType.CurrentSession => new SessionInfo[] { from }, + SyncPlayBroadcastType.AllGroup => Participants + .Values + .Select(session => session.Session), + SyncPlayBroadcastType.AllExceptCurrentSession => Participants + .Values + .Select(session => session.Session) + .Where(session => !session.Id.Equals(from.Id, StringComparison.OrdinalIgnoreCase)), + SyncPlayBroadcastType.AllReady => Participants + .Values + .Where(session => !session.IsBuffering) + .Select(session => session.Session), + _ => Enumerable.Empty<SessionInfo>() + }; } + /// <summary> + /// Checks if a given user can access a given item, that is, the user has access to a folder where the item is stored. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="item">The item.</param> + /// <returns><c>true</c> if the user can access the item, <c>false</c> otherwise.</returns> private bool HasAccessToItem(User user, BaseItem item) { var collections = _libraryManager.GetCollectionFolders(item) @@ -202,41 +200,42 @@ namespace Emby.Server.Implementations.SyncPlay return collections.Intersect(user.GetPreference(PreferenceKind.EnabledFolders)).Any(); } - private bool HasAccessToQueue(User user, Guid[] queue) + /// <summary> + /// Checks if a given user can access all items of a given queue, that is, + /// the user has the required minimum parental access and has access to all required folders. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="queue">The queue.</param> + /// <returns><c>true</c> if the user can access all the items in the queue, <c>false</c> otherwise.</returns> + private bool HasAccessToQueue(User user, IEnumerable<Guid> queue) { - if (queue == null || queue.Length == 0) + // Check if queue is empty. + if (!queue?.Any() ?? true) { return true; } - var items = queue.ToList() - .Select(item => _libraryManager.GetItemById(item)); - - // Find the highest rating value, which becomes the required minimum for the user. - var MinParentalRatingAccessRequired = items - .Select(item => item.InheritedParentalRatingValue) - .Min(); - - // Check ParentalRating access, user must have the minimum required access level. - var hasParentalRatingAccess = !user.MaxParentalAgeRating.HasValue - || MinParentalRatingAccessRequired <= user.MaxParentalAgeRating; - - // Check that user has access to all required folders. - if (!user.HasPermission(PermissionKind.EnableAllFolders) && hasParentalRatingAccess) + foreach (var itemId in queue) { - // Get list of items that are not accessible. - var blockedItems = items.Where(item => !HasAccessToItem(user, item)); + var item = _libraryManager.GetItemById(itemId); + if (user.MaxParentalAgeRating.HasValue && item.InheritedParentalRatingValue > user.MaxParentalAgeRating) + { + return false; + } - // We need the user to be able to access all items. - return !blockedItems.Any(); + if (!user.HasPermission(PermissionKind.EnableAllFolders) && !HasAccessToItem(user, item)) + { + return false; + } } - return hasParentalRatingAccess; + return true; } - private bool AllUsersHaveAccessToQueue(Guid[] queue) + private bool AllUsersHaveAccessToQueue(IEnumerable<Guid> queue) { - if (queue == null || queue.Length == 0) + // Check if queue is empty. + if (!queue?.Any() ?? true) { return true; } @@ -269,7 +268,7 @@ namespace Emby.Server.Implementations.SyncPlay if (sessionIsPlayingAnItem) { - var playlist = session.NowPlayingQueue.Select(item => item.Id).ToArray(); + var playlist = session.NowPlayingQueue.Select(item => item.Id); PlayQueue.Reset(); PlayQueue.SetPlaylist(playlist); PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id); @@ -277,17 +276,19 @@ namespace Emby.Server.Implementations.SyncPlay PositionTicks = session.PlayState.PositionTicks ?? 0; // Mantain playstate. - var waitingState = new WaitingGroupState(_logger); - waitingState.ResumePlaying = !session.PlayState.IsPaused; + var waitingState = new WaitingGroupState(_logger) + { + ResumePlaying = !session.PlayState.IsPaused + }; SetState(waitingState); } var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); - State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("InitGroup: {0} created group {1}.", session.Id.ToString(), GroupId.ToString()); + _logger.LogInformation("InitGroup: {0} created group {1}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -302,9 +303,9 @@ namespace Emby.Server.Implementations.SyncPlay var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionJoin: {0} joined group {1}.", session.Id.ToString(), GroupId.ToString()); + _logger.LogInformation("SessionJoin: {0} joined group {1}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -316,15 +317,15 @@ namespace Emby.Server.Implementations.SyncPlay var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - State.SessionJoined(this, State.GetGroupState(), session, cancellationToken); + _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionRestore: {0} re-joined group {1}.", session.Id.ToString(), GroupId.ToString()); + _logger.LogInformation("SessionRestore: {0} re-joined group {1}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) { - State.SessionLeaving(this, State.GetGroupState(), session, cancellationToken); + _state.SessionLeaving(this, _state.Type, session, cancellationToken); RemoveSession(session); _syncPlayManager.RemoveSessionFromGroup(session, this); @@ -335,18 +336,17 @@ namespace Emby.Server.Implementations.SyncPlay var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - _logger.LogInformation("SessionLeave: {0} left group {1}.", session.Id.ToString(), GroupId.ToString()); + _logger.LogInformation("SessionLeave: {0} left group {1}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> - public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) + public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { // The server's job is to maintain a consistent state for clients to reference // and notify clients of state changes. The actual syncing of media playback // happens client side. Clients are aware of the server's time and use it to sync. - _logger.LogInformation("HandleRequest: {0} requested {1}, group {2} in {3} state.", - session.Id.ToString(), request.GetRequestType(), GroupId.ToString(), State.GetGroupState()); - request.Apply(this, State, session, cancellationToken); + _logger.LogInformation("HandleRequest: {0} requested {1}, group {2} in {3} state.", session.Id, request.Type, GroupId.ToString(), _state.Type); + request.Apply(this, _state, session, cancellationToken); } /// <inheritdoc /> @@ -356,7 +356,7 @@ namespace Emby.Server.Implementations.SyncPlay { GroupId = GroupId.ToString(), GroupName = GroupName, - State = State.GetGroupState(), + State = _state.Type, Participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(), LastUpdatedAt = DateToUTCString(DateTime.UtcNow) }; @@ -365,7 +365,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public bool HasAccessToPlayQueue(User user) { - var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToArray(); + var items = PlayQueue.GetPlaylist().Select(item => item.ItemId); return HasAccessToQueue(user, items); } @@ -381,10 +381,10 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SetState(ISyncPlayState state) + public void SetState(IGroupState state) { - _logger.LogInformation("SetState: {0} switching from {1} to {2}.", GroupId.ToString(), State.GetGroupState(), state.GetGroupState()); - this.State = state; + _logger.LogInformation("SetState: {0} switching from {1} to {2}.", GroupId.ToString(), _state.Type, state.Type); + this._state = state; } /// <inheritdoc /> @@ -443,16 +443,14 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public string DateToUTCString(DateTime dateTime) { - return dateTime.ToUniversalTime().ToString("o"); + return dateTime.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture); } /// <inheritdoc /> public long SanitizePositionTicks(long? positionTicks) { var ticks = positionTicks ?? 0; - ticks = Math.Max(ticks, 0); - ticks = Math.Min(ticks, RunTimeTicks); - return ticks; + return Math.Clamp(ticks, 0, RunTimeTicks); } /// <inheritdoc /> @@ -509,10 +507,10 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks) + public bool SetPlayQueue(IEnumerable<Guid> playQueue, int playingItemPosition, long startPositionTicks) { // Ignore on empty queue or invalid item position. - if (playQueue.Length < 1 || playingItemPosition >= playQueue.Length || playingItemPosition < 0) + if (!playQueue.Any() || playingItemPosition >= playQueue.Count() || playingItemPosition < 0) { return false; } @@ -555,7 +553,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool RemoveFromPlayQueue(string[] playlistItemIds) + public bool RemoveFromPlayQueue(IEnumerable<string> playlistItemIds) { var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds); if (playingItemRemoved) @@ -584,10 +582,10 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool AddToPlayQueue(Guid[] newItems, string mode) + public bool AddToPlayQueue(IEnumerable<Guid> newItems, string mode) { // Ignore on empty list. - if (newItems.Length < 1) + if (!newItems.Any()) { return false; } @@ -598,7 +596,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } - if (mode.Equals("next")) + if (mode.Equals("next", StringComparison.OrdinalIgnoreCase)) { PlayQueue.QueueNext(newItems); } @@ -652,7 +650,8 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SetRepeatMode(string mode) { + public void SetRepeatMode(string mode) + { switch (mode) { case "RepeatOne": @@ -669,7 +668,8 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SetShuffleMode(string mode) { + public void SetShuffleMode(string mode) + { switch (mode) { case "Shuffle": @@ -687,7 +687,7 @@ namespace Emby.Server.Implementations.SyncPlay { var startPositionTicks = PositionTicks; - if (State.GetGroupState().Equals(GroupState.Playing)) + if (_state.Type.Equals(GroupStateType.Playing)) { var currentTime = DateTime.UtcNow; var elapsedTime = currentTime - LastActivity; @@ -711,6 +711,5 @@ namespace Emby.Server.Implementations.SyncPlay RepeatMode = PlayQueue.RepeatMode }; } - } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs b/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs deleted file mode 100644 index 70fe3e0067..0000000000 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/IdleGroupState.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Threading; -using MediaBrowser.Controller.Session; -using MediaBrowser.Model.SyncPlay; -using Microsoft.Extensions.Logging; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class IdleGroupState. - /// </summary> - /// <remarks> - /// Class is not thread-safe, external locking is required when accessing methods. - /// </remarks> - public class IdleGroupState : AbstractGroupState - { - /// <summary> - /// Default constructor. - /// </summary> - public IdleGroupState(ILogger logger) - : base(logger) - { - // Do nothing. - } - - /// <inheritdoc /> - public override GroupState GetGroupState() - { - return GroupState.Idle; - } - - /// <inheritdoc /> - public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, GetGroupState(), session, cancellationToken); - } - - /// <inheritdoc /> - public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) - { - // Do nothing. - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - // Change state. - var waitingState = new WaitingGroupState(_logger); - context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - // Change state. - var waitingState = new WaitingGroupState(_logger); - context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, prevState, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, prevState, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, prevState, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, prevState, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - SendStopCommand(context, prevState, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - // Change state. - var waitingState = new WaitingGroupState(_logger); - context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); - } - - /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) - { - // Change state. - var waitingState = new WaitingGroupState(_logger); - context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); - } - - private void SendStopCommand(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) - { - var command = context.NewSyncPlayCommand(SendCommandType.Stop); - if (!prevState.Equals(GetGroupState())) - { - context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - } - else - { - context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - } - } - } -} diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index ab9be145f3..178536631e 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -39,14 +39,14 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// The map between sessions and groups. /// </summary> - private readonly Dictionary<string, ISyncPlayGroupController> _sessionToGroupMap = - new Dictionary<string, ISyncPlayGroupController>(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, IGroupController> _sessionToGroupMap = + new Dictionary<string, IGroupController>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The groups. /// </summary> - private readonly Dictionary<Guid, ISyncPlayGroupController> _groups = - new Dictionary<Guid, ISyncPlayGroupController>(); + private readonly Dictionary<Guid, IGroupController> _groups = + new Dictionary<Guid, IGroupController>(); /// <summary> /// Lock used for accesing any group. @@ -83,7 +83,7 @@ namespace Emby.Server.Implementations.SyncPlay /// Gets all groups. /// </summary> /// <value>All groups.</value> - public IEnumerable<ISyncPlayGroupController> Groups => _groups.Values; + public IEnumerable<IGroupController> Groups => _groups.Values; /// <inheritdoc /> public void Dispose() @@ -229,7 +229,7 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } - var group = new SyncPlayGroupController(_logger, _userManager, _sessionManager, _libraryManager, this); + var group = new GroupController(_logger, _userManager, _sessionManager, _libraryManager, this); _groups[group.GroupId] = group; group.CreateGroup(session, request, cancellationToken); @@ -249,7 +249,7 @@ namespace Emby.Server.Implementations.SyncPlay lock (_groupsLock) { - _groups.TryGetValue(groupId, out ISyncPlayGroupController group); + _groups.TryGetValue(groupId, out IGroupController group); if (group == null) { @@ -346,7 +346,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken) + public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { // TODO: create abstract class for GroupRequests to avoid explicit request type here. if (!IsRequestValid(session, GroupRequestType.Playback, request)) @@ -375,28 +375,23 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group) + public void AddSessionToGroup(SessionInfo session, IGroupController group) { if (session == null) { throw new InvalidOperationException("Session is null!"); } - if (group == null) - { - throw new InvalidOperationException("Group is null!"); - } - if (IsSessionInGroup(session)) { throw new InvalidOperationException("Session in other group already!"); } - _sessionToGroupMap[session.Id] = group; + _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); } /// <inheritdoc /> - public void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group) + public void RemoveSessionFromGroup(SessionInfo session, IGroupController group) { if (session == null) { diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 847c3ab117..6bd78179b5 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -125,10 +125,10 @@ namespace Jellyfin.Api.Controllers var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new PlayGroupRequest() { - PlayingQueue = RequestHelpers.GetGuids(playingQueue), PlayingItemPosition = playingItemPosition, StartPositionTicks = startPositionTicks }; + syncPlayRequest.PlayingQueue.AddRange(RequestHelpers.GetGuids(playingQueue)); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -165,10 +165,8 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string[] playlistItemIds) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new RemoveFromPlaylistGroupRequest() - { - PlaylistItemIds = playlistItemIds - }; + var syncPlayRequest = new RemoveFromPlaylistGroupRequest(); + syncPlayRequest.PlaylistItemIds.AddRange(playlistItemIds); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -212,9 +210,9 @@ namespace Jellyfin.Api.Controllers var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new QueueGroupRequest() { - ItemIds = RequestHelpers.GetGuids(itemIds), Mode = mode }; + syncPlayRequest.ItemIds.AddRange(RequestHelpers.GetGuids(itemIds)); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -304,7 +302,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] bool bufferingDone) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - IPlaybackGroupRequest syncPlayRequest; + IGroupPlaybackRequest syncPlayRequest; if (!bufferingDone) { syncPlayRequest = new BufferGroupRequest() diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs similarity index 51% rename from Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs rename to MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index 26cd51b8d8..829ef2bbab 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; @@ -11,71 +12,53 @@ namespace MediaBrowser.Controller.SyncPlay /// <remarks> /// Class is not thread-safe, external locking is required when accessing methods. /// </remarks> - public abstract class AbstractGroupState : ISyncPlayState + public abstract class AbstractGroupState : IGroupState { /// <summary> - /// The logger. + /// Initializes a new instance of the <see cref="AbstractGroupState"/> class. /// </summary> - protected readonly ILogger _logger; - - /// <summary> - /// Default constructor. - /// </summary> - public AbstractGroupState(ILogger logger) + /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> + protected AbstractGroupState(ILogger logger) { - _logger = logger; - } - - /// <summary> - /// Sends a group state update to all group. - /// </summary> - /// <param name="context">The context of the state.</param> - /// <param name="reason">The reason of the state change.</param> - /// <param name="session">The session.</param> - /// <param name="cancellationToken">The cancellation token.</param> - protected void SendGroupStateUpdate(ISyncPlayStateContext context, IPlaybackGroupRequest reason, SessionInfo session, CancellationToken cancellationToken) - { - // Notify relevant state change event. - var stateUpdate = new GroupStateUpdate() - { - State = GetGroupState(), - Reason = reason.GetRequestType() - }; - var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate); - context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + Logger = logger; } /// <inheritdoc /> - public abstract GroupState GetGroupState(); + public abstract GroupStateType Type { get; } + + /// <summary> + /// Gets the logger. + /// </summary> + protected ILogger Logger { get; } /// <inheritdoc /> - public abstract void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + public abstract void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <inheritdoc /> - public abstract void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + public abstract void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, IGroupPlaybackRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { var playingItemRemoved = context.RemoveFromPlayQueue(request.PlaylistItemIds); @@ -83,29 +66,25 @@ namespace MediaBrowser.Controller.SyncPlay var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); - if (playingItemRemoved) + if (playingItemRemoved && !context.PlayQueue.IsItemPlaying()) { - var PlayingItemIndex = context.PlayQueue.PlayingItemIndex; - if (context.PlayQueue.PlayingItemIndex == -1) - { - _logger.LogDebug("HandleRequest: {0} in group {1}, play queue is empty.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, play queue is empty.", request.Type, context.GroupId.ToString()); - ISyncPlayState idleState = new IdleGroupState(_logger); - context.SetState(idleState); - var stopRequest = new StopGroupRequest(); - idleState.HandleRequest(context, GetGroupState(), stopRequest, session, cancellationToken); - } + IGroupState idleState = new IdleGroupState(Logger); + context.SetState(idleState); + var stopRequest = new StopGroupRequest(); + idleState.HandleRequest(context, Type, stopRequest, session, cancellationToken); } } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { var result = context.MoveItemInPlayQueue(request.PlaylistItemId, request.NewIndex); if (!result) { - _logger.LogError("HandleRequest: {0} in group {1}, unable to move item in play queue.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogError("HandleRequest: {0} in group {1}, unable to move item in play queue.", request.Type, context.GroupId.ToString()); return; } @@ -115,72 +94,72 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { var result = context.AddToPlayQueue(request.ItemIds, request.Mode); if (!result) { - _logger.LogError("HandleRequest: {0} in group {1}, unable to add items to play queue.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogError("HandleRequest: {0} in group {1}, unable to add items to play queue.", request.Type, context.GroupId.ToString()); return; } - var reason = request.Mode.Equals("next") ? PlayQueueUpdateReason.QueueNext : PlayQueueUpdateReason.Queue; + var reason = request.Mode.Equals("next", StringComparison.OrdinalIgnoreCase) ? PlayQueueUpdateReason.QueueNext : PlayQueueUpdateReason.Queue; var playQueueUpdate = context.GetPlayQueueUpdate(reason); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { context.SetRepeatMode(request.Mode); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RepeatMode); @@ -189,7 +168,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { context.SetShuffleMode(request.Mode); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.ShuffleMode); @@ -198,21 +177,40 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Collected pings are used to account for network latency when unpausing playback. context.UpdatePing(session, request.Ping); } /// <inheritdoc /> - public virtual void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { context.SetIgnoreGroupWait(session, request.IgnoreWait); } - private void UnhandledRequest(IPlaybackGroupRequest request) + /// <summary> + /// Sends a group state update to all group. + /// </summary> + /// <param name="context">The context of the state.</param> + /// <param name="reason">The reason of the state change.</param> + /// <param name="session">The session.</param> + /// <param name="cancellationToken">The cancellation token.</param> + protected void SendGroupStateUpdate(IGroupStateContext context, IGroupPlaybackRequest reason, SessionInfo session, CancellationToken cancellationToken) { - _logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.GetRequestType(), GetGroupState()); + // Notify relevant state change event. + var stateUpdate = new GroupStateUpdate() + { + State = Type, + Reason = reason.Type + }; + var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate); + context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); + } + + private void UnhandledRequest(IGroupPlaybackRequest request) + { + Logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.Type, Type); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs new file mode 100644 index 0000000000..1a507e044c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -0,0 +1,126 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class IdleGroupState. + /// </summary> + /// <remarks> + /// Class is not thread-safe, external locking is required when accessing methods. + /// </remarks> + public class IdleGroupState : AbstractGroupState + { + /// <summary> + /// Initializes a new instance of the <see cref="IdleGroupState"/> class. + /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> + public IdleGroupState(ILogger logger) + : base(logger) + { + // Do nothing. + } + + /// <inheritdoc /> + public override GroupStateType Type + { + get + { + return GroupStateType.Idle; + } + } + + /// <inheritdoc /> + public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, Type, session, cancellationToken); + } + + /// <inheritdoc /> + public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) + { + // Do nothing. + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state. + var waitingState = new WaitingGroupState(Logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state. + var waitingState = new WaitingGroupState(Logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + SendStopCommand(context, prevState, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state. + var waitingState = new WaitingGroupState(Logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); + } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + // Change state. + var waitingState = new WaitingGroupState(Logger); + context.SetState(waitingState); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); + } + + private void SendStopCommand(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) + { + var command = context.NewSyncPlayCommand(SendCommandType.Stop); + if (!prevState.Equals(Type)) + { + context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); + } + else + { + context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); + } + } + } +} diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs similarity index 54% rename from Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs rename to MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index ca2cb0988b..11f526d31d 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -15,8 +15,9 @@ namespace MediaBrowser.Controller.SyncPlay public class PausedGroupState : AbstractGroupState { /// <summary> - /// Default constructor. + /// Initializes a new instance of the <see cref="PausedGroupState"/> class. /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> public PausedGroupState(ILogger logger) : base(logger) { @@ -24,48 +25,51 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupState GetGroupState() + public override GroupStateType Type { - return GroupState.Paused; + get + { + return GroupStateType.Paused; + } } /// <inheritdoc /> - public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Wait for session to be ready. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); + waitingState.SessionJoined(context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Do nothing. } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var playingState = new PlayingGroupState(_logger); + var playingState = new PlayingGroupState(Logger); context.SetState(playingState); - playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + playingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - if (!prevState.Equals(GetGroupState())) + if (!prevState.Equals(Type)) { // Pause group and compute the media playback position. var currentTime = DateTime.UtcNow; @@ -94,42 +98,42 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var idleState = new IdleGroupState(_logger); + var idleState = new IdleGroupState(Logger); context.SetState(idleState); - idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + idleState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - if (prevState.Equals(GetGroupState())) + if (prevState.Equals(Type)) { // Client got lost, sending current state. var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } - else if (prevState.Equals(GroupState.Waiting)) + else if (prevState.Equals(GroupStateType.Waiting)) { // Sending current state to all clients. var command = context.NewSyncPlayCommand(SendCommandType.Pause); @@ -141,21 +145,21 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs similarity index 53% rename from Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs rename to MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index 85119669dd..2aa7598118 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -15,13 +15,9 @@ namespace MediaBrowser.Controller.SyncPlay public class PlayingGroupState : AbstractGroupState { /// <summary> - /// Ignore requests for buffering. - /// </summary> - public bool IgnoreBuffering { get; set; } - - /// <summary> - /// Default constructor. + /// Initializes a new instance of the <see cref="PlayingGroupState"/> class. /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> public PlayingGroupState(ILogger logger) : base(logger) { @@ -29,39 +25,47 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupState GetGroupState() + public override GroupStateType Type { - return GroupState.Playing; + get + { + return GroupStateType.Playing; + } } + /// <summary> + /// Gets or sets a value indicating whether requests for buffering should be ignored. + /// </summary> + public bool IgnoreBuffering { get; set; } + /// <inheritdoc /> - public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Wait for session to be ready. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.SessionJoined(context, GetGroupState(), session, cancellationToken); + waitingState.SessionJoined(context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Do nothing. } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - if (!prevState.Equals(GetGroupState())) + if (!prevState.Equals(Type)) { // Pick a suitable time that accounts for latency. var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing); @@ -70,9 +74,7 @@ namespace MediaBrowser.Controller.SyncPlay // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position). // The added delay does not guarantee, of course, that the command will be received in time. // Playback synchronization will mainly happen client side. - context.LastActivity = DateTime.UtcNow.AddMilliseconds( - delayMillis - ); + context.LastActivity = DateTime.UtcNow.AddMilliseconds(delayMillis); var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); @@ -89,34 +91,34 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var pausedState = new PausedGroupState(_logger); + var pausedState = new PausedGroupState(Logger); context.SetState(pausedState); - pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + pausedState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var idleState = new IdleGroupState(_logger); + var idleState = new IdleGroupState(Logger); context.SetState(idleState); - idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + idleState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { if (IgnoreBuffering) { @@ -124,21 +126,21 @@ namespace MediaBrowser.Controller.SyncPlay } // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - if (prevState.Equals(GetGroupState())) + if (prevState.Equals(Type)) { // Group was not waiting, make sure client has latest state. var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } - else if (prevState.Equals(GroupState.Waiting)) + else if (prevState.Equals(GroupStateType.Waiting)) { // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); @@ -146,21 +148,21 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(_logger); + var waitingState = new WaitingGroupState(Logger); context.SetState(waitingState); - waitingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + waitingState.HandleRequest(context, Type, request, session, cancellationToken); } } } diff --git a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs similarity index 67% rename from Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs rename to MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index bc3cc49182..7f454570a9 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -15,23 +15,9 @@ namespace MediaBrowser.Controller.SyncPlay public class WaitingGroupState : AbstractGroupState { /// <summary> - /// Tells the state to switch to after buffering is done. - /// </summary> - public bool ResumePlaying { get; set; } = false; - - /// <summary> - /// Whether the initial state has been set. - /// </summary> - private bool InitialStateSet { get; set; } = false; - - /// <summary> - /// The group state before the first ever event. - /// </summary> - private GroupState InitialState { get; set; } - - /// <summary> - /// Default constructor. + /// Initializes a new instance of the <see cref="WaitingGroupState"/> class. /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> public WaitingGroupState(ILogger logger) : base(logger) { @@ -39,13 +25,31 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupState GetGroupState() + public override GroupStateType Type { - return GroupState.Waiting; + get + { + return GroupStateType.Waiting; + } } + /// <summary> + /// Gets or sets a value indicating whether playback should resume when group is ready. + /// </summary> + public bool ResumePlaying { get; set; } = false; + + /// <summary> + /// Gets or sets a value indicating whether the initial state has been set. + /// </summary> + private bool InitialStateSet { get; set; } = false; + + /// <summary> + /// Gets or sets the group state before the first ever event. + /// </summary> + private GroupStateType InitialState { get; set; } + /// <inheritdoc /> - public override void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -54,7 +58,8 @@ namespace MediaBrowser.Controller.SyncPlay InitialStateSet = true; } - if (prevState.Equals(GroupState.Playing)) { + if (prevState.Equals(GroupStateType.Playing)) + { ResumePlaying = true; // Pause group and compute the media playback position. var currentTime = DateTime.UtcNow; @@ -82,7 +87,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken) + public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -98,26 +103,26 @@ namespace MediaBrowser.Controller.SyncPlay if (ResumePlaying) { // Client, that was buffering, left the group. - var playingState = new PlayingGroupState(_logger); + var playingState = new PlayingGroupState(Logger); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); - playingState.HandleRequest(context, GetGroupState(), unpauseRequest, session, cancellationToken); + playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); - _logger.LogDebug("SessionLeaving: {0} left the group {1}, notifying others to resume.", session.Id.ToString(), context.GroupId.ToString()); + Logger.LogDebug("SessionLeaving: {0} left the group {1}, notifying others to resume.", session.Id, context.GroupId.ToString()); } else { // Group is ready, returning to previous state. - var pausedState = new PausedGroupState(_logger); + var pausedState = new PausedGroupState(Logger); context.SetState(pausedState); - _logger.LogDebug("SessionLeaving: {0} left the group {1}, returning to previous state.", session.Id.ToString(), context.GroupId.ToString()); + Logger.LogDebug("SessionLeaving: {0} left the group {1}, returning to previous state.", session.Id, context.GroupId.ToString()); } } } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -131,22 +136,14 @@ namespace MediaBrowser.Controller.SyncPlay var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks); if (!setQueueStatus) { - _logger.LogError("HandleRequest: {0} in group {1}, unable to set playing queue.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogError("HandleRequest: {0} in group {1}, unable to set playing queue.", request.Type, context.GroupId.ToString()); // Ignore request and return to previous state. - ISyncPlayState newState; - switch (prevState) - { - case GroupState.Playing: - newState = new PlayingGroupState(_logger); - break; - case GroupState.Paused: - newState = new PausedGroupState(_logger); - break; - default: - newState = new IdleGroupState(_logger); - break; - } + IGroupState newState = prevState switch { + GroupStateType.Playing => new PlayingGroupState(Logger), + GroupStateType.Paused => new PausedGroupState(Logger), + _ => new IdleGroupState(Logger) + }; context.SetState(newState); return; @@ -159,11 +156,11 @@ namespace MediaBrowser.Controller.SyncPlay // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.Type, context.GroupId.ToString(), session.Id); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -187,28 +184,21 @@ namespace MediaBrowser.Controller.SyncPlay else { // Return to old state. - ISyncPlayState newState; - switch (prevState) + IGroupState newState = prevState switch { - case GroupState.Playing: - newState = new PlayingGroupState(_logger); - break; - case GroupState.Paused: - newState = new PausedGroupState(_logger); - break; - default: - newState = new IdleGroupState(_logger); - break; - } + GroupStateType.Playing => new PlayingGroupState(Logger), + GroupStateType.Paused => new PausedGroupState(Logger), + _ => new IdleGroupState(Logger) + }; context.SetState(newState); - _logger.LogDebug("HandleRequest: {0} in group {1}, unable to change current playing item.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, unable to change current playing item.", request.Type, context.GroupId.ToString()); } } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -217,7 +207,7 @@ namespace MediaBrowser.Controller.SyncPlay InitialStateSet = true; } - if (prevState.Equals(GroupState.Idle)) + if (prevState.Equals(GroupStateType.Idle)) { ResumePlaying = true; context.RestartCurrentItem(); @@ -229,22 +219,24 @@ namespace MediaBrowser.Controller.SyncPlay // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - _logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.Type, context.GroupId.ToString()); } else { if (ResumePlaying) { - _logger.LogDebug("HandleRequest: {0} in group {1}, ignoring sessions that are not ready and forcing the playback to start.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, ignoring sessions that are not ready and forcing the playback to start.", request.Type, context.GroupId.ToString()); // An Unpause request is forcing the playback to start, ignoring sessions that are not ready. context.SetAllBuffering(false); // Change state. - var playingState = new PlayingGroupState(_logger); - playingState.IgnoreBuffering = true; + var playingState = new PlayingGroupState(Logger) + { + IgnoreBuffering = true + }; context.SetState(playingState); - playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + playingState.HandleRequest(context, Type, request, session, cancellationToken); } else { @@ -258,7 +250,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -275,7 +267,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -285,13 +277,13 @@ namespace MediaBrowser.Controller.SyncPlay } // Change state. - var idleState = new IdleGroupState(_logger); + var idleState = new IdleGroupState(Logger); context.SetState(idleState); - idleState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + idleState.HandleRequest(context, Type, request, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -300,11 +292,11 @@ namespace MediaBrowser.Controller.SyncPlay InitialStateSet = true; } - if (prevState.Equals(GroupState.Playing)) + if (prevState.Equals(GroupStateType.Playing)) { ResumePlaying = true; } - else if(prevState.Equals(GroupState.Paused)) + else if (prevState.Equals(GroupStateType.Paused)) { ResumePlaying = false; } @@ -327,7 +319,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -337,9 +329,9 @@ namespace MediaBrowser.Controller.SyncPlay } // Make sure the client is playing the correct item. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var updateSession = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -349,7 +341,7 @@ namespace MediaBrowser.Controller.SyncPlay return; } - if (prevState.Equals(GroupState.Playing)) + if (prevState.Equals(GroupStateType.Playing)) { // Resume playback when all ready. ResumePlaying = true; @@ -372,7 +364,7 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.AllReady, command, cancellationToken); } - else if (prevState.Equals(GroupState.Paused)) + else if (prevState.Equals(GroupStateType.Paused)) { // Don't resume playback when all ready. ResumePlaying = false; @@ -383,7 +375,7 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Pause); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); } - else if (prevState.Equals(GroupState.Waiting)) + else if (prevState.Equals(GroupStateType.Waiting)) { // Another session is now buffering. context.SetBuffering(session, true); @@ -401,7 +393,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -411,9 +403,9 @@ namespace MediaBrowser.Controller.SyncPlay } // Make sure the client is playing the correct item. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.GetRequestType(), context.GroupId.ToString(), session.Id.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -433,8 +425,7 @@ namespace MediaBrowser.Controller.SyncPlay var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks; if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks) { - _logger.LogWarning("HandleRequest: {0} in group {1}, {2} is not time syncing properly. Ignoring elapsed time.", - request.GetRequestType(), context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {0} in group {1}, {2} is not time syncing properly. Ignoring elapsed time.", request.Type, context.GroupId.ToString(), session.Id); elapsedTime = TimeSpan.Zero; } @@ -450,8 +441,7 @@ namespace MediaBrowser.Controller.SyncPlay var delayTicks = context.PositionTicks - clientPosition.Ticks; var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks; - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} at {3} (delay of {4} seconds).", - request.GetRequestType(), context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogDebug("HandleRequest: {0} in group {1}, {2} at {3} (delay of {4} seconds).", request.Type, context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); if (ResumePlaying) { @@ -469,8 +459,7 @@ namespace MediaBrowser.Controller.SyncPlay // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - _logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", - request.GetRequestType(), context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", request.Type, context.GroupId.ToString(), session.Id); return; } @@ -485,8 +474,7 @@ namespace MediaBrowser.Controller.SyncPlay command.When = context.DateToUTCString(pauseAtTime); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - _logger.LogInformation("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready in {3} seconds.", - request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogInformation("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready in {3} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -505,8 +493,7 @@ namespace MediaBrowser.Controller.SyncPlay context.SendCommand(session, filter, command, cancellationToken); - _logger.LogInformation("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume in {3} seconds.", - request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogInformation("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume in {3} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -519,14 +506,13 @@ namespace MediaBrowser.Controller.SyncPlay var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - _logger.LogWarning("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time. {3} seconds to recover.", - request.GetRequestType(), context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogWarning("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time. {3} seconds to recover.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } // Change state. - var playingState = new PlayingGroupState(_logger); + var playingState = new PlayingGroupState(Logger); context.SetState(playingState); - playingState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + playingState.HandleRequest(context, Type, request, session, cancellationToken); } } else @@ -543,10 +529,11 @@ namespace MediaBrowser.Controller.SyncPlay // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - _logger.LogWarning("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", - request.GetRequestType(), context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", request.Type, context.GroupId.ToString(), session.Id); return; - } else { + } + else + { // Session is ready. context.SetBuffering(session, false); } @@ -554,28 +541,27 @@ namespace MediaBrowser.Controller.SyncPlay if (!context.IsBuffering()) { // Group is ready, returning to previous state. - var pausedState = new PausedGroupState(_logger); + var pausedState = new PausedGroupState(Logger); context.SetState(pausedState); - if (InitialState.Equals(GroupState.Playing)) + if (InitialState.Equals(GroupStateType.Playing)) { // Group went from playing to waiting state and a pause request occured while waiting. var pauserequest = new PauseGroupRequest(); - pausedState.HandleRequest(context, GetGroupState(), pauserequest, session, cancellationToken); + pausedState.HandleRequest(context, Type, pauserequest, session, cancellationToken); } - else if (InitialState.Equals(GroupState.Paused)) + else if (InitialState.Equals(GroupStateType.Paused)) { - pausedState.HandleRequest(context, GetGroupState(), request, session, cancellationToken); + pausedState.HandleRequest(context, Type, request, session, cancellationToken); } - _logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", - request.GetRequestType(), context.GroupId.ToString(), session.Id); + Logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", request.Type, context.GroupId.ToString(), session.Id); } } } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -587,9 +573,9 @@ namespace MediaBrowser.Controller.SyncPlay ResumePlaying = true; // Make sure the client knows the playing item, to avoid duplicate requests. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.Type, context.GroupId.ToString()); return; } @@ -607,28 +593,21 @@ namespace MediaBrowser.Controller.SyncPlay else { // Return to old state. - ISyncPlayState newState; - switch (prevState) + IGroupState newState = prevState switch { - case GroupState.Playing: - newState = new PlayingGroupState(_logger); - break; - case GroupState.Paused: - newState = new PausedGroupState(_logger); - break; - default: - newState = new IdleGroupState(_logger); - break; - } + GroupStateType.Playing => new PlayingGroupState(Logger), + GroupStateType.Paused => new PausedGroupState(Logger), + _ => new IdleGroupState(Logger) + }; context.SetState(newState); - _logger.LogDebug("HandleRequest: {0} in group {1}, no next track available.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, no next track available.", request.Type, context.GroupId.ToString()); } } /// <inheritdoc /> - public override void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -640,9 +619,9 @@ namespace MediaBrowser.Controller.SyncPlay ResumePlaying = true; // Make sure the client knows the playing item, to avoid duplicate requests. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.Type, context.GroupId.ToString()); return; } @@ -660,23 +639,16 @@ namespace MediaBrowser.Controller.SyncPlay else { // Return to old state. - ISyncPlayState newState; - switch (prevState) + IGroupState newState = prevState switch { - case GroupState.Playing: - newState = new PlayingGroupState(_logger); - break; - case GroupState.Paused: - newState = new PausedGroupState(_logger); - break; - default: - newState = new IdleGroupState(_logger); - break; - } + GroupStateType.Playing => new PlayingGroupState(Logger), + GroupStateType.Paused => new PausedGroupState(Logger), + _ => new IdleGroupState(Logger) + }; context.SetState(newState); - _logger.LogDebug("HandleRequest: {0} in group {1}, no previous track available.", request.GetRequestType(), context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {0} in group {1}, no previous track available.", request.Type, context.GroupId.ToString()); } } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs b/MediaBrowser.Controller/SyncPlay/IGroupController.cs similarity index 94% rename from MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs rename to MediaBrowser.Controller/SyncPlay/IGroupController.cs index 2f497ebbb9..038233fdd3 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayController.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupController.cs @@ -7,9 +7,9 @@ using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> - /// Interface ISyncPlayGroupController. + /// Interface IGroupController. /// </summary> - public interface ISyncPlayGroupController + public interface IGroupController { /// <summary> /// Gets the group identifier. @@ -26,7 +26,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <summary> /// Checks if the group is empty. /// </summary> - /// <returns><c>true</c> if the group is empty, <c>false</c> otherwise</returns> + /// <returns><c>true</c> if the group is empty, <c>false</c> otherwise.</returns> bool IsGroupEmpty(); /// <summary> @@ -66,7 +66,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The requested action.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken); + void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken); /// <summary> /// Gets the info about the group for the clients. @@ -80,6 +80,5 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="user">The user.</param> /// <returns><c>true</c> if the user can access the play queue; <c>false</c> otherwise.</returns> bool HasAccessToPlayQueue(User user); - } } diff --git a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs new file mode 100644 index 0000000000..3b195e98ca --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs @@ -0,0 +1,27 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Interface IGroupPlaybackRequest. + /// </summary> + public interface IGroupPlaybackRequest + { + /// <summary> + /// Gets the playback request type. + /// </summary> + /// <returns>The playback request type.</returns> + PlaybackRequestType Type { get; } + + /// <summary> + /// Applies the request to a group. + /// </summary> + /// <param name="context">The context of the state.</param> + /// <param name="state">The current state.</param> + /// <param name="session">The session.</param> + /// <param name="cancellationToken">The cancellation token.</param> + void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs similarity index 75% rename from MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs rename to MediaBrowser.Controller/SyncPlay/IGroupState.cs index 218e871e36..981b65221b 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -1,19 +1,19 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> - /// Interface ISyncPlayState. + /// Interface IGroupState. /// </summary> - public interface ISyncPlayState + public interface IGroupState { /// <summary> - /// Gets the group state. + /// Gets the group state type. /// </summary> - /// <value>The group state.</value> - GroupState GetGroupState(); + /// <value>The group state type.</value> + GroupStateType Type { get; } /// <summary> /// Handles a session that joined the group. @@ -22,7 +22,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="prevState">The previous state.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionJoined(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a session that is leaving the group. @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="prevState">The previous state.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionLeaving(ISyncPlayStateContext context, GroupState prevState, SessionInfo session, CancellationToken cancellationToken); + void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Generic handle. Context's state can change. @@ -41,7 +41,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The generic action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IPlaybackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, IGroupPlaybackRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a play action requested by a session. Context's state can change. @@ -51,7 +51,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The play action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a playlist-item change requested by a session. Context's state can change. @@ -61,7 +61,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The playlist-item change action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a remove-items change requested by a session. Context's state can change. @@ -71,7 +71,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The remove-items change action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a move-item change requested by a session. Context's state should not change. @@ -81,7 +81,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The move-item change action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a queue change requested by a session. Context's state should not change. @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The queue action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles an unpause action requested by a session. Context's state can change. @@ -101,7 +101,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The unpause action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a pause action requested by a session. Context's state can change. @@ -111,7 +111,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The pause action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a stop action requested by a session. Context's state can change. @@ -121,7 +121,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The stop action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a seek action requested by a session. Context's state can change. @@ -131,7 +131,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The seek action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a buffering action requested by a session. Context's state can change. @@ -141,7 +141,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The buffering action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a buffering-done action requested by a session. Context's state can change. @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The buffering-done action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a next-track action requested by a session. Context's state can change. @@ -161,7 +161,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The next-track action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a previous-track action requested by a session. Context's state can change. @@ -171,7 +171,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The previous-track action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a repeat-mode change requested by a session. Context's state should not change. @@ -181,7 +181,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The repeat-mode action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a shuffle-mode change requested by a session. Context's state should not change. @@ -191,7 +191,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The shuffle-mode action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Updates ping of a session. Context's state should not change. @@ -201,7 +201,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The buffering-done action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Updates whether the session should be considered during group wait. Context's state should not change. @@ -211,6 +211,6 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The ignore-wait action.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(ISyncPlayStateContext context, GroupState prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs similarity index 93% rename from MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs rename to MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs index 4aac2a8818..2ddaae6400 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs @@ -1,15 +1,16 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> - /// Interface ISyncPlayStateContext. + /// Interface IGroupStateContext. /// </summary> - public interface ISyncPlayStateContext + public interface IGroupStateContext { /// <summary> /// Gets the default ping value used for sessions, in milliseconds. @@ -57,11 +58,12 @@ namespace MediaBrowser.Controller.SyncPlay /// Sets a new state. /// </summary> /// <param name="state">The new state.</param> - void SetState(ISyncPlayState state); + void SetState(IGroupState state); /// <summary> /// Sends a GroupUpdate message to the interested sessions. /// </summary> + /// <typeparam name="T">The type of the data of the message.</typeparam> /// <param name="from">The current session.</param> /// <param name="type">The filtering type.</param> /// <param name="message">The message to send.</param> @@ -89,6 +91,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <summary> /// Builds a new group update message. /// </summary> + /// <typeparam name="T">The type of the data of the message.</typeparam> /// <param name="type">The update type.</param> /// <param name="data">The data to send.</param> /// <returns>The group update.</returns> @@ -154,7 +157,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="playingItemPosition">The playing item position in the play queue.</param> /// <param name="startPositionTicks">The start position ticks.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool SetPlayQueue(Guid[] playQueue, int playingItemPosition, long startPositionTicks); + bool SetPlayQueue(IEnumerable<Guid> playQueue, int playingItemPosition, long startPositionTicks); /// <summary> /// Sets the playing item. @@ -168,7 +171,7 @@ namespace MediaBrowser.Controller.SyncPlay /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - bool RemoveFromPlayQueue(string[] playlistItemIds); + bool RemoveFromPlayQueue(IEnumerable<string> playlistItemIds); /// <summary> /// Moves an item in the play queue. @@ -184,7 +187,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="newItems">The new items to add to the play queue.</param> /// <param name="mode">The mode with which the items will be added.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool AddToPlayQueue(Guid[] newItems, string mode); + bool AddToPlayQueue(IEnumerable<Guid> newItems, string mode); /// <summary> /// Restarts current item in play queue. diff --git a/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs deleted file mode 100644 index 35ca64c8df..0000000000 --- a/MediaBrowser.Controller/SyncPlay/IPlaybackGroupRequest.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Interface IPlaybackGroupRequest. - /// </summary> - public interface IPlaybackGroupRequest - { - /// <summary> - /// Gets the playback request type. - /// </summary> - /// <returns>The playback request type.</returns> - PlaybackRequestType GetRequestType(); - - /// <summary> - /// Applies the request to a group. - /// </summary> - void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken); - } -} diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index ec13686c64..65146d4ae8 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(SessionInfo session, IPlaybackGroupRequest request, CancellationToken cancellationToken); + void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken); /// <summary> /// Maps a session to a group. @@ -56,7 +56,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> - void AddSessionToGroup(SessionInfo session, ISyncPlayGroupController group); + void AddSessionToGroup(SessionInfo session, IGroupController group); /// <summary> /// Unmaps a session from a group. @@ -64,6 +64,6 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> - void RemoveSessionFromGroup(SessionInfo session, ISyncPlayGroupController group); + void RemoveSessionFromGroup(SessionInfo session, IGroupController group); } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs deleted file mode 100644 index 5466cbe2f7..0000000000 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/IgnoreWaitGroupRequest.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class IgnoreWaitGroupRequest. - /// </summary> - public class IgnoreWaitGroupRequest : IPlaybackGroupRequest - { - /// <summary> - /// Gets or sets the client group-wait status. - /// </summary> - /// <value>The client group-wait status.</value> - public bool IgnoreWait { get; set; } - - /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.IgnoreWait; - } - - /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) - { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs deleted file mode 100644 index facb25155c..0000000000 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PauseGroupRequest.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class PauseGroupRequest. - /// </summary> - public class PauseGroupRequest : IPlaybackGroupRequest - { - /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Pause; - } - - /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) - { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs deleted file mode 100644 index 78aeb9c6f0..0000000000 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/RemoveFromPlaylistGroupRequest.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class RemoveFromPlaylistGroupRequest. - /// </summary> - public class RemoveFromPlaylistGroupRequest : IPlaybackGroupRequest - { - /// <summary> - /// Gets or sets the playlist identifiers ot the items. - /// </summary> - /// <value>The playlist identifiers ot the items.</value> - public string[] PlaylistItemIds { get; set; } - - /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.RemoveFromPlaylist; - } - - /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) - { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs deleted file mode 100644 index f1581c98d9..0000000000 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/StopGroupRequest.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class StopGroupRequest. - /// </summary> - public class StopGroupRequest : IPlaybackGroupRequest - { - /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Stop; - } - - /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) - { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs deleted file mode 100644 index 1072952081..0000000000 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/UnpauseGroupRequest.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Threading; -using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Controller.Session; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Class UnpauseGroupRequest. - /// </summary> - public class UnpauseGroupRequest : IPlaybackGroupRequest - { - /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Unpause; - } - - /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) - { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); - } - } -} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs similarity index 69% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index 65fced43f1..b5bed89f21 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -1,14 +1,14 @@ using System; using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class BufferGroupRequest. /// </summary> - public class BufferGroupRequest : IPlaybackGroupRequest + public class BufferGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets when the request has been made by the client. @@ -23,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// <summary> - /// Gets or sets the client playback status. + /// Gets or sets a value indicating whether the client playback is unpaused. /// </summary> /// <value>The client playback status.</value> public bool IsPlaying { get; set; } @@ -35,15 +35,12 @@ namespace MediaBrowser.Controller.SyncPlay public string PlaylistItemId { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Buffer; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Buffer; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs new file mode 100644 index 0000000000..325839f107 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs @@ -0,0 +1,27 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class IgnoreWaitGroupRequest. + /// </summary> + public class IgnoreWaitGroupRequest : IGroupPlaybackRequest + { + /// <summary> + /// Gets or sets a value indicating whether the client should be ignored. + /// </summary> + /// <value>The client group-wait status.</value> + public bool IgnoreWait { get; set; } + + /// <inheritdoc /> + public PlaybackRequestType Type { get; } = PlaybackRequestType.IgnoreWait; + + /// <inheritdoc /> + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.Type, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs similarity index 62% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index 38170facf0..3c95f53d4a 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class MovePlaylistItemGroupRequest. /// </summary> - public class MovePlaylistItemGroupRequest : IPlaybackGroupRequest + public class MovePlaylistItemGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the playlist identifier of the item. @@ -22,15 +22,12 @@ namespace MediaBrowser.Controller.SyncPlay public int NewIndex { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.MovePlaylistItem; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.MovePlaylistItem; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs similarity index 54% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs index b27c10f169..8636d6f4d5 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/NextTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class NextTrackGroupRequest. /// </summary> - public class NextTrackGroupRequest : IPlaybackGroupRequest + public class NextTrackGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the playing item identifier. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public string PlaylistItemId { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.NextTrack; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.NextTrack; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs new file mode 100644 index 0000000000..45bd3b15f1 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs @@ -0,0 +1,21 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class PauseGroupRequest. + /// </summary> + public class PauseGroupRequest : IGroupPlaybackRequest + { + /// <inheritdoc /> + public PlaybackRequestType Type { get; } = PlaybackRequestType.Pause; + + /// <inheritdoc /> + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.Type, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs similarity index 53% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs index 5605578d75..9dacb79857 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class PingGroupRequest. /// </summary> - public class PingGroupRequest : IPlaybackGroupRequest + public class PingGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the ping time. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public long Ping { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Ping; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Ping; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs similarity index 61% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index f3dd769e46..e090a882e2 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -1,20 +1,21 @@ using System; +using System.Collections.Generic; using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class PlayGroupRequest. /// </summary> - public class PlayGroupRequest : IPlaybackGroupRequest + public class PlayGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the playing queue. + /// Gets the playing queue. /// </summary> /// <value>The playing queue.</value> - public Guid[] PlayingQueue { get; set; } + public List<Guid> PlayingQueue { get; } = new List<Guid>(); /// <summary> /// Gets or sets the playing item from the queue. @@ -29,15 +30,12 @@ namespace MediaBrowser.Controller.SyncPlay public long StartPositionTicks { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Play; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Play; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs similarity index 55% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs index 31b93b9675..aca5d678e0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/PreviousTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class PreviousTrackGroupRequest. /// </summary> - public class PreviousTrackGroupRequest : IPlaybackGroupRequest + public class PreviousTrackGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the playing item identifier. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public string PlaylistItemId { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.PreviousTrack; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.PreviousTrack; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs similarity index 54% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index 01c08cc860..82380b2098 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -1,20 +1,21 @@ using System; +using System.Collections.Generic; using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class QueueGroupRequest. /// </summary> - public class QueueGroupRequest : IPlaybackGroupRequest + public class QueueGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the items to queue. + /// Gets the items to queue. /// </summary> /// <value>The items to queue.</value> - public Guid[] ItemIds { get; set; } + public List<Guid> ItemIds { get; } = new List<Guid>(); /// <summary> /// Gets or sets the mode in which to add the new items. @@ -23,15 +24,12 @@ namespace MediaBrowser.Controller.SyncPlay public string Mode { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Queue; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Queue; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs similarity index 70% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index 8f266ed32e..c8a2268cfb 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -1,14 +1,14 @@ using System; using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class ReadyGroupRequest. /// </summary> - public class ReadyGroupRequest : IPlaybackGroupRequest + public class ReadyGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets when the request has been made by the client. @@ -23,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// <summary> - /// Gets or sets the client playback status. + /// Gets or sets a value indicating whether the client playback is unpaused. /// </summary> /// <value>The client playback status.</value> public bool IsPlaying { get; set; } @@ -35,15 +35,12 @@ namespace MediaBrowser.Controller.SyncPlay public string PlaylistItemId { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Ready; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Ready; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs new file mode 100644 index 0000000000..4ead1301b6 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class RemoveFromPlaylistGroupRequest. + /// </summary> + public class RemoveFromPlaylistGroupRequest : IGroupPlaybackRequest + { + /// <summary> + /// Gets the playlist identifiers ot the items. + /// </summary> + /// <value>The playlist identifiers ot the items.</value> + public List<string> PlaylistItemIds { get; } = new List<string>(); + + /// <inheritdoc /> + public PlaybackRequestType Type { get; } = PlaybackRequestType.RemoveFromPlaylist; + + /// <inheritdoc /> + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.Type, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs similarity index 54% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs index 24d9be5073..d311bffdc4 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class SeekGroupRequest. /// </summary> - public class SeekGroupRequest : IPlaybackGroupRequest + public class SeekGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the position ticks. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public long PositionTicks { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.Seek; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.Seek; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs similarity index 56% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index 070fd71d25..0983d91292 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetCurrentItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class SetPlaylistItemGroupRequest. /// </summary> - public class SetPlaylistItemGroupRequest : IPlaybackGroupRequest + public class SetPlaylistItemGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the playlist identifier of the playing item. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public string PlaylistItemId { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.SetPlaylistItem; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.SetPlaylistItem; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs similarity index 53% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs index 5f36f60e45..79373ef5f5 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetRepeatModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class SetRepeatModeGroupRequest. /// </summary> - public class SetRepeatModeGroupRequest : IPlaybackGroupRequest + public class SetRepeatModeGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the repeat mode. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public string Mode { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.SetRepeatMode; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.SetRepeatMode; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs similarity index 53% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs index 472455fd3b..316fb49f40 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequest/SetShuffleModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs @@ -1,13 +1,13 @@ using System.Threading; -using MediaBrowser.Model.SyncPlay; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { /// <summary> /// Class SetShuffleModeGroupRequest. /// </summary> - public class SetShuffleModeGroupRequest : IPlaybackGroupRequest + public class SetShuffleModeGroupRequest : IGroupPlaybackRequest { /// <summary> /// Gets or sets the shuffle mode. @@ -16,15 +16,12 @@ namespace MediaBrowser.Controller.SyncPlay public string Mode { get; set; } /// <inheritdoc /> - public PlaybackRequestType GetRequestType() - { - return PlaybackRequestType.SetShuffleMode; - } + public PlaybackRequestType Type { get; } = PlaybackRequestType.SetShuffleMode; /// <inheritdoc /> - public void Apply(ISyncPlayStateContext context, ISyncPlayState state, SessionInfo session, CancellationToken cancellationToken) + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.GetGroupState(), this, session, cancellationToken); + state.HandleRequest(context, state.Type, this, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs new file mode 100644 index 0000000000..9f6f8ea63c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs @@ -0,0 +1,21 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class StopGroupRequest. + /// </summary> + public class StopGroupRequest : IGroupPlaybackRequest + { + /// <inheritdoc /> + public PlaybackRequestType Type { get; } = PlaybackRequestType.Stop; + + /// <inheritdoc /> + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.Type, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs new file mode 100644 index 0000000000..84a6b0a6e7 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs @@ -0,0 +1,21 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Class UnpauseGroupRequest. + /// </summary> + public class UnpauseGroupRequest : IGroupPlaybackRequest + { + /// <inheritdoc /> + public PlaybackRequestType Type { get; } = PlaybackRequestType.Unpause; + + /// <inheritdoc /> + public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + { + state.HandleRequest(context, state.Type, this, session, cancellationToken); + } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 030005abe6..8bc21a6a80 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -5,76 +5,23 @@ using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay { - static class ListShuffleExtension - { - private static Random rng = new Random(); - public static void Shuffle<T>(this IList<T> list) - { - int n = list.Count; - while (n > 1) - { - n--; - int k = rng.Next(n + 1); - T value = list[k]; - list[k] = list[n]; - list[n] = value; - } - } - } - /// <summary> /// Class PlayQueueManager. /// </summary> public class PlayQueueManager { - /// <summary> - /// Gets or sets the playing item index. - /// </summary> - /// <value>The playing item index.</value> - public int PlayingItemIndex { get; private set; } - - /// <summary> - /// Gets or sets the last time the queue has been changed. - /// </summary> - /// <value>The last time the queue has been changed.</value> - public DateTime LastChange { get; private set; } - - /// <summary> - /// Gets the sorted playlist. - /// </summary> - /// <value>The sorted playlist, or play queue of the group.</value> - private List<QueueItem> SortedPlaylist { get; set; } = new List<QueueItem>(); - - /// <summary> - /// Gets the shuffled playlist. - /// </summary> - /// <value>The shuffled playlist, or play queue of the group.</value> - private List<QueueItem> ShuffledPlaylist { get; set; } = new List<QueueItem>(); - - /// <summary> - /// Gets or sets the shuffle mode. - /// </summary> - /// <value>The shuffle mode.</value> - public GroupShuffleMode ShuffleMode { get; private set; } = GroupShuffleMode.Sorted; - - /// <summary> - /// Gets or sets the repeat mode. - /// </summary> - /// <value>The repeat mode.</value> - public GroupRepeatMode RepeatMode { get; private set; } = GroupRepeatMode.RepeatNone; - - /// <summary> - /// Gets or sets the progressive identifier counter. - /// </summary> - /// <value>The progressive identifier.</value> - private int ProgressiveId { get; set; } = 0; - /// <summary> /// Placeholder index for when no item is playing. /// </summary> /// <value>The no-playing item index.</value> private const int NoPlayingItemIndex = -1; + /// <summary> + /// Random number generator used to shuffle lists. + /// </summary> + /// <value>The random number generator.</value> + private readonly Random randomNumberGenerator = new Random(); + /// <summary> /// Initializes a new instance of the <see cref="PlayQueueManager" /> class. /// </summary> @@ -84,84 +31,70 @@ namespace MediaBrowser.Controller.SyncPlay } /// <summary> - /// Gets the next available identifier. + /// Gets the playing item index. /// </summary> - /// <returns>The next available identifier.</returns> - private int GetNextProgressiveId() { - return ProgressiveId++; - } + /// <value>The playing item index.</value> + public int PlayingItemIndex { get; private set; } /// <summary> - /// Creates a list from the array of items. Each item is given an unique playlist identifier. + /// Gets the last time the queue has been changed. /// </summary> - /// <returns>The list of queue items.</returns> - private List<QueueItem> CreateQueueItemsFromArray(Guid[] items) + /// <value>The last time the queue has been changed.</value> + public DateTime LastChange { get; private set; } + + /// <summary> + /// Gets the shuffle mode. + /// </summary> + /// <value>The shuffle mode.</value> + public GroupShuffleMode ShuffleMode { get; private set; } = GroupShuffleMode.Sorted; + + /// <summary> + /// Gets the repeat mode. + /// </summary> + /// <value>The repeat mode.</value> + public GroupRepeatMode RepeatMode { get; private set; } = GroupRepeatMode.RepeatNone; + + /// <summary> + /// Gets or sets the sorted playlist. + /// </summary> + /// <value>The sorted playlist, or play queue of the group.</value> + private List<QueueItem> SortedPlaylist { get; set; } = new List<QueueItem>(); + + /// <summary> + /// Gets or sets the shuffled playlist. + /// </summary> + /// <value>The shuffled playlist, or play queue of the group.</value> + private List<QueueItem> ShuffledPlaylist { get; set; } = new List<QueueItem>(); + + /// <summary> + /// Gets or sets the progressive identifier counter. + /// </summary> + /// <value>The progressive identifier.</value> + private int ProgressiveId { get; set; } + + /// <summary> + /// Checks if an item is playing. + /// </summary> + /// <returns><c>true</c> if an item is playing; <c>false</c> otherwise.</returns> + public bool IsItemPlaying() { - return items.ToList() - .Select(item => new QueueItem() - { - ItemId = item, - PlaylistItemId = "syncPlayItem" + GetNextProgressiveId() - }) - .ToList(); + return PlayingItemIndex != NoPlayingItemIndex; } /// <summary> - /// Gets the current playlist, depending on the shuffle mode. + /// Gets the current playlist considering the shuffle mode. /// </summary> /// <returns>The playlist.</returns> - private List<QueueItem> GetPlaylistAsList() + public IReadOnlyList<QueueItem> GetPlaylist() { - if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) - { - return ShuffledPlaylist; - } - else - { - return SortedPlaylist; - } - } - - /// <summary> - /// Gets the current playing item, depending on the shuffle mode. - /// </summary> - /// <returns>The playing item.</returns> - private QueueItem GetPlayingItem() - { - if (PlayingItemIndex == NoPlayingItemIndex) - { - return null; - } - else if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) - { - return ShuffledPlaylist[PlayingItemIndex]; - } - else - { - return SortedPlaylist[PlayingItemIndex]; - } - } - - /// <summary> - /// Gets the current playlist as an array, depending on the shuffle mode. - /// </summary> - /// <returns>The array of items in the playlist.</returns> - public QueueItem[] GetPlaylist() { - if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) - { - return ShuffledPlaylist.ToArray(); - } - else - { - return SortedPlaylist.ToArray(); - } + return GetPlaylistInternal(); } /// <summary> /// Sets a new playlist. Playing item is reset. /// </summary> /// <param name="items">The new items of the playlist.</param> - public void SetPlaylist(Guid[] items) + public void SetPlaylist(IEnumerable<Guid> items) { SortedPlaylist.Clear(); ShuffledPlaylist.Clear(); @@ -170,7 +103,7 @@ namespace MediaBrowser.Controller.SyncPlay if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { ShuffledPlaylist = SortedPlaylist.ToList(); - ShuffledPlaylist.Shuffle(); + Shuffle(ShuffledPlaylist); } PlayingItemIndex = NoPlayingItemIndex; @@ -181,7 +114,7 @@ namespace MediaBrowser.Controller.SyncPlay /// Appends new items to the playlist. The specified order is mantained. /// </summary> /// <param name="items">The items to add to the playlist.</param> - public void Queue(Guid[] items) + public void Queue(IEnumerable<Guid> items) { var newItems = CreateQueueItemsFromArray(items); @@ -195,13 +128,14 @@ namespace MediaBrowser.Controller.SyncPlay } /// <summary> - /// Shuffles the playlist. Shuffle mode is changed. + /// Shuffles the playlist. Shuffle mode is changed. The playlist gets re-shuffled if already shuffled. /// </summary> public void ShufflePlaylist() { - if (PlayingItemIndex == NoPlayingItemIndex) { + if (PlayingItemIndex == NoPlayingItemIndex) + { ShuffledPlaylist = SortedPlaylist.ToList(); - ShuffledPlaylist.Shuffle(); + Shuffle(ShuffledPlaylist); } else if (ShuffleMode.Equals(GroupShuffleMode.Sorted)) { @@ -209,7 +143,7 @@ namespace MediaBrowser.Controller.SyncPlay var playingItem = SortedPlaylist[PlayingItemIndex]; ShuffledPlaylist = SortedPlaylist.ToList(); ShuffledPlaylist.RemoveAt(PlayingItemIndex); - ShuffledPlaylist.Shuffle(); + Shuffle(ShuffledPlaylist); ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); PlayingItemIndex = 0; } @@ -218,7 +152,7 @@ namespace MediaBrowser.Controller.SyncPlay // Re-shuffle playlist. var playingItem = ShuffledPlaylist[PlayingItemIndex]; ShuffledPlaylist.RemoveAt(PlayingItemIndex); - ShuffledPlaylist.Shuffle(); + Shuffle(ShuffledPlaylist); ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); PlayingItemIndex = 0; } @@ -262,6 +196,7 @@ namespace MediaBrowser.Controller.SyncPlay { ShuffledPlaylist.Add(playingItem); } + PlayingItemIndex = 0; } else @@ -274,7 +209,7 @@ namespace MediaBrowser.Controller.SyncPlay /// Adds new items to the playlist right after the playing item. The specified order is mantained. /// </summary> /// <param name="items">The items to add to the playlist.</param> - public void QueueNext(Guid[] items) + public void QueueNext(IEnumerable<Guid> items) { var newItems = CreateQueueItemsFromArray(items); @@ -334,8 +269,18 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="itemId">The new playing item identifier.</param> public void SetPlayingItemById(Guid itemId) { - var itemIds = GetPlaylistAsList().Select(queueItem => queueItem.ItemId).ToList(); - PlayingItemIndex = itemIds.IndexOf(itemId); + PlayingItemIndex = NoPlayingItemIndex; + + var playlist = GetPlaylistInternal(); + foreach (var item in playlist) + { + if (item.ItemId.Equals(itemId)) + { + PlayingItemIndex = playlist.IndexOf(item); + break; + } + } + LastChange = DateTime.UtcNow; } @@ -346,8 +291,18 @@ namespace MediaBrowser.Controller.SyncPlay /// <returns><c>true</c> if playing item has been set; <c>false</c> if item is not in the playlist.</returns> public bool SetPlayingItemByPlaylistId(string playlistItemId) { - var playlistIds = GetPlaylistAsList().Select(queueItem => queueItem.PlaylistItemId).ToList(); - PlayingItemIndex = playlistIds.IndexOf(playlistItemId); + PlayingItemIndex = NoPlayingItemIndex; + + var playlist = GetPlaylistInternal(); + foreach (var item in playlist) + { + if (item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)) + { + PlayingItemIndex = playlist.IndexOf(item); + break; + } + } + LastChange = DateTime.UtcNow; return PlayingItemIndex != NoPlayingItemIndex; } @@ -358,8 +313,8 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="playlistIndex">The new playing item index.</param> public void SetPlayingItemByIndex(int playlistIndex) { - var list = GetPlaylistAsList(); - if (playlistIndex < 0 || playlistIndex > list.Count()) + var playlist = GetPlaylistInternal(); + if (playlistIndex < 0 || playlistIndex > playlist.Count) { PlayingItemIndex = NoPlayingItemIndex; } @@ -376,7 +331,7 @@ namespace MediaBrowser.Controller.SyncPlay /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - public bool RemoveFromPlaylist(string[] playlistItemIds) + public bool RemoveFromPlaylist(IEnumerable<string> playlistItemIds) { var playingItem = GetPlayingItem(); var playlistItemIdsList = playlistItemIds.ToList(); @@ -396,7 +351,7 @@ namespace MediaBrowser.Controller.SyncPlay { // Was first element, picking next if available. // Default to no playing item otherwise. - PlayingItemIndex = SortedPlaylist.Count() > 0 ? 0 : NoPlayingItemIndex; + PlayingItemIndex = SortedPlaylist.Count > 0 ? 0 : NoPlayingItemIndex; } return true; @@ -422,24 +377,32 @@ namespace MediaBrowser.Controller.SyncPlay /// <returns><c>true</c> if the item has been moved; <c>false</c> otherwise.</returns> public bool MovePlaylistItem(string playlistItemId, int newIndex) { - var list = GetPlaylistAsList(); + var playlist = GetPlaylistInternal(); var playingItem = GetPlayingItem(); - var playlistIds = list.Select(queueItem => queueItem.PlaylistItemId).ToList(); - var oldIndex = playlistIds.IndexOf(playlistItemId); + var oldIndex = -1; + foreach (var item in playlist) + { + if (item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)) + { + oldIndex = playlist.IndexOf(item); + break; + } + } + if (oldIndex < 0) { return false; } - var queueItem = list[oldIndex]; - list.RemoveAt(oldIndex); - newIndex = Math.Min(newIndex, list.Count()); + var queueItem = playlist[oldIndex]; + playlist.RemoveAt(oldIndex); + newIndex = Math.Min(newIndex, playlist.Count); newIndex = Math.Max(newIndex, 0); - list.Insert(newIndex, queueItem); + playlist.Insert(newIndex, queueItem); LastChange = DateTime.UtcNow; - PlayingItemIndex = list.IndexOf(playingItem); + PlayingItemIndex = playlist.IndexOf(playingItem); return true; } @@ -505,7 +468,7 @@ namespace MediaBrowser.Controller.SyncPlay public QueueItem GetNextItemPlaylistId() { int newIndex; - var playlist = GetPlaylistAsList(); + var playlist = GetPlaylistInternal(); switch (RepeatMode) { @@ -514,17 +477,18 @@ namespace MediaBrowser.Controller.SyncPlay break; case GroupRepeatMode.RepeatAll: newIndex = PlayingItemIndex + 1; - if (newIndex >= playlist.Count()) + if (newIndex >= playlist.Count) { newIndex = 0; } + break; default: newIndex = PlayingItemIndex + 1; break; } - if (newIndex < 0 || newIndex >= playlist.Count()) + if (newIndex < 0 || newIndex >= playlist.Count) { return null; } @@ -545,7 +509,7 @@ namespace MediaBrowser.Controller.SyncPlay } PlayingItemIndex++; - if (PlayingItemIndex >= SortedPlaylist.Count()) + if (PlayingItemIndex >= SortedPlaylist.Count) { if (RepeatMode.Equals(GroupRepeatMode.RepeatAll)) { @@ -579,7 +543,7 @@ namespace MediaBrowser.Controller.SyncPlay { if (RepeatMode.Equals(GroupRepeatMode.RepeatAll)) { - PlayingItemIndex = SortedPlaylist.Count() - 1; + PlayingItemIndex = SortedPlaylist.Count - 1; } else { @@ -591,5 +555,86 @@ namespace MediaBrowser.Controller.SyncPlay LastChange = DateTime.UtcNow; return true; } + + /// <summary> + /// Shuffles a given list. + /// </summary> + /// <param name="list">The list to shuffle.</param> + private void Shuffle<T>(IList<T> list) + { + int n = list.Count; + while (n > 1) + { + n--; + int k = randomNumberGenerator.Next(n + 1); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } + + /// <summary> + /// Gets the next available identifier. + /// </summary> + /// <returns>The next available identifier.</returns> + private int GetNextProgressiveId() + { + return ProgressiveId++; + } + + /// <summary> + /// Creates a list from the array of items. Each item is given an unique playlist identifier. + /// </summary> + /// <returns>The list of queue items.</returns> + private List<QueueItem> CreateQueueItemsFromArray(IEnumerable<Guid> items) + { + var list = new List<QueueItem>(); + foreach (var item in items) + { + list.Add(new QueueItem() + { + ItemId = item, + PlaylistItemId = "syncPlayItem" + GetNextProgressiveId() + }); + } + + return list; + } + + /// <summary> + /// Gets the current playlist considering the shuffle mode. + /// </summary> + /// <returns>The playlist.</returns> + private List<QueueItem> GetPlaylistInternal() + { + if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + return ShuffledPlaylist; + } + else + { + return SortedPlaylist; + } + } + + /// <summary> + /// Gets the current playing item, depending on the shuffle mode. + /// </summary> + /// <returns>The playing item.</returns> + private QueueItem GetPlayingItem() + { + if (PlayingItemIndex == NoPlayingItemIndex) + { + return null; + } + else if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) + { + return ShuffledPlaylist[PlayingItemIndex]; + } + else + { + return SortedPlaylist[PlayingItemIndex]; + } + } } } diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs index 255f6812bd..85b9a35229 100644 --- a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs +++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the group state. /// </summary> /// <value>The group state.</value> - public GroupState State { get; set; } + public GroupStateType State { get; set; } /// <summary> /// Gets or sets the participants. diff --git a/MediaBrowser.Model/SyncPlay/GroupState.cs b/MediaBrowser.Model/SyncPlay/GroupStateType.cs similarity index 95% rename from MediaBrowser.Model/SyncPlay/GroupState.cs rename to MediaBrowser.Model/SyncPlay/GroupStateType.cs index 871634d558..341859b306 100644 --- a/MediaBrowser.Model/SyncPlay/GroupState.cs +++ b/MediaBrowser.Model/SyncPlay/GroupStateType.cs @@ -3,20 +3,23 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Enum GroupState. /// </summary> - public enum GroupState + public enum GroupStateType { /// <summary> /// The group is in idle state. No media is playing. /// </summary> Idle, + /// <summary> /// The group is in wating state. Playback is paused. Will start playing when users are ready. /// </summary> Waiting, + /// <summary> /// The group is in paused state. Playback is paused. Will resume on play command. /// </summary> Paused, + /// <summary> /// The group is in playing state. Playback is advancing. /// </summary> diff --git a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs index 7c7b267e6f..532b5a56f4 100644 --- a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs @@ -1,5 +1,3 @@ -#nullable disable - namespace MediaBrowser.Model.SyncPlay { /// <summary> @@ -11,7 +9,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the state of the group. /// </summary> /// <value>The state of the group.</value> - public GroupState State { get; set; } + public GroupStateType State { get; set; } /// <summary> /// Gets or sets the reason of the state change. diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs index 8c7208211c..12d6058ac3 100644 --- a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs @@ -5,6 +5,7 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Class GroupUpdate. /// </summary> + /// <typeparam name="T">The type of the data of the message.</typeparam> public class GroupUpdate<T> { /// <summary> diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs index 5e2740a892..575597e62d 100644 --- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs @@ -1,5 +1,7 @@ #nullable disable +using System.Collections.Generic; + namespace MediaBrowser.Model.SyncPlay { /// <summary> @@ -23,7 +25,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the playlist. /// </summary> /// <value>The playlist.</value> - public QueueItem[] Playlist { get; set; } + public IReadOnlyList<QueueItem> Playlist { get; set; } /// <summary> /// Gets or sets the playing item index in the playlist. diff --git a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs index 0d0f48ea97..4809dc44f8 100644 --- a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs +++ b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs @@ -69,6 +69,7 @@ namespace MediaBrowser.Model.SyncPlay /// A user is requesting previous track in playlist. /// </summary> PreviousTrack = 12, + /// <summary> /// A user is setting the repeat mode. /// </summary> From cfefcd988abf1b00c903d7f556199ca5647092b7 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 14 Nov 2020 07:07:09 -0700 Subject: [PATCH 0343/1930] Updated based on review feedback --- Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index 1b16a39ced..67d9bd1f12 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -42,7 +42,7 @@ namespace Jellyfin.Api.ModelBinders if (value != null) { - var splitValues = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); + var splitValues = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var typedValues = GetParsedResult(splitValues, elementType, converter); bindingContext.Result = ModelBindingResult.Success(typedValues); } From e36725096afd0287c6aa8b19e6612649836f3e1e Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 14 Nov 2020 22:18:43 +0800 Subject: [PATCH 0344/1930] fix return type for GetAttachment --- Jellyfin.Api/Controllers/VideoAttachmentsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs index 09a1c93e6a..418c0c1230 100644 --- a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs +++ b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs @@ -46,7 +46,7 @@ namespace Jellyfin.Api.Controllers [Produces(MediaTypeNames.Application.Octet)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public async Task<ActionResult<FileStreamResult>> GetAttachment( + public async Task<ActionResult> GetAttachment( [FromRoute, Required] Guid videoId, [FromRoute, Required] string mediaSourceId, [FromRoute, Required] int index) From 450cd614acdd2425d1fc713ebeb7e5b3a7156a06 Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Sat, 14 Nov 2020 08:13:53 -0700 Subject: [PATCH 0345/1930] Update Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs Co-authored-by: Bond-009 <bond.009@outlook.com> --- Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index 67d9bd1f12..e90f48d2fe 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -42,7 +42,7 @@ namespace Jellyfin.Api.ModelBinders if (value != null) { - var splitValues = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries); var typedValues = GetParsedResult(splitValues, elementType, converter); bindingContext.Result = ModelBindingResult.Success(typedValues); } From 83333e1fe8ed35f73fafdc200a4bf39be7d80f1b Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sat, 14 Nov 2020 17:07:52 +0100 Subject: [PATCH 0346/1930] Replace foreach loop with FindIndex --- .../SyncPlay/Queue/PlayQueueManager.cs | 36 +++---------------- 1 file changed, 4 insertions(+), 32 deletions(-) diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 8bc21a6a80..821a6314bd 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -269,18 +269,8 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="itemId">The new playing item identifier.</param> public void SetPlayingItemById(Guid itemId) { - PlayingItemIndex = NoPlayingItemIndex; - var playlist = GetPlaylistInternal(); - foreach (var item in playlist) - { - if (item.ItemId.Equals(itemId)) - { - PlayingItemIndex = playlist.IndexOf(item); - break; - } - } - + PlayingItemIndex = playlist.FindIndex(item => item.ItemId.Equals(itemId)); LastChange = DateTime.UtcNow; } @@ -291,19 +281,10 @@ namespace MediaBrowser.Controller.SyncPlay /// <returns><c>true</c> if playing item has been set; <c>false</c> if item is not in the playlist.</returns> public bool SetPlayingItemByPlaylistId(string playlistItemId) { - PlayingItemIndex = NoPlayingItemIndex; - var playlist = GetPlaylistInternal(); - foreach (var item in playlist) - { - if (item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)) - { - PlayingItemIndex = playlist.IndexOf(item); - break; - } - } - + PlayingItemIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)); LastChange = DateTime.UtcNow; + return PlayingItemIndex != NoPlayingItemIndex; } @@ -380,16 +361,7 @@ namespace MediaBrowser.Controller.SyncPlay var playlist = GetPlaylistInternal(); var playingItem = GetPlayingItem(); - var oldIndex = -1; - foreach (var item in playlist) - { - if (item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)) - { - oldIndex = playlist.IndexOf(item); - break; - } - } - + var oldIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)); if (oldIndex < 0) { return false; From 843847fc9311ecd04d262d8b04698d88d6332efc Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 14 Nov 2020 09:16:08 -0700 Subject: [PATCH 0347/1930] Remove extraneous newline --- deployment/Dockerfile.debian.amd64 | 3 +-- deployment/Dockerfile.debian.arm64 | 3 +-- deployment/Dockerfile.debian.armhf | 3 +-- deployment/Dockerfile.linux.amd64 | 3 +-- deployment/Dockerfile.macos | 3 +-- deployment/Dockerfile.portable | 3 +-- deployment/Dockerfile.ubuntu.amd64 | 3 +-- deployment/Dockerfile.ubuntu.arm64 | 3 +-- deployment/Dockerfile.ubuntu.armhf | 3 +-- deployment/Dockerfile.windows.amd64 | 3 +-- 10 files changed, 10 insertions(+), 20 deletions(-) diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index 6241aa1a7f..1f28748b2f 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index d09ba957e2..9bd51ad8c3 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index dbffb8846c..fe54e5b47e 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index e3faf43774..4d00bc4997 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index b68c25a8ce..85f3fc6424 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index 3a93b97261..3253d2141a 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,8 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index bac6fadaf6..d4fa596a3b 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index dd042edbc2..5fd19a2fc5 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index e5f669eff6..d73ea92fbd 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 5170b6895a..0c99f6954d 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,8 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet From 6b4debb44e93bbf9966eaf7c0a769f4b3130a071 Mon Sep 17 00:00:00 2001 From: Adam Bokor <bokoradam112@gmail.com> Date: Sat, 14 Nov 2020 14:05:02 +0000 Subject: [PATCH 0348/1930] Translated using Weblate (Hungarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hu/ --- Emby.Server.Implementations/Localization/Core/hu.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index 343d213d41..804dabe57a 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -113,5 +113,7 @@ "TaskDownloadMissingSubtitles": "Hiányzó feliratok letöltése", "TaskRefreshChannelsDescription": "Frissíti az internetes csatornák adatait.", "TaskRefreshChannels": "Csatornák frissítése", - "TaskCleanTranscodeDescription": "Törli az egy napnál régebbi átkódolási fájlokat." + "TaskCleanTranscodeDescription": "Törli az egy napnál régebbi átkódolási fájlokat.", + "TaskCleanActivityLogDescription": "A beállítottnál korábbi bejegyzések törlése a tevékenységnaplóból.", + "TaskCleanActivityLog": "Tevékenységnapló törlése" } From fa69f6fd511b88f2c10f37c45e1924b8bfe2e7ec Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sat, 14 Nov 2020 18:09:25 +0100 Subject: [PATCH 0349/1930] Handle ignore-wait request in waiting state in SyncPlay --- .../SyncPlay/GroupController.cs | 6 +- .../SyncPlay/GroupStates/IdleGroupState.cs | 8 +-- .../SyncPlay/GroupStates/PausedGroupState.cs | 8 +-- .../SyncPlay/GroupStates/PlayingGroupState.cs | 8 +-- .../SyncPlay/GroupStates/WaitingGroupState.cs | 34 +++++++-- .../SyncPlay/IGroupState.cs | 72 +++++++++---------- 6 files changed, 68 insertions(+), 68 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 5a3c707dbf..5447aad5dd 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -372,12 +372,10 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait) { - if (!Participants.ContainsKey(session.Id)) + if (Participants.TryGetValue(session.Id, out GroupMember value)) { - return; + value.IgnoreGroupWait = ignoreGroupWait; } - - Participants[session.Id].IgnoreGroupWait = ignoreGroupWait; } /// <inheritdoc /> diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index 1a507e044c..d9350cc9b9 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -24,13 +24,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupStateType Type - { - get - { - return GroupStateType.Idle; - } - } + public override GroupStateType Type { get; } = GroupStateType.Idle; /// <inheritdoc /> public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index 11f526d31d..5ae4786057 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -25,13 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupStateType Type - { - get - { - return GroupStateType.Paused; - } - } + public override GroupStateType Type { get; } = GroupStateType.Paused; /// <inheritdoc /> public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index 2aa7598118..394c64e511 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -25,13 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupStateType Type - { - get - { - return GroupStateType.Playing; - } - } + public override GroupStateType Type { get; } = GroupStateType.Playing; /// <summary> /// Gets or sets a value indicating whether requests for buffering should be ignored. diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index 7f454570a9..c78077b357 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -25,13 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay } /// <inheritdoc /> - public override GroupStateType Type - { - get - { - return GroupStateType.Waiting; - } - } + public override GroupStateType Type { get; } = GroupStateType.Waiting; /// <summary> /// Gets or sets a value indicating whether playback should resume when group is ready. @@ -651,5 +645,31 @@ namespace MediaBrowser.Controller.SyncPlay Logger.LogDebug("HandleRequest: {0} in group {1}, no previous track available.", request.Type, context.GroupId.ToString()); } } + + /// <inheritdoc /> + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + { + context.SetIgnoreGroupWait(session, request.IgnoreWait); + + if (!context.IsBuffering()) + { + Logger.LogDebug("HandleRequest: {0} in group {1}, returning to previous state.", request.Type, context.GroupId.ToString()); + + if (ResumePlaying) + { + // Client, that was buffering, stopped following playback. + var playingState = new PlayingGroupState(Logger); + context.SetState(playingState); + var unpauseRequest = new UnpauseGroupRequest(); + playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); + } + else + { + // Group is ready, returning to previous state. + var pausedState = new PausedGroupState(Logger); + context.SetState(pausedState); + } + } + } } } diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs index 981b65221b..f6ebe2a58d 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -34,181 +34,181 @@ namespace MediaBrowser.Controller.SyncPlay void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Generic handle. Context's state can change. + /// Generic handler. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The generic action.</param> + /// <param name="request">The generic request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, IGroupPlaybackRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a play action requested by a session. Context's state can change. + /// Handles a play request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The play action.</param> + /// <param name="request">The play request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a playlist-item change requested by a session. Context's state can change. + /// Handles a set-playlist-item request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The playlist-item change action.</param> + /// <param name="request">The set-playlist-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a remove-items change requested by a session. Context's state can change. + /// Handles a remove-items request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The remove-items change action.</param> + /// <param name="request">The remove-items request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a move-item change requested by a session. Context's state should not change. + /// Handles a move-playlist-item request from a session. Context's state should not change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The move-item change action.</param> + /// <param name="request">The move-playlist-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a queue change requested by a session. Context's state should not change. + /// Handles a queue request from a session. Context's state should not change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The queue action.</param> + /// <param name="request">The queue request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles an unpause action requested by a session. Context's state can change. + /// Handles an unpause request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The unpause action.</param> + /// <param name="request">The unpause request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a pause action requested by a session. Context's state can change. + /// Handles a pause request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The pause action.</param> + /// <param name="request">The pause request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a stop action requested by a session. Context's state can change. + /// Handles a stop request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The stop action.</param> + /// <param name="request">The stop request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a seek action requested by a session. Context's state can change. + /// Handles a seek request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The seek action.</param> + /// <param name="request">The seek request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a buffering action requested by a session. Context's state can change. + /// Handles a buffer request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The buffering action.</param> + /// <param name="request">The buffer request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a buffering-done action requested by a session. Context's state can change. + /// Handles a ready request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The buffering-done action.</param> + /// <param name="request">The ready request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a next-track action requested by a session. Context's state can change. + /// Handles a next-track request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The next-track action.</param> + /// <param name="request">The next-track request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a previous-track action requested by a session. Context's state can change. + /// Handles a previous-track request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The previous-track action.</param> + /// <param name="request">The previous-track request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a repeat-mode change requested by a session. Context's state should not change. + /// Handles a set-repeat-mode request from a session. Context's state should not change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The repeat-mode action.</param> + /// <param name="request">The repeat-mode request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a shuffle-mode change requested by a session. Context's state should not change. + /// Handles a set-shuffle-mode request from a session. Context's state should not change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The shuffle-mode action.</param> + /// <param name="request">The shuffle-mode request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Updates ping of a session. Context's state should not change. + /// Updates the ping of a session. Context's state should not change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The buffering-done action.</param> + /// <param name="request">The ping request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Updates whether the session should be considered during group wait. Context's state should not change. + /// Handles a ignore-wait request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The ignore-wait action.</param> + /// <param name="request">The ignore-wait request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken); From bc7359f87dafb972dfe79667128f307643015bac Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 14 Nov 2020 15:47:34 +0100 Subject: [PATCH 0350/1930] Use string.Split(char) where possible instead of string.Split(char[]) --- Emby.Dlna/Didl/Filter.cs | 2 +- .../ApplicationHost.cs | 2 +- .../Data/SqliteItemRepository.cs | 24 +++++++++---------- Emby.Server.Implementations/Dto/DtoService.cs | 2 +- .../Security/AuthorizationContext.cs | 4 ++-- .../Library/MediaSourceManager.cs | 2 +- .../LiveTv/LiveTvManager.cs | 2 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 2 +- .../JsonCommaDelimitedArrayConverter.cs | 4 ++-- .../MediaEncoding/JobLogger.cs | 8 +++---- .../Subtitles/SubtitleManager.cs | 8 +++---- 11 files changed, 30 insertions(+), 30 deletions(-) diff --git a/Emby.Dlna/Didl/Filter.cs b/Emby.Dlna/Didl/Filter.cs index b58fdff2c9..d703f043eb 100644 --- a/Emby.Dlna/Didl/Filter.cs +++ b/Emby.Dlna/Didl/Filter.cs @@ -18,7 +18,7 @@ namespace Emby.Dlna.Didl { _all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase); - _fields = (filter ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + _fields = (filter ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries); } public bool Contains(string field) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f3bd95d805..ea75252c55 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1032,7 +1032,7 @@ namespace Emby.Server.Implementations else { // No metafile, so lets see if the folder is versioned. - metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1]; + metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; int versionIndex = dir.LastIndexOf('_'); if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version parsedVersion)) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 0761b64bd2..638c7a9b49 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1007,7 +1007,7 @@ namespace Emby.Server.Implementations.Data return; } - var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + var parts = value.Split('|', StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { @@ -1057,7 +1057,7 @@ namespace Emby.Server.Implementations.Data return; } - var parts = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + var parts = value.Split('|' , StringSplitOptions.RemoveEmptyEntries); var list = new List<ItemImageInfo>(); foreach (var part in parts) { @@ -1096,7 +1096,7 @@ namespace Emby.Server.Implementations.Data public ItemImageInfo ItemImageInfoFromValueString(string value) { - var parts = value.Split(new[] { '*' }, StringSplitOptions.None); + var parts = value.Split('*', StringSplitOptions.None); if (parts.Length < 3) { @@ -1532,7 +1532,7 @@ namespace Emby.Server.Implementations.Data { if (!reader.IsDBNull(index)) { - item.Genres = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + item.Genres = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; @@ -1593,7 +1593,7 @@ namespace Emby.Server.Implementations.Data { IEnumerable<MetadataField> GetLockedFields(string s) { - foreach (var i in s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var i in s.Split('|', StringSplitOptions.RemoveEmptyEntries)) { if (Enum.TryParse(i, true, out MetadataField parsedValue)) { @@ -1612,7 +1612,7 @@ namespace Emby.Server.Implementations.Data { if (!reader.IsDBNull(index)) { - item.Studios = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + item.Studios = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; @@ -1622,7 +1622,7 @@ namespace Emby.Server.Implementations.Data { if (!reader.IsDBNull(index)) { - item.Tags = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + item.Tags = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; @@ -1636,7 +1636,7 @@ namespace Emby.Server.Implementations.Data { IEnumerable<TrailerType> GetTrailerTypes(string s) { - foreach (var i in s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var i in s.Split('|', StringSplitOptions.RemoveEmptyEntries)) { if (Enum.TryParse(i, true, out TrailerType parsedValue)) { @@ -1811,7 +1811,7 @@ namespace Emby.Server.Implementations.Data { if (!reader.IsDBNull(index)) { - item.ProductionLocations = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); + item.ProductionLocations = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries).ToArray(); } index++; @@ -1848,14 +1848,14 @@ namespace Emby.Server.Implementations.Data { if (item is IHasArtist hasArtists && !reader.IsDBNull(index)) { - hasArtists.Artists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + hasArtists.Artists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; if (item is IHasAlbumArtist hasAlbumArtists && !reader.IsDBNull(index)) { - hasAlbumArtists.AlbumArtists = reader.GetString(index).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + hasAlbumArtists.AlbumArtists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; @@ -5611,7 +5611,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type return counts; } - var allTypes = typeString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries) + var allTypes = typeString.Split('|', StringSplitOptions.RemoveEmptyEntries) .ToLookup(x => x); foreach (var type in allTypes) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 73502c2c9f..f3e3a6397f 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -275,7 +275,7 @@ namespace Emby.Server.Implementations.Dto continue; } - var containers = container.Split(new[] { ',' }); + var containers = container.Split(','); if (containers.Length < 2) { continue; diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index e733c9092a..ea22b260ef 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -245,7 +245,7 @@ namespace Emby.Server.Implementations.HttpServer.Security return null; } - var parts = authorizationHeader.Split(new[] { ' ' }, 2); + var parts = authorizationHeader.Split(' ', 2); // There should be at least to parts if (parts.Length != 2) @@ -269,7 +269,7 @@ namespace Emby.Server.Implementations.HttpServer.Security foreach (var item in parts) { - var param = item.Trim().Split(new[] { '=' }, 2); + var param = item.Trim().Split('=', 2); if (param.Length == 2) { diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 376a155705..928f5f88e4 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -849,7 +849,7 @@ namespace Emby.Server.Implementations.Library throw new ArgumentException("Key can't be empty.", nameof(key)); } - var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2); + var keys = key.Split(LiveStreamIdDelimeter, 2); var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), keys[0], StringComparison.OrdinalIgnoreCase)); diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 5b9c5761ef..8c9bb6ba01 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2208,7 +2208,7 @@ namespace Emby.Server.Implementations.LiveTv /// <returns>Task.</returns> public Task ResetTuner(string id, CancellationToken cancellationToken) { - var parts = id.Split(new[] { '_' }, 2); + var parts = id.Split('_', 2); var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), parts[0], StringComparison.OrdinalIgnoreCase)); diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 13d6da3174..f06f038ab5 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -74,7 +74,7 @@ namespace Jellyfin.Api.Helpers } return removeEmpty - ? value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries) + ? value.Split(separator, StringSplitOptions.RemoveEmptyEntries) : value.Split(separator); } diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index b24a497613..06a29a0dbe 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Common.Json.Converters { if (reader.TokenType == JsonTokenType.String) { - var stringEntries = reader.GetString()?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var stringEntries = reader.GetString()?.Split(',', StringSplitOptions.RemoveEmptyEntries); if (stringEntries == null || stringEntries.Length == 0) { return Array.Empty<T>(); @@ -71,4 +71,4 @@ namespace MediaBrowser.Common.Json.Converters JsonSerializer.Serialize(writer, value, options); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index ac520c5c44..cc8820f393 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (part.StartsWith("fps=", StringComparison.OrdinalIgnoreCase)) { - var rate = part.Split(new[] { '=' }, 2)[^1]; + var rate = part.Split('=', 2)[^1]; if (float.TryParse(rate, NumberStyles.Any, _usCulture, out var val)) { @@ -103,7 +103,7 @@ namespace MediaBrowser.Controller.MediaEncoding else if (state.RunTimeTicks.HasValue && part.StartsWith("time=", StringComparison.OrdinalIgnoreCase)) { - var time = part.Split(new[] { '=' }, 2).Last(); + var time = part.Split('=', 2)[^1]; if (TimeSpan.TryParse(time, _usCulture, out var val)) { @@ -116,7 +116,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase)) { - var size = part.Split(new[] { '=' }, 2).Last(); + var size = part.Split('=', 2)[^1]; int? scale = null; if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1) @@ -135,7 +135,7 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase)) { - var rate = part.Split(new[] { '=' }, 2).Last(); + var rate = part.Split('=', 2)[^1]; int? scale = null; if (rate.IndexOf("kbits/s", StringComparison.OrdinalIgnoreCase) != -1) diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index f3fbe2d12d..6ec7c163f7 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -147,7 +147,7 @@ namespace MediaBrowser.Providers.Subtitles string subtitleId, CancellationToken cancellationToken) { - var parts = subtitleId.Split(new[] { '_' }, 2); + var parts = subtitleId.Split('_', 2); var provider = GetProvider(parts[0]); try @@ -329,7 +329,7 @@ namespace MediaBrowser.Providers.Subtitles Index = index, ItemId = item.Id, Type = MediaStreamType.Subtitle - }).First(); + })[0]; var path = stream.Path; _monitor.ReportFileSystemChangeBeginning(path); @@ -349,10 +349,10 @@ namespace MediaBrowser.Providers.Subtitles /// <inheritdoc /> public Task<SubtitleResponse> GetRemoteSubtitles(string id, CancellationToken cancellationToken) { - var parts = id.Split(new[] { '_' }, 2); + var parts = id.Split('_', 2); var provider = GetProvider(parts[0]); - id = parts.Last(); + id = parts[1]; return provider.GetSubtitles(id, cancellationToken); } From 9041389f651f7e163911b301c623d95c89da9ee5 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 14 Nov 2020 15:49:31 +0100 Subject: [PATCH 0351/1930] Use string.Trim(char) instead of string.Trim(char[]) where possible --- .../HttpServer/Security/AuthorizationContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index ea22b260ef..fdf2e3908a 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -273,7 +273,7 @@ namespace Emby.Server.Implementations.HttpServer.Security if (param.Length == 2) { - var value = NormalizeValue(param[1].Trim(new[] { '"' })); + var value = NormalizeValue(param[1].Trim('"')); result[param[0]] = value; } } From c4bb32f259926df38298c9b1b3ca8ac80f727374 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 14 Nov 2020 15:54:50 +0100 Subject: [PATCH 0352/1930] Access last element by index where possible --- Emby.Dlna/Eventing/DlnaEventManager.cs | 2 +- Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs | 2 +- Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs | 6 +++--- Jellyfin.Api/Controllers/RemoteImageController.cs | 2 +- Jellyfin.Api/Helpers/StreamingHelpers.cs | 2 +- MediaBrowser.Providers/Subtitles/SubtitleManager.cs | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs index 770d56c30f..b6e45c50ea 100644 --- a/Emby.Dlna/Eventing/DlnaEventManager.cs +++ b/Emby.Dlna/Eventing/DlnaEventManager.cs @@ -83,7 +83,7 @@ namespace Emby.Dlna.Eventing if (!string.IsNullOrEmpty(header)) { // Starts with SECOND- - header = header.Split('-').Last(); + header = header.Split('-')[^1]; if (int.TryParse(header, NumberStyles.Integer, _usCulture, out var val)) { diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 0333e723bc..78e62ff0a5 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -182,7 +182,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (string.IsNullOrEmpty(currentFile)) { - return (files.Last(), true); + return (files[^1], true); } var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index c064e2fe6c..7c13d45e95 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -163,7 +163,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private string GetChannelNumber(string extInf, Dictionary<string, string> attributes, string mediaUrl) { - var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var nameParts = extInf.Split(',', StringSplitOptions.RemoveEmptyEntries); var nameInExtInf = nameParts.Length > 1 ? nameParts[^1].AsSpan().Trim() : ReadOnlySpan<char>.Empty; string numberString = null; @@ -273,8 +273,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private static string GetChannelName(string extInf, Dictionary<string, string> attributes) { - var nameParts = extInf.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - var nameInExtInf = nameParts.Length > 1 ? nameParts.Last().Trim() : null; + var nameParts = extInf.Split(',', StringSplitOptions.RemoveEmptyEntries); + var nameInExtInf = nameParts.Length > 1 ? nameParts[^1].Trim() : null; // Check for channel number with the format from SatIp // #EXTINF:0,84. VOX Schweiz diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index 5f095443b9..331277aec1 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -249,7 +249,7 @@ namespace Jellyfin.Api.Controllers { var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); using var response = await httpClient.GetAsync(url).ConfigureAwait(false); - var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); + var ext = response.Content.Headers.ContentType.MediaType.Split('/')[^1]; var fullCachePath = GetFullCachePath(urlHash + "." + ext); Directory.CreateDirectory(Path.GetDirectoryName(fullCachePath)); diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index f4ec29bdef..4e6e981be9 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -84,7 +84,7 @@ namespace Jellyfin.Api.Helpers streamingRequest.StreamOptions = ParseStreamOptions(httpRequest.Query); - var url = httpRequest.Path.Value.Split('.').Last(); + var url = httpRequest.Path.Value.Split('.')[^1]; if (string.IsNullOrEmpty(streamingRequest.AudioCodec)) { diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 6ec7c163f7..47e9d5ee8c 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -352,7 +352,7 @@ namespace MediaBrowser.Providers.Subtitles var parts = id.Split('_', 2); var provider = GetProvider(parts[0]); - id = parts[1]; + id = parts[^1]; return provider.GetSubtitles(id, cancellationToken); } From ff49a3bb6156a6b50a43d398796a8b4f3b4c2bda Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 14 Nov 2020 16:28:49 +0100 Subject: [PATCH 0353/1930] Missed some stuff --- DvdLib/Ifo/Dvd.cs | 2 +- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- .../Library/Resolvers/Audio/AudioResolver.cs | 2 +- .../ScheduledTasks/Tasks/ChapterImagesTask.cs | 2 +- Jellyfin.Api/Controllers/FilterController.cs | 6 +++--- .../Probing/ProbeResultNormalizer.cs | 4 ++-- MediaBrowser.Model/Dlna/ContainerProfile.cs | 2 +- MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs | 2 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 2 +- .../Plugins/TheTvdb/TvdbSeriesProvider.cs | 2 +- RSSDP/HttpParserBase.cs | 8 ++++---- 12 files changed, 18 insertions(+), 18 deletions(-) diff --git a/DvdLib/Ifo/Dvd.cs b/DvdLib/Ifo/Dvd.cs index 361319625c..b4a11ed5d6 100644 --- a/DvdLib/Ifo/Dvd.cs +++ b/DvdLib/Ifo/Dvd.cs @@ -31,7 +31,7 @@ namespace DvdLib.Ifo continue; } - var nums = ifo.Name.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries); + var nums = ifo.Name.Split('_', StringSplitOptions.RemoveEmptyEntries); if (nums.Length >= 2 && ushort.TryParse(nums[1], out var ifoNumber)) { ReadVTS(ifoNumber, ifo.FullName); diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index f16eda1ec2..7074382b68 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2705,7 +2705,7 @@ namespace Emby.Server.Implementations.Library var videos = videoListResolver.Resolve(fileSystemChildren); - var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase)); + var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase)); if (currentVideo != null) { diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 70be524116..2c4497c693 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -201,7 +201,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio continue; } - var firstMedia = resolvedItem.Files.First(); + var firstMedia = resolvedItem.Files[0]; var libraryItem = new T { diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs index 8439f8a99d..171e442581 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs @@ -106,7 +106,7 @@ namespace Emby.Server.Implementations.ScheduledTasks try { previouslyFailedImages = File.ReadAllText(failHistoryPath) - .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries) + .Split('|', StringSplitOptions.RemoveEmptyEntries) .ToList(); } catch (IOException) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 2a567c8461..008bb58d16 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -78,8 +78,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery { User = user, - MediaTypes = (mediaTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries), - IncludeItemTypes = (includeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries), + MediaTypes = (mediaTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), + IncludeItemTypes = (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), Recursive = true, EnableTotalRecordCount = false, DtoOptions = new DtoOptions @@ -168,7 +168,7 @@ namespace Jellyfin.Api.Controllers var genreQuery = new InternalItemsQuery(user) { IncludeItemTypes = - (includeItemTypes ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries), + (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), DtoOptions = new DtoOptions { Fields = Array.Empty<ItemFields>(), diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index cdeefbbbdf..15a70e2e7d 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -149,7 +149,7 @@ namespace MediaBrowser.MediaEncoding.Probing var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC"); if (!string.IsNullOrWhiteSpace(iTunEXTC)) { - var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + var parts = iTunEXTC.Split('|', StringSplitOptions.RemoveEmptyEntries); // Example // mpaa|G|100|For crude humor if (parts.Length > 1) @@ -1139,7 +1139,7 @@ namespace MediaBrowser.MediaEncoding.Probing return null; } - return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries) + return value.Split('/', StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i)); } diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index f77d9b2675..09afa64bbd 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -34,7 +34,7 @@ namespace MediaBrowser.Model.Dlna return Array.Empty<string>(); } - return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + return value.Split(',', StringSplitOptions.RemoveEmptyEntries); } public bool ContainsContainer(string container) diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index 8b73ecbd4d..50e3374f77 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -186,7 +186,7 @@ namespace MediaBrowser.Model.Dlna if (mediaProfile != null && !string.IsNullOrEmpty(mediaProfile.OrgPn)) { - orgPnValues.AddRange(mediaProfile.OrgPn.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); + orgPnValues.AddRange(mediaProfile.OrgPn.Split(',', StringSplitOptions.RemoveEmptyEntries)); } else { diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 4959a9b922..13234c3813 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1647,7 +1647,7 @@ namespace MediaBrowser.Model.Dlna // strip spaces to avoid having to encode var values = value - .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + .Split('|', StringSplitOptions.RemoveEmptyEntries); if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 32dab60a6b..9eed6172dd 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -391,7 +391,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb item.Genres = Array.Empty<string>(); foreach (var genre in result.Genre - .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) .Where(i => !string.IsNullOrWhiteSpace(i))) { diff --git a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs index b34e52235a..e5a3e9a6a3 100644 --- a/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs @@ -170,7 +170,7 @@ namespace MediaBrowser.Providers.Plugins.TheTvdb _logger.LogError(e, "Failed to retrieve series with remote id {RemoteId}", id); } - return result?.Data.First().Id.ToString(); + return result?.Data[0].Id.ToString(CultureInfo.InvariantCulture); } /// <summary> diff --git a/RSSDP/HttpParserBase.cs b/RSSDP/HttpParserBase.cs index a40612bc29..11202940e1 100644 --- a/RSSDP/HttpParserBase.cs +++ b/RSSDP/HttpParserBase.cs @@ -119,7 +119,7 @@ namespace Rssdp.Infrastructure } else { - headersToAddTo.TryAddWithoutValidation(headerName, values.First()); + headersToAddTo.TryAddWithoutValidation(headerName, values[0]); } } @@ -151,7 +151,7 @@ namespace Rssdp.Infrastructure return lineIndex; } - private IList<string> ParseValues(string headerValue) + private List<string> ParseValues(string headerValue) { // This really should be better and match the HTTP 1.1 spec, // but this should actually be good enough for SSDP implementations @@ -160,7 +160,7 @@ namespace Rssdp.Infrastructure if (headerValue == "\"\"") { - values.Add(String.Empty); + values.Add(string.Empty); return values; } @@ -172,7 +172,7 @@ namespace Rssdp.Infrastructure else { var segments = headerValue.Split(SeparatorCharacters); - if (headerValue.Contains("\"")) + if (headerValue.Contains('"')) { for (int segmentIndex = 0; segmentIndex < segments.Length; segmentIndex++) { From d4e568c8bf1e5312075225c5554eeffb5335fd47 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 14 Nov 2020 20:30:08 +0100 Subject: [PATCH 0354/1930] Replace Task.WaitAll with Task.Wait --- .../ScheduledTasks/ScheduledTaskWorker.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 56f4133a06..3a9e284583 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -653,7 +653,7 @@ namespace Emby.Server.Implementations.ScheduledTasks try { _logger.LogInformation(Name + ": Waiting on Task"); - var exited = Task.WaitAll(new[] { task }, 2000); + var exited = task.Wait(2000); if (exited) { From 95a2de757f8142fed4ef19b71ac2d483fa152674 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 14 Nov 2020 14:30:34 -0700 Subject: [PATCH 0355/1930] remove custom HttpException --- .../Library/LibraryManager.cs | 3 +- .../LiveTv/Listings/SchedulesDirect.cs | 6 +-- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +- .../ScheduledTasks/Tasks/PluginUpdateTask.cs | 3 +- .../Updates/InstallationManager.cs | 5 --- MediaBrowser.Model/Net/HttpException.cs | 42 ------------------- .../Manager/ItemImageProvider.cs | 5 ++- .../Manager/ProviderManager.cs | 10 +---- 8 files changed, 14 insertions(+), 64 deletions(-) delete mode 100644 MediaBrowser.Model/Net/HttpException.cs diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index f16eda1ec2..e7cf05496f 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Emby.Naming.Audio; @@ -2907,7 +2908,7 @@ namespace Emby.Server.Implementations.Library return item.GetImageInfo(image.Type, imageIndex); } - catch (HttpException ex) + catch (HttpRequestException ex) { if (ex.StatusCode.HasValue && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden)) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index aacadde504..43128c60d7 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -591,7 +591,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture); return result; } - catch (HttpException ex) + catch (HttpRequestException ex) { if (ex.StatusCode.HasValue) { @@ -621,7 +621,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { return await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false); } - catch (HttpException ex) + catch (HttpRequestException ex) { _tokens.Clear(); @@ -711,7 +711,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); } - catch (HttpException ex) + catch (HttpRequestException ex) { // Apparently we're supposed to swallow this if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 2f4c601172..9fdbad63c2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return discoverResponse; } - catch (HttpException ex) + catch (HttpRequestException ex) { if (!throwAllExceptions && ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) { @@ -663,7 +663,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var modelInfo = await GetModelInfo(info, true, CancellationToken.None).ConfigureAwait(false); info.DeviceId = modelInfo.DeviceID; } - catch (HttpException ex) + catch (HttpRequestException ex) { if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound) { diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs index c5af68bcec..161fa05809 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Updates; @@ -101,7 +102,7 @@ namespace Emby.Server.Implementations.ScheduledTasks throw; } } - catch (HttpException ex) + catch (HttpRequestException ex) { _logger.LogError(ex, "Error downloading {0}", package.Name); } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index fd1f43e626..6b6b8c4fe5 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -116,11 +116,6 @@ namespace Emby.Server.Implementations.Updates _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest); return Array.Empty<PackageInfo>(); } - catch (HttpException ex) - { - _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest); - return Array.Empty<PackageInfo>(); - } catch (HttpRequestException ex) { _logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest); diff --git a/MediaBrowser.Model/Net/HttpException.cs b/MediaBrowser.Model/Net/HttpException.cs deleted file mode 100644 index 48ff5d51cc..0000000000 --- a/MediaBrowser.Model/Net/HttpException.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Net; - -namespace MediaBrowser.Model.Net -{ - /// <summary> - /// Class HttpException. - /// </summary> - public class HttpException : Exception - { - /// <summary> - /// Gets or sets the status code. - /// </summary> - /// <value>The status code.</value> - public HttpStatusCode? StatusCode { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether this instance is timed out. - /// </summary> - /// <value><c>true</c> if this instance is timed out; otherwise, <c>false</c>.</value> - public bool IsTimedOut { get; set; } - - /// <summary> - /// Initializes a new instance of the <see cref="HttpException" /> class. - /// </summary> - /// <param name="message">The message.</param> - /// <param name="innerException">The inner exception.</param> - public HttpException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// <summary> - /// Initializes a new instance of the <see cref="HttpException" /> class. - /// </summary> - /// <param name="message">The message.</param> - public HttpException(string message) - : base(message) - { - } - } -} diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index a57a85376e..39748171af 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; @@ -481,7 +482,7 @@ namespace MediaBrowser.Providers.Manager result.UpdateType |= ItemUpdateType.ImageUpdate; return true; } - catch (HttpException ex) + catch (HttpRequestException ex) { // Sometimes providers send back bad url's. Just move to the next image if (ex.StatusCode.HasValue @@ -595,7 +596,7 @@ namespace MediaBrowser.Providers.Manager cancellationToken).ConfigureAwait(false); result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate; } - catch (HttpException ex) + catch (HttpRequestException ex) { // Sometimes providers send back bad urls. Just move onto the next image if (ex.StatusCode.HasValue diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index a0c7d4ad09..7a1b7bb2c7 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -160,10 +160,7 @@ namespace MediaBrowser.Providers.Manager if (response.StatusCode != HttpStatusCode.OK) { - throw new HttpException("Invalid image received.") - { - StatusCode = response.StatusCode - }; + throw new HttpRequestException("Invalid image received.", null, response.StatusCode); } var contentType = response.Content.Headers.ContentType.MediaType; @@ -181,10 +178,7 @@ namespace MediaBrowser.Providers.Manager // thetvdb will sometimes serve a rubbish 404 html page with a 200 OK code, because reasons... if (contentType.Equals(MediaTypeNames.Text.Html, StringComparison.OrdinalIgnoreCase)) { - throw new HttpException("Invalid image received.") - { - StatusCode = HttpStatusCode.NotFound - }; + throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound); } await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); From 5d77f422f0e4998130f1defebd08e053188a1a25 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sat, 14 Nov 2020 23:40:01 +0100 Subject: [PATCH 0356/1930] Hide some property setters, init null values, update namespaces --- .../SyncPlay/GroupController.cs | 49 +++------- .../Controllers/SyncPlayController.cs | 93 +++++-------------- .../GroupStates/AbstractGroupState.cs | 10 +- .../SyncPlay/GroupStates/IdleGroupState.cs | 3 +- .../SyncPlay/GroupStates/PausedGroupState.cs | 3 +- .../SyncPlay/GroupStates/PlayingGroupState.cs | 3 +- .../SyncPlay/GroupStates/WaitingGroupState.cs | 6 +- .../SyncPlay/IGroupController.cs | 1 + .../SyncPlay/IGroupState.cs | 1 + .../SyncPlay/IGroupStateContext.cs | 14 +-- .../PlaybackRequests/BufferGroupRequest.cs | 33 +++++-- .../IgnoreWaitGroupRequest.cs | 15 ++- .../MovePlaylistItemGroupRequest.cs | 23 +++-- .../PlaybackRequests/NextTrackGroupRequest.cs | 15 ++- .../PlaybackRequests/PauseGroupRequest.cs | 2 +- .../PlaybackRequests/PingGroupRequest.cs | 15 ++- .../PlaybackRequests/PlayGroupRequest.cs | 29 ++++-- .../PreviousTrackGroupRequest.cs | 15 ++- .../PlaybackRequests/QueueGroupRequest.cs | 27 ++++-- .../PlaybackRequests/ReadyGroupRequest.cs | 33 +++++-- .../RemoveFromPlaylistGroupRequest.cs | 15 ++- .../PlaybackRequests/SeekGroupRequest.cs | 15 ++- .../SetPlaylistItemGroupRequest.cs | 15 ++- .../SetRepeatModeGroupRequest.cs | 15 ++- .../SetShuffleModeGroupRequest.cs | 15 ++- .../PlaybackRequests/StopGroupRequest.cs | 2 +- .../PlaybackRequests/UnpauseGroupRequest.cs | 2 +- .../SyncPlay/Queue/PlayQueueManager.cs | 9 +- MediaBrowser.Model/SyncPlay/GroupInfoDto.cs | 15 ++- MediaBrowser.Model/SyncPlay/GroupQueueMode.cs | 18 ++++ .../SyncPlay/GroupRequestType.cs | 10 +- MediaBrowser.Model/SyncPlay/GroupStateType.cs | 8 +- .../SyncPlay/NewGroupRequest.cs | 10 +- .../SyncPlay/PlayQueueUpdate.cs | 13 ++- .../SyncPlay/PlayQueueUpdateReason.cs | 4 +- MediaBrowser.Model/SyncPlay/QueueItem.cs | 23 +++-- MediaBrowser.Model/SyncPlay/SendCommand.cs | 15 ++- 37 files changed, 365 insertions(+), 229 deletions(-) create mode 100644 MediaBrowser.Model/SyncPlay/GroupQueueMode.cs diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 5447aad5dd..a0d951b3e6 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -10,6 +10,8 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; +using MediaBrowser.Controller.SyncPlay.GroupStates; +using MediaBrowser.Controller.SyncPlay.Queue; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; @@ -358,7 +360,7 @@ namespace Emby.Server.Implementations.SyncPlay GroupName = GroupName, State = _state.Type, Participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(), - LastUpdatedAt = DateToUTCString(DateTime.UtcNow) + LastUpdatedAt = DateTime.UtcNow }; } @@ -422,8 +424,8 @@ namespace Emby.Server.Implementations.SyncPlay PlaylistItemId = PlayQueue.GetPlayingItemPlaylistId(), PositionTicks = PositionTicks, Command = type, - When = DateToUTCString(LastActivity), - EmittedAt = DateToUTCString(DateTime.UtcNow) + When = LastActivity, + EmittedAt = DateTime.UtcNow }; } @@ -438,12 +440,6 @@ namespace Emby.Server.Implementations.SyncPlay }; } - /// <inheritdoc /> - public string DateToUTCString(DateTime dateTime) - { - return dateTime.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture); - } - /// <inheritdoc /> public long SanitizePositionTicks(long? positionTicks) { @@ -580,7 +576,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool AddToPlayQueue(IEnumerable<Guid> newItems, string mode) + public bool AddToPlayQueue(IEnumerable<Guid> newItems, GroupQueueMode mode) { // Ignore on empty list. if (!newItems.Any()) @@ -594,7 +590,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } - if (mode.Equals("next", StringComparison.OrdinalIgnoreCase)) + if (mode.Equals(GroupQueueMode.QueueNext)) { PlayQueue.QueueNext(newItems); } @@ -648,36 +644,15 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SetRepeatMode(string mode) + public void SetRepeatMode(GroupRepeatMode mode) { - switch (mode) - { - case "RepeatOne": - PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatOne); - break; - case "RepeatAll": - PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatAll); - break; - default: - // On unknown values, default to repeat none. - PlayQueue.SetRepeatMode(GroupRepeatMode.RepeatNone); - break; - } + PlayQueue.SetRepeatMode(mode); } /// <inheritdoc /> - public void SetShuffleMode(string mode) + public void SetShuffleMode(GroupShuffleMode mode) { - switch (mode) - { - case "Shuffle": - PlayQueue.SetShuffleMode(GroupShuffleMode.Shuffle); - break; - default: - // On unknown values, default to sorted playlist. - PlayQueue.SetShuffleMode(GroupShuffleMode.Sorted); - break; - } + PlayQueue.SetShuffleMode(mode); } /// <inheritdoc /> @@ -701,7 +676,7 @@ namespace Emby.Server.Implementations.SyncPlay return new PlayQueueUpdate() { Reason = reason, - LastUpdate = DateToUTCString(PlayQueue.LastChange), + LastUpdate = PlayQueue.LastChange, Playlist = PlayQueue.GetPlaylist(), PlayingItemIndex = PlayQueue.PlayingItemIndex, StartPositionTicks = startPositionTicks, diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 6bd78179b5..9085a71c88 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -7,6 +7,7 @@ using Jellyfin.Api.Helpers; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -118,17 +119,12 @@ namespace Jellyfin.Api.Controllers [HttpPost("Play")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPlay( - [FromQuery, Required] string playingQueue, + [FromQuery, Required] Guid[] playingQueue, [FromQuery, Required] int playingItemPosition, [FromQuery, Required] long startPositionTicks) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlayGroupRequest() - { - PlayingItemPosition = playingItemPosition, - StartPositionTicks = startPositionTicks - }; - syncPlayRequest.PlayingQueue.AddRange(RequestHelpers.GetGuids(playingQueue)); + var syncPlayRequest = new PlayGroupRequest(playingQueue, playingItemPosition, startPositionTicks); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -145,10 +141,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string playlistItemId) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetPlaylistItemGroupRequest() - { - PlaylistItemId = playlistItemId - }; + var syncPlayRequest = new SetPlaylistItemGroupRequest(playlistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -165,8 +158,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string[] playlistItemIds) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new RemoveFromPlaylistGroupRequest(); - syncPlayRequest.PlaylistItemIds.AddRange(playlistItemIds); + var syncPlayRequest = new RemoveFromPlaylistGroupRequest(playlistItemIds); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -185,11 +177,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] int newIndex) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new MovePlaylistItemGroupRequest() - { - PlaylistItemId = playlistItemId, - NewIndex = newIndex - }; + var syncPlayRequest = new MovePlaylistItemGroupRequest(playlistItemId, newIndex); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -197,22 +185,18 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to queue items to the playlist of a SyncPlay group. /// </summary> - /// <param name="itemIds">The items to add. Item ids, comma delimited.</param> - /// <param name="mode">The mode in which to queue items.</param> + /// <param name="items">The items to add.</param> + /// <param name="mode">The mode in which to enqueue the items.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayQueue( - [FromQuery, Required] string itemIds, - [FromQuery, Required] string mode) + [FromQuery, Required] Guid[] items, + [FromQuery, Required] GroupQueueMode mode) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new QueueGroupRequest() - { - Mode = mode - }; - syncPlayRequest.ItemIds.AddRange(RequestHelpers.GetGuids(itemIds)); + var syncPlayRequest = new QueueGroupRequest(items, mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -274,10 +258,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] long positionTicks) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SeekGroupRequest() - { - PositionTicks = positionTicks - }; + var syncPlayRequest = new SeekGroupRequest(positionTicks); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -305,23 +286,11 @@ namespace Jellyfin.Api.Controllers IGroupPlaybackRequest syncPlayRequest; if (!bufferingDone) { - syncPlayRequest = new BufferGroupRequest() - { - When = when, - PositionTicks = positionTicks, - IsPlaying = isPlaying, - PlaylistItemId = playlistItemId - }; + syncPlayRequest = new BufferGroupRequest(when, positionTicks, isPlaying, playlistItemId); } else { - syncPlayRequest = new ReadyGroupRequest() - { - When = when, - PositionTicks = positionTicks, - IsPlaying = isPlaying, - PlaylistItemId = playlistItemId - }; + syncPlayRequest = new ReadyGroupRequest(when, positionTicks, isPlaying, playlistItemId); } _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); @@ -340,10 +309,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] bool ignoreWait) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new IgnoreWaitGroupRequest() - { - IgnoreWait = ignoreWait - }; + var syncPlayRequest = new IgnoreWaitGroupRequest(ignoreWait); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -360,10 +326,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string playlistItemId) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new NextTrackGroupRequest() - { - PlaylistItemId = playlistItemId - }; + var syncPlayRequest = new NextTrackGroupRequest(playlistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -380,10 +343,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string playlistItemId) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PreviousTrackGroupRequest() - { - PlaylistItemId = playlistItemId - }; + var syncPlayRequest = new PreviousTrackGroupRequest(playlistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -397,13 +357,10 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetRepeatMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetRepeatMode( - [FromQuery, Required] string mode) + [FromQuery, Required] GroupRepeatMode mode) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetRepeatModeGroupRequest() - { - Mode = mode - }; + var syncPlayRequest = new SetRepeatModeGroupRequest(mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -417,13 +374,10 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetShuffleMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetShuffleMode( - [FromQuery, Required] string mode) + [FromQuery, Required] GroupShuffleMode mode) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetShuffleModeGroupRequest() - { - Mode = mode - }; + var syncPlayRequest = new SetShuffleModeGroupRequest(mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -440,10 +394,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] double ping) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PingGroupRequest() - { - Ping = Convert.ToInt64(ping) - }; + var syncPlayRequest = new PingGroupRequest(Convert.ToInt64(ping)); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index 829ef2bbab..bc2e223802 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -1,10 +1,10 @@ -using System; using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.GroupStates { /// <summary> /// Class AbstractGroupState. @@ -104,7 +104,11 @@ namespace MediaBrowser.Controller.SyncPlay return; } - var reason = request.Mode.Equals("next", StringComparison.OrdinalIgnoreCase) ? PlayQueueUpdateReason.QueueNext : PlayQueueUpdateReason.Queue; + var reason = request.Mode switch + { + GroupQueueMode.QueueNext => PlayQueueUpdateReason.QueueNext, + _ => PlayQueueUpdateReason.Queue + }; var playQueueUpdate = context.GetPlayQueueUpdate(reason); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index d9350cc9b9..660afb607d 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -1,9 +1,10 @@ using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.GroupStates { /// <summary> /// Class IdleGroupState. diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index 5ae4786057..29942898e6 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -1,10 +1,11 @@ using System; using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.GroupStates { /// <summary> /// Class PausedGroupState. diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index 394c64e511..c5d73dedb8 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -1,10 +1,11 @@ using System; using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.GroupStates { /// <summary> /// Class PlayingGroupState. diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index c78077b357..78318dd94d 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -1,10 +1,11 @@ using System; using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; using Microsoft.Extensions.Logging; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.GroupStates { /// <summary> /// Class WaitingGroupState. @@ -464,8 +465,7 @@ namespace MediaBrowser.Controller.SyncPlay { // Others are still buffering, tell this client to pause when ready. var command = context.NewSyncPlayCommand(SendCommandType.Pause); - var pauseAtTime = currentTime.AddTicks(delayTicks); - command.When = context.DateToUTCString(pauseAtTime); + command.When = currentTime.AddTicks(delayTicks); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); Logger.LogInformation("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready in {3} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); diff --git a/MediaBrowser.Controller/SyncPlay/IGroupController.cs b/MediaBrowser.Controller/SyncPlay/IGroupController.cs index 038233fdd3..aa8bb9eaea 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupController.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupController.cs @@ -2,6 +2,7 @@ using System; using System.Threading; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.Queue; using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs index f6ebe2a58d..0028823b4e 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -1,5 +1,6 @@ using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs index 2ddaae6400..3609be36b7 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.Queue; using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay @@ -97,13 +98,6 @@ namespace MediaBrowser.Controller.SyncPlay /// <returns>The group update.</returns> GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data); - /// <summary> - /// Converts DateTime to UTC string. - /// </summary> - /// <param name="dateTime">The date to convert.</param> - /// <returns>The UTC string.</returns> - string DateToUTCString(DateTime dateTime); - /// <summary> /// Sanitizes the PositionTicks, considers the current playing item when available. /// </summary> @@ -187,7 +181,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="newItems">The new items to add to the play queue.</param> /// <param name="mode">The mode with which the items will be added.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool AddToPlayQueue(IEnumerable<Guid> newItems, string mode); + bool AddToPlayQueue(IEnumerable<Guid> newItems, GroupQueueMode mode); /// <summary> /// Restarts current item in play queue. @@ -210,13 +204,13 @@ namespace MediaBrowser.Controller.SyncPlay /// Sets the repeat mode. /// </summary> /// <param name="mode">The new mode.</param> - void SetRepeatMode(string mode); + void SetRepeatMode(GroupRepeatMode mode); /// <summary> /// Sets the shuffle mode. /// </summary> /// <param name="mode">The new mode.</param> - void SetShuffleMode(string mode); + void SetShuffleMode(GroupShuffleMode mode); /// <summary> /// Creates a play queue update. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index b5bed89f21..a12ab96b77 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -3,7 +3,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class BufferGroupRequest. @@ -11,28 +11,43 @@ namespace MediaBrowser.Controller.SyncPlay public class BufferGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets when the request has been made by the client. + /// Initializes a new instance of the <see cref="BufferGroupRequest"/> class. + /// </summary> + /// <param name="when">When the request has been made, as reported by the client.</param> + /// <param name="positionTicks">The position ticks.</param> + /// <param name="isPlaying">Whether the client playback is unpaused.</param> + /// <param name="playlistItemId">The playlist item identifier of the playing item.</param> + public BufferGroupRequest(DateTime when, long positionTicks, bool isPlaying, string playlistItemId) + { + When = when; + PositionTicks = positionTicks; + IsPlaying = isPlaying; + PlaylistItemId = playlistItemId; + } + + /// <summary> + /// Gets when the request has been made by the client. /// </summary> /// <value>The date of the request.</value> - public DateTime When { get; set; } + public DateTime When { get; } /// <summary> - /// Gets or sets the position ticks. + /// Gets the position ticks. /// </summary> /// <value>The position ticks.</value> - public long PositionTicks { get; set; } + public long PositionTicks { get; } /// <summary> - /// Gets or sets a value indicating whether the client playback is unpaused. + /// Gets a value indicating whether the client playback is unpaused. /// </summary> /// <value>The client playback status.</value> - public bool IsPlaying { get; set; } + public bool IsPlaying { get; } /// <summary> - /// Gets or sets the playlist item identifier of the playing item. + /// Gets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Buffer; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs index 325839f107..25034cb10b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class IgnoreWaitGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class IgnoreWaitGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets a value indicating whether the client should be ignored. + /// Initializes a new instance of the <see cref="IgnoreWaitGroupRequest"/> class. + /// </summary> + /// <param name="ignoreWait">Whether the client should be ignored.</param> + public IgnoreWaitGroupRequest(bool ignoreWait) + { + IgnoreWait = ignoreWait; + } + + /// <summary> + /// Gets a value indicating whether the client should be ignored. /// </summary> /// <value>The client group-wait status.</value> - public bool IgnoreWait { get; set; } + public bool IgnoreWait { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.IgnoreWait; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index 3c95f53d4a..a12eff8b84 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class MovePlaylistItemGroupRequest. @@ -10,16 +10,27 @@ namespace MediaBrowser.Controller.SyncPlay public class MovePlaylistItemGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the playlist identifier of the item. + /// Initializes a new instance of the <see cref="MovePlaylistItemGroupRequest"/> class. /// </summary> - /// <value>The playlist identifier of the item.</value> - public string PlaylistItemId { get; set; } + /// <param name="playlistItemId">The playlist identifier of the item.</param> + /// <param name="newIndex">The new position.</param> + public MovePlaylistItemGroupRequest(string playlistItemId, int newIndex) + { + PlaylistItemId = playlistItemId; + NewIndex = newIndex; + } /// <summary> - /// Gets or sets the new position. + /// Gets the playlist identifier of the item. + /// </summary> + /// <value>The playlist identifier of the item.</value> + public string PlaylistItemId { get; } + + /// <summary> + /// Gets the new position. /// </summary> /// <value>The new position.</value> - public int NewIndex { get; set; } + public int NewIndex { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.MovePlaylistItem; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs index 8636d6f4d5..f87bbc556d 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class NextTrackGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class NextTrackGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the playing item identifier. + /// Initializes a new instance of the <see cref="NextTrackGroupRequest"/> class. + /// </summary> + /// <param name="playlistItemId">The playing item identifier.</param> + public NextTrackGroupRequest(string playlistItemId) + { + PlaylistItemId = playlistItemId; + } + + /// <summary> + /// Gets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.NextTrack; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs index 45bd3b15f1..0dcd1423fd 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class PauseGroupRequest. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs index 9dacb79857..2528bb3e70 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class PingGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class PingGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the ping time. + /// Initializes a new instance of the <see cref="PingGroupRequest"/> class. + /// </summary> + /// <param name="ping">The ping time.</param> + public PingGroupRequest(long ping) + { + Ping = ping; + } + + /// <summary> + /// Gets the ping time. /// </summary> /// <value>The ping time.</value> - public long Ping { get; set; } + public long Ping { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Ping; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index e090a882e2..306c161ed9 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -4,30 +4,45 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class PlayGroupRequest. /// </summary> public class PlayGroupRequest : IGroupPlaybackRequest { + /// <summary> + /// Initializes a new instance of the <see cref="PlayGroupRequest"/> class. + /// </summary> + /// <param name="playingQueue">The playing queue.</param> + /// <param name="playingItemPosition">The playing item position.</param> + /// <param name="startPositionTicks">The start position ticks.</param> + public PlayGroupRequest(Guid[] playingQueue, int playingItemPosition, long startPositionTicks) + { + var list = new List<Guid>(); + list.AddRange(playingQueue); + PlayingQueue = list; + PlayingItemPosition = playingItemPosition; + StartPositionTicks = startPositionTicks; + } + /// <summary> /// Gets the playing queue. /// </summary> /// <value>The playing queue.</value> - public List<Guid> PlayingQueue { get; } = new List<Guid>(); + public IReadOnlyList<Guid> PlayingQueue { get; } /// <summary> - /// Gets or sets the playing item from the queue. + /// Gets the position of the playing item in the queue. /// </summary> - /// <value>The playing item.</value> - public int PlayingItemPosition { get; set; } + /// <value>The playing item position.</value> + public int PlayingItemPosition { get; } /// <summary> - /// Gets or sets the start position ticks. + /// Gets the start position ticks. /// </summary> /// <value>The start position ticks.</value> - public long StartPositionTicks { get; set; } + public long StartPositionTicks { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Play; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs index aca5d678e0..206fef3312 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class PreviousTrackGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class PreviousTrackGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the playing item identifier. + /// Initializes a new instance of the <see cref="PreviousTrackGroupRequest"/> class. + /// </summary> + /// <param name="playlistItemId">The playing item identifier.</param> + public PreviousTrackGroupRequest(string playlistItemId) + { + PlaylistItemId = playlistItemId; + } + + /// <summary> + /// Gets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.PreviousTrack; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index 82380b2098..9580b53154 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -4,7 +4,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class QueueGroupRequest. @@ -12,16 +12,29 @@ namespace MediaBrowser.Controller.SyncPlay public class QueueGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets the items to queue. + /// Initializes a new instance of the <see cref="QueueGroupRequest"/> class. /// </summary> - /// <value>The items to queue.</value> - public List<Guid> ItemIds { get; } = new List<Guid>(); + /// <param name="items">The items to add to the queue.</param> + /// <param name="mode">The enqueue mode.</param> + public QueueGroupRequest(Guid[] items, GroupQueueMode mode) + { + var list = new List<Guid>(); + list.AddRange(items); + ItemIds = list; + Mode = mode; + } /// <summary> - /// Gets or sets the mode in which to add the new items. + /// Gets the items to enqueue. /// </summary> - /// <value>The mode.</value> - public string Mode { get; set; } + /// <value>The items to enqueue.</value> + public IReadOnlyList<Guid> ItemIds { get; } + + /// <summary> + /// Gets the mode in which to add the new items. + /// </summary> + /// <value>The enqueue mode.</value> + public GroupQueueMode Mode { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Queue; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index c8a2268cfb..a2b3553cee 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -3,7 +3,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class ReadyGroupRequest. @@ -11,28 +11,43 @@ namespace MediaBrowser.Controller.SyncPlay public class ReadyGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets when the request has been made by the client. + /// Initializes a new instance of the <see cref="ReadyGroupRequest"/> class. + /// </summary> + /// <param name="when">When the request has been made, as reported by the client.</param> + /// <param name="positionTicks">The position ticks.</param> + /// <param name="isPlaying">Whether the client playback is unpaused.</param> + /// <param name="playlistItemId">The playlist item identifier of the playing item.</param> + public ReadyGroupRequest(DateTime when, long positionTicks, bool isPlaying, string playlistItemId) + { + When = when; + PositionTicks = positionTicks; + IsPlaying = isPlaying; + PlaylistItemId = playlistItemId; + } + + /// <summary> + /// Gets when the request has been made by the client. /// </summary> /// <value>The date of the request.</value> - public DateTime When { get; set; } + public DateTime When { get; } /// <summary> - /// Gets or sets the position ticks. + /// Gets the position ticks. /// </summary> /// <value>The position ticks.</value> - public long PositionTicks { get; set; } + public long PositionTicks { get; } /// <summary> - /// Gets or sets a value indicating whether the client playback is unpaused. + /// Gets a value indicating whether the client playback is unpaused. /// </summary> /// <value>The client playback status.</value> - public bool IsPlaying { get; set; } + public bool IsPlaying { get; } /// <summary> - /// Gets or sets the playlist item identifier of the playing item. + /// Gets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Ready; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index 4ead1301b6..21c602846e 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -3,18 +3,29 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class RemoveFromPlaylistGroupRequest. /// </summary> public class RemoveFromPlaylistGroupRequest : IGroupPlaybackRequest { + /// <summary> + /// Initializes a new instance of the <see cref="RemoveFromPlaylistGroupRequest"/> class. + /// </summary> + /// <param name="items">The playlist ids of the items to remove.</param> + public RemoveFromPlaylistGroupRequest(string[] items) + { + var list = new List<string>(); + list.AddRange(items); + PlaylistItemIds = list; + } + /// <summary> /// Gets the playlist identifiers ot the items. /// </summary> /// <value>The playlist identifiers ot the items.</value> - public List<string> PlaylistItemIds { get; } = new List<string>(); + public IReadOnlyList<string> PlaylistItemIds { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.RemoveFromPlaylist; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs index d311bffdc4..f7bfc19788 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class SeekGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class SeekGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the position ticks. + /// Initializes a new instance of the <see cref="SeekGroupRequest"/> class. + /// </summary> + /// <param name="positionTicks">The position ticks.</param> + public SeekGroupRequest(long positionTicks) + { + PositionTicks = positionTicks; + } + + /// <summary> + /// Gets the position ticks. /// </summary> /// <value>The position ticks.</value> - public long PositionTicks { get; set; } + public long PositionTicks { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.Seek; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index 0983d91292..2ca33c1ccf 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class SetPlaylistItemGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class SetPlaylistItemGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the playlist identifier of the playing item. + /// Initializes a new instance of the <see cref="SetPlaylistItemGroupRequest"/> class. + /// </summary> + /// <param name="playlistItemId">The playlist identifier of the item.</param> + public SetPlaylistItemGroupRequest(string playlistItemId) + { + PlaylistItemId = playlistItemId; + } + + /// <summary> + /// Gets the playlist identifier of the playing item. /// </summary> /// <value>The playlist identifier of the playing item.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.SetPlaylistItem; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs index 79373ef5f5..cd4505e4d0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class SetRepeatModeGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class SetRepeatModeGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the repeat mode. + /// Initializes a new instance of the <see cref="SetRepeatModeGroupRequest"/> class. + /// </summary> + /// <param name="mode">The repeat mode.</param> + public SetRepeatModeGroupRequest(GroupRepeatMode mode) + { + Mode = mode; + } + + /// <summary> + /// Gets the repeat mode. /// </summary> /// <value>The repeat mode.</value> - public string Mode { get; set; } + public GroupRepeatMode Mode { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.SetRepeatMode; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs index 316fb49f40..4530a34c02 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class SetShuffleModeGroupRequest. @@ -10,10 +10,19 @@ namespace MediaBrowser.Controller.SyncPlay public class SetShuffleModeGroupRequest : IGroupPlaybackRequest { /// <summary> - /// Gets or sets the shuffle mode. + /// Initializes a new instance of the <see cref="SetShuffleModeGroupRequest"/> class. + /// </summary> + /// <param name="mode">The shuffle mode.</param> + public SetShuffleModeGroupRequest(GroupShuffleMode mode) + { + Mode = mode; + } + + /// <summary> + /// Gets the shuffle mode. /// </summary> /// <value>The shuffle mode.</value> - public string Mode { get; set; } + public GroupShuffleMode Mode { get; } /// <inheritdoc /> public PlaybackRequestType Type { get; } = PlaybackRequestType.SetShuffleMode; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs index 9f6f8ea63c..ec01cd1105 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class StopGroupRequest. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs index 84a6b0a6e7..bdf4fd4767 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs @@ -2,7 +2,7 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> /// Class UnpauseGroupRequest. diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 821a6314bd..2d1d1533b9 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Linq; using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Controller.SyncPlay +namespace MediaBrowser.Controller.SyncPlay.Queue { /// <summary> /// Class PlayQueueManager. @@ -563,11 +563,8 @@ namespace MediaBrowser.Controller.SyncPlay var list = new List<QueueItem>(); foreach (var item in items) { - list.Add(new QueueItem() - { - ItemId = item, - PlaylistItemId = "syncPlayItem" + GetNextProgressiveId() - }); + var queueItem = new QueueItem(item, "syncPlayItem" + GetNextProgressiveId()); + list.Add(queueItem); } return list; diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs index 85b9a35229..16a75eb68e 100644 --- a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs +++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs @@ -1,5 +1,4 @@ -#nullable disable - +using System; using System.Collections.Generic; namespace MediaBrowser.Model.SyncPlay @@ -9,6 +8,16 @@ namespace MediaBrowser.Model.SyncPlay /// </summary> public class GroupInfoDto { + /// <summary> + /// Initializes a new instance of the <see cref="GroupInfoDto"/> class. + /// </summary> + public GroupInfoDto() + { + GroupId = string.Empty; + GroupName = string.Empty; + Participants = new List<string>(); + } + /// <summary> /// Gets or sets the group identifier. /// </summary> @@ -37,6 +46,6 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the date when this dto has been updated. /// </summary> /// <value>The date when this dto has been updated.</value> - public string LastUpdatedAt { get; set; } + public DateTime LastUpdatedAt { get; set; } } } diff --git a/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs b/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs new file mode 100644 index 0000000000..5c9c2627b9 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/GroupQueueMode.cs @@ -0,0 +1,18 @@ +namespace MediaBrowser.Model.SyncPlay +{ + /// <summary> + /// Enum GroupQueueMode. + /// </summary> + public enum GroupQueueMode + { + /// <summary> + /// Insert items at the end of the queue. + /// </summary> + Queue = 0, + + /// <summary> + /// Insert items after the currently playing item. + /// </summary> + QueueNext = 1 + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupRequestType.cs b/MediaBrowser.Model/SyncPlay/GroupRequestType.cs index e7361817ca..75c0712364 100644 --- a/MediaBrowser.Model/SyncPlay/GroupRequestType.cs +++ b/MediaBrowser.Model/SyncPlay/GroupRequestType.cs @@ -8,26 +8,26 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// A user is requesting to create a new group. /// </summary> - NewGroup, + NewGroup = 0, /// <summary> /// A user is requesting to join a group. /// </summary> - JoinGroup, + JoinGroup = 1, /// <summary> /// A user is requesting to leave a group. /// </summary> - LeaveGroup, + LeaveGroup = 2, /// <summary> /// A user is requesting the list of available groups. /// </summary> - ListGroups, + ListGroups = 3, /// <summary> /// A user is sending a playback command to a group. /// </summary> - Playback + Playback = 4 } } diff --git a/MediaBrowser.Model/SyncPlay/GroupStateType.cs b/MediaBrowser.Model/SyncPlay/GroupStateType.cs index 341859b306..7aa454f928 100644 --- a/MediaBrowser.Model/SyncPlay/GroupStateType.cs +++ b/MediaBrowser.Model/SyncPlay/GroupStateType.cs @@ -8,21 +8,21 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// The group is in idle state. No media is playing. /// </summary> - Idle, + Idle = 0, /// <summary> /// The group is in wating state. Playback is paused. Will start playing when users are ready. /// </summary> - Waiting, + Waiting = 1, /// <summary> /// The group is in paused state. Playback is paused. Will resume on play command. /// </summary> - Paused, + Paused = 2, /// <summary> /// The group is in playing state. Playback is advancing. /// </summary> - Playing + Playing = 3 } } diff --git a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs index ccab5313f7..eb61a68d15 100644 --- a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs +++ b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs @@ -1,5 +1,3 @@ -#nullable disable - namespace MediaBrowser.Model.SyncPlay { /// <summary> @@ -7,6 +5,14 @@ namespace MediaBrowser.Model.SyncPlay /// </summary> public class NewGroupRequest { + /// <summary> + /// Initializes a new instance of the <see cref="NewGroupRequest"/> class. + /// </summary> + public NewGroupRequest() + { + GroupName = string.Empty; + } + /// <summary> /// Gets or sets the group name. /// </summary> diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs index 575597e62d..d193b4c663 100644 --- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs @@ -1,5 +1,4 @@ -#nullable disable - +using System; using System.Collections.Generic; namespace MediaBrowser.Model.SyncPlay @@ -9,6 +8,14 @@ namespace MediaBrowser.Model.SyncPlay /// </summary> public class PlayQueueUpdate { + /// <summary> + /// Initializes a new instance of the <see cref="PlayQueueUpdate"/> class. + /// </summary> + public PlayQueueUpdate() + { + Playlist = new List<QueueItem>(); + } + /// <summary> /// Gets or sets the request type that originated this update. /// </summary> @@ -19,7 +26,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the UTC time of the last change to the playing queue. /// </summary> /// <value>The UTC time of the last change to the playing queue.</value> - public string LastUpdate { get; set; } + public DateTime LastUpdate { get; set; } /// <summary> /// Gets or sets the playlist. diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs index 4b3f6eb4d6..e78940fe68 100644 --- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs @@ -26,12 +26,12 @@ namespace MediaBrowser.Model.SyncPlay MoveItem = 3, /// <summary> - /// A user is making changes to the queue. + /// A user is adding items the queue. /// </summary> Queue = 4, /// <summary> - /// A user is making changes to the queue. + /// A user is adding items to the queue, after the currently playing item. /// </summary> QueueNext = 5, diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/QueueItem.cs index ce253b182c..9c4d3a4ceb 100644 --- a/MediaBrowser.Model/SyncPlay/QueueItem.cs +++ b/MediaBrowser.Model/SyncPlay/QueueItem.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace MediaBrowser.Model.SyncPlay @@ -10,15 +8,26 @@ namespace MediaBrowser.Model.SyncPlay public class QueueItem { /// <summary> - /// Gets or sets the item identifier. + /// Initializes a new instance of the <see cref="QueueItem"/> class. /// </summary> - /// <value>The item identifier.</value> - public Guid ItemId { get; set; } + /// <param name="itemId">The item identifier.</param> + /// <param name="playlistItemId">The playlist identifier of the item.</param> + public QueueItem(Guid itemId, string playlistItemId) + { + ItemId = itemId; + PlaylistItemId = playlistItemId; + } /// <summary> - /// Gets or sets the playlist identifier of the item. + /// Gets the item identifier. + /// </summary> + /// <value>The item identifier.</value> + public Guid ItemId { get; } + + /// <summary> + /// Gets the playlist identifier of the item. /// </summary> /// <value>The playlist identifier of the item.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs index b24f7e97bd..a3aa54b380 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommand.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs @@ -1,4 +1,4 @@ -#nullable disable +using System; namespace MediaBrowser.Model.SyncPlay { @@ -7,6 +7,15 @@ namespace MediaBrowser.Model.SyncPlay /// </summary> public class SendCommand { + /// <summary> + /// Initializes a new instance of the <see cref="SendCommand"/> class. + /// </summary> + public SendCommand() + { + GroupId = string.Empty; + PlaylistItemId = string.Empty; + } + /// <summary> /// Gets or sets the group identifier. /// </summary> @@ -23,7 +32,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the UTC time when to execute the command. /// </summary> /// <value>The UTC time when to execute the command.</value> - public string When { get; set; } + public DateTime When { get; set; } /// <summary> /// Gets or sets the position ticks. @@ -41,6 +50,6 @@ namespace MediaBrowser.Model.SyncPlay /// Gets or sets the UTC time when this command has been emitted. /// </summary> /// <value>The UTC time when this command has been emitted.</value> - public string EmittedAt { get; set; } + public DateTime EmittedAt { get; set; } } } From ce4787c7eb2d19de263d7db0d05479f176544034 Mon Sep 17 00:00:00 2001 From: 4d1m <silviu.dimulete@gmail.com> Date: Sun, 15 Nov 2020 10:32:30 +0000 Subject: [PATCH 0357/1930] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index bc008df3b4..5e4022292e 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -112,5 +112,7 @@ "TasksChannelsCategory": "Canale de pe Internet", "TasksApplicationCategory": "Aplicație", "TasksLibraryCategory": "Librărie", - "TasksMaintenanceCategory": "Mentenanță" + "TasksMaintenanceCategory": "Mentenanță", + "TaskCleanActivityLogDescription": "Șterge intrările din jurnalul de activitate mai vechi de data configurată.", + "TaskCleanActivityLog": "Curăță Jurnalul de Activitate" } From c70710de32f99eb6dc7b1f4d650924cc7d8a286b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 09:30:04 -0700 Subject: [PATCH 0358/1930] Update user cache after updating user. --- Jellyfin.Server.Implementations/Users/UserManager.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 40b89ed284..f684d151d6 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -158,7 +158,6 @@ namespace Jellyfin.Server.Implementations.Users user.Username = newName; await UpdateUserAsync(user).ConfigureAwait(false); - OnUserUpdated?.Invoke(this, new GenericEventArgs<User>(user)); } @@ -167,6 +166,7 @@ namespace Jellyfin.Server.Implementations.Users { using var dbContext = _dbProvider.CreateContext(); dbContext.Users.Update(user); + _users[user.Id] = user; dbContext.SaveChanges(); } @@ -175,7 +175,7 @@ namespace Jellyfin.Server.Implementations.Users { await using var dbContext = _dbProvider.CreateContext(); dbContext.Users.Update(user); - + _users[user.Id] = user; await dbContext.SaveChangesAsync().ConfigureAwait(false); } @@ -642,6 +642,7 @@ namespace Jellyfin.Server.Implementations.Users user.SetPreference(PreferenceKind.LatestItemExcludes, config.LatestItemsExcludes); dbContext.Update(user); + _users[user.Id] = user; await dbContext.SaveChangesAsync().ConfigureAwait(false); } @@ -713,6 +714,7 @@ namespace Jellyfin.Server.Implementations.Users user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders); dbContext.Update(user); + _users[user.Id] = user; await dbContext.SaveChangesAsync().ConfigureAwait(false); } @@ -723,6 +725,7 @@ namespace Jellyfin.Server.Implementations.Users dbContext.Remove(user.ProfileImage); await dbContext.SaveChangesAsync().ConfigureAwait(false); user.ProfileImage = null; + _users[user.Id] = user; } private static bool IsValidUsername(string name) From c7e53bce2fa43ad38807a0589e1bc020237e49c6 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sun, 15 Nov 2020 17:03:27 +0100 Subject: [PATCH 0359/1930] Patch data-races and minor changes in SyncPlay --- .../SyncPlay/GroupController.cs | 96 ++---- .../SyncPlay/SyncPlayManager.cs | 312 +++++++++--------- .../Controllers/SyncPlayController.cs | 16 +- .../Controllers/TimeSyncController.cs | 14 +- .../GroupStates/AbstractGroupState.cs | 14 +- .../SyncPlay/GroupStates/WaitingGroupState.cs | 46 +-- .../SyncPlay/IGroupStateContext.cs | 6 +- .../SyncPlay/ISyncPlayManager.cs | 16 - .../PlaybackRequests/PlayGroupRequest.cs | 4 +- .../PlaybackRequests/QueueGroupRequest.cs | 4 +- .../RemoveFromPlaylistGroupRequest.cs | 5 +- .../SyncPlay/Queue/PlayQueueManager.cs | 22 +- MediaBrowser.Model/SyncPlay/GroupInfoDto.cs | 37 ++- .../SyncPlay/GroupStateUpdate.cs | 21 +- MediaBrowser.Model/SyncPlay/GroupUpdate.cs | 29 +- .../SyncPlay/JoinGroupRequest.cs | 13 +- .../SyncPlay/NewGroupRequest.cs | 9 +- .../SyncPlay/PlayQueueUpdate.cs | 45 ++- MediaBrowser.Model/SyncPlay/SendCommand.cs | 36 +- .../SyncPlay/UtcTimeResponse.cs | 23 +- 20 files changed, 383 insertions(+), 385 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index a0d951b3e6..48596bb421 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -45,11 +45,6 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> private readonly ILibraryManager _libraryManager; - /// <summary> - /// The SyncPlay manager. - /// </summary> - private readonly ISyncPlayManager _syncPlayManager; - /// <summary> /// Internal group state. /// </summary> @@ -63,19 +58,16 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="userManager">The user manager.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="libraryManager">The library manager.</param> - /// <param name="syncPlayManager">The SyncPlay manager.</param> public GroupController( ILogger logger, IUserManager userManager, ISessionManager sessionManager, - ILibraryManager libraryManager, - ISyncPlayManager syncPlayManager) + ILibraryManager libraryManager) { _logger = logger; _userManager = userManager; _sessionManager = sessionManager; _libraryManager = libraryManager; - _syncPlayManager = syncPlayManager; _state = new IdleGroupState(_logger); } @@ -168,7 +160,7 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> /// <param name="from">The current session.</param> /// <param name="type">The filtering type.</param> - /// <returns>The array of sessions matching the filter.</returns> + /// <returns>The list of sessions matching the filter.</returns> private IEnumerable<SessionInfo> FilterSessions(SessionInfo from, SyncPlayBroadcastType type) { return type switch @@ -209,7 +201,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="user">The user.</param> /// <param name="queue">The queue.</param> /// <returns><c>true</c> if the user can access all the items in the queue, <c>false</c> otherwise.</returns> - private bool HasAccessToQueue(User user, IEnumerable<Guid> queue) + private bool HasAccessToQueue(User user, IReadOnlyList<Guid> queue) { // Check if queue is empty. if (!queue?.Any() ?? true) @@ -234,7 +226,7 @@ namespace Emby.Server.Implementations.SyncPlay return true; } - private bool AllUsersHaveAccessToQueue(IEnumerable<Guid> queue) + private bool AllUsersHaveAccessToQueue(IReadOnlyList<Guid> queue) { // Check if queue is empty. if (!queue?.Any() ?? true) @@ -262,7 +254,6 @@ namespace Emby.Server.Implementations.SyncPlay { GroupName = request.GroupName; AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); var sessionIsPlayingAnItem = session.FullNowPlayingItem != null; @@ -270,7 +261,7 @@ namespace Emby.Server.Implementations.SyncPlay if (sessionIsPlayingAnItem) { - var playlist = session.NowPlayingQueue.Select(item => item.Id); + var playlist = session.NowPlayingQueue.Select(item => item.Id).ToList(); PlayQueue.Reset(); PlayQueue.SetPlaylist(playlist); PlayQueue.SetPlayingItemById(session.FullNowPlayingItem.Id); @@ -290,14 +281,13 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("InitGroup: {0} created group {1}.", session.Id, GroupId.ToString()); + _logger.LogInformation("InitGroup: {SessionId} created group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { AddSession(session); - _syncPlayManager.AddSessionToGroup(session, this); var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); @@ -307,7 +297,7 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionJoin: {0} joined group {1}.", session.Id, GroupId.ToString()); + _logger.LogInformation("SessionJoin: {SessionId} joined group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -321,7 +311,7 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionRestore: {0} re-joined group {1}.", session.Id, GroupId.ToString()); + _logger.LogInformation("SessionRestore: {SessionId} re-joined group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -330,7 +320,6 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionLeaving(this, _state.Type, session, cancellationToken); RemoveSession(session); - _syncPlayManager.RemoveSessionFromGroup(session, this); var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, GroupId.ToString()); SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); @@ -338,7 +327,7 @@ namespace Emby.Server.Implementations.SyncPlay var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - _logger.LogInformation("SessionLeave: {0} left group {1}.", session.Id, GroupId.ToString()); + _logger.LogInformation("SessionLeave: {SessionId} left group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -347,27 +336,21 @@ namespace Emby.Server.Implementations.SyncPlay // The server's job is to maintain a consistent state for clients to reference // and notify clients of state changes. The actual syncing of media playback // happens client side. Clients are aware of the server's time and use it to sync. - _logger.LogInformation("HandleRequest: {0} requested {1}, group {2} in {3} state.", session.Id, request.Type, GroupId.ToString(), _state.Type); + _logger.LogInformation("HandleRequest: {SessionId} requested {RequestType}, group {GroupId} is {StateType}.", session.Id, request.Type, GroupId.ToString(), _state.Type); request.Apply(this, _state, session, cancellationToken); } /// <inheritdoc /> public GroupInfoDto GetInfo() { - return new GroupInfoDto() - { - GroupId = GroupId.ToString(), - GroupName = GroupName, - State = _state.Type, - Participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(), - LastUpdatedAt = DateTime.UtcNow - }; + var participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(); + return new GroupInfoDto(GroupId, GroupName, _state.Type, participants, DateTime.UtcNow); } /// <inheritdoc /> public bool HasAccessToPlayQueue(User user) { - var items = PlayQueue.GetPlaylist().Select(item => item.ItemId); + var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToList(); return HasAccessToQueue(user, items); } @@ -383,7 +366,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetState(IGroupState state) { - _logger.LogInformation("SetState: {0} switching from {1} to {2}.", GroupId.ToString(), _state.Type, state.Type); + _logger.LogInformation("SetState: {GroupId} switching from {FromStateType} to {ToStateType}.", GroupId.ToString(), _state.Type, state.Type); this._state = state; } @@ -418,26 +401,19 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public SendCommand NewSyncPlayCommand(SendCommandType type) { - return new SendCommand() - { - GroupId = GroupId.ToString(), - PlaylistItemId = PlayQueue.GetPlayingItemPlaylistId(), - PositionTicks = PositionTicks, - Command = type, - When = LastActivity, - EmittedAt = DateTime.UtcNow - }; + return new SendCommand( + GroupId, + PlayQueue.GetPlayingItemPlaylistId(), + LastActivity, + type, + PositionTicks, + DateTime.UtcNow); } /// <inheritdoc /> public GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data) { - return new GroupUpdate<T>() - { - GroupId = GroupId.ToString(), - Type = type, - Data = data - }; + return new GroupUpdate<T>(GroupId, type, data); } /// <inheritdoc /> @@ -501,10 +477,10 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool SetPlayQueue(IEnumerable<Guid> playQueue, int playingItemPosition, long startPositionTicks) + public bool SetPlayQueue(IReadOnlyList<Guid> playQueue, int playingItemPosition, long startPositionTicks) { // Ignore on empty queue or invalid item position. - if (!playQueue.Any() || playingItemPosition >= playQueue.Count() || playingItemPosition < 0) + if (playQueue.Count == 0 || playingItemPosition >= playQueue.Count || playingItemPosition < 0) { return false; } @@ -547,7 +523,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool RemoveFromPlayQueue(IEnumerable<string> playlistItemIds) + public bool RemoveFromPlayQueue(IReadOnlyList<string> playlistItemIds) { var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds); if (playingItemRemoved) @@ -576,10 +552,10 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool AddToPlayQueue(IEnumerable<Guid> newItems, GroupQueueMode mode) + public bool AddToPlayQueue(IReadOnlyList<Guid> newItems, GroupQueueMode mode) { // Ignore on empty list. - if (!newItems.Any()) + if (newItems.Count == 0) { return false; } @@ -673,16 +649,14 @@ namespace Emby.Server.Implementations.SyncPlay startPositionTicks += Math.Max(elapsedTime.Ticks, 0); } - return new PlayQueueUpdate() - { - Reason = reason, - LastUpdate = PlayQueue.LastChange, - Playlist = PlayQueue.GetPlaylist(), - PlayingItemIndex = PlayQueue.PlayingItemIndex, - StartPositionTicks = startPositionTicks, - ShuffleMode = PlayQueue.ShuffleMode, - RepeatMode = PlayQueue.RepeatMode - }; + return new PlayQueueUpdate( + reason, + PlayQueue.LastChange, + PlayQueue.GetPlaylist(), + PlayQueue.PlayingItemIndex, + startPositionTicks, + PlayQueue.ShuffleMode, + PlayQueue.RepeatMode); } } } diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 178536631e..ee75580cc1 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -72,19 +72,9 @@ namespace Emby.Server.Implementations.SyncPlay _userManager = userManager; _sessionManager = sessionManager; _libraryManager = libraryManager; - _sessionManager.SessionStarted += OnSessionManagerSessionStarted; - _sessionManager.SessionEnded += OnSessionManagerSessionEnded; - _sessionManager.PlaybackStart += OnSessionManagerPlaybackStart; - _sessionManager.PlaybackStopped += OnSessionManagerPlaybackStopped; } - /// <summary> - /// Gets all groups. - /// </summary> - /// <value>All groups.</value> - public IEnumerable<IGroupController> Groups => _groups.Values; - /// <inheritdoc /> public void Dispose() { @@ -92,127 +82,6 @@ namespace Emby.Server.Implementations.SyncPlay GC.SuppressFinalize(this); } - /// <summary> - /// Releases unmanaged and optionally managed resources. - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) - { - if (_disposed) - { - return; - } - - _sessionManager.SessionStarted -= OnSessionManagerSessionStarted; - _sessionManager.SessionEnded -= OnSessionManagerSessionEnded; - _sessionManager.PlaybackStart -= OnSessionManagerPlaybackStart; - _sessionManager.PlaybackStopped -= OnSessionManagerPlaybackStopped; - - _disposed = true; - } - - private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) - { - var session = e.SessionInfo; - if (!IsSessionInGroup(session)) - { - return; - } - - var groupId = GetSessionGroup(session) ?? Guid.Empty; - var request = new JoinGroupRequest() - { - GroupId = groupId - }; - JoinGroup(session, groupId, request, CancellationToken.None); - } - - private void OnSessionManagerSessionEnded(object sender, SessionEventArgs e) - { - var session = e.SessionInfo; - if (!IsSessionInGroup(session)) - { - return; - } - - // TODO: probably remove this event, not used at the moment. - } - - private void OnSessionManagerPlaybackStart(object sender, PlaybackProgressEventArgs e) - { - var session = e.Session; - if (!IsSessionInGroup(session)) - { - return; - } - - // TODO: probably remove this event, not used at the moment. - } - - private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e) - { - var session = e.Session; - if (!IsSessionInGroup(session)) - { - return; - } - - // TODO: probably remove this event, not used at the moment. - } - - private bool IsRequestValid<T>(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true) - { - if (session == null || (request == null && checkRequest)) - { - return false; - } - - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess == SyncPlayAccess.None) - { - _logger.LogWarning("IsRequestValid: {0} does not have access to SyncPlay. Requested {1}.", session.Id, requestType); - - var error = new GroupUpdate<string>() - { - // TODO: rename to a more generic error. Next PR will fix this. - Type = GroupUpdateType.JoinGroupDenied - }; - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return false; - } - - if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) - { - _logger.LogWarning("IsRequestValid: {0} does not have permission to create groups.", session.Id); - - var error = new GroupUpdate<string> - { - Type = GroupUpdateType.CreateGroupDenied - }; - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return false; - } - - return true; - } - - private bool IsRequestValid(SessionInfo session, GroupRequestType requestType) - { - return IsRequestValid(session, requestType, session, false); - } - - private bool IsSessionInGroup(SessionInfo session) - { - return _sessionToGroupMap.ContainsKey(session.Id); - } - - private Guid? GetSessionGroup(SessionInfo session) - { - _sessionToGroupMap.TryGetValue(session.Id, out var group); - return group?.GroupId; - } - /// <inheritdoc /> public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { @@ -229,9 +98,10 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } - var group = new GroupController(_logger, _userManager, _sessionManager, _libraryManager, this); + var group = new GroupController(_logger, _userManager, _sessionManager, _libraryManager); _groups[group.GroupId] = group; + AddSessionToGroup(session, group); group.CreateGroup(session, request, cancellationToken); } } @@ -253,25 +123,18 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("JoinGroup: {0} tried to join group {0} that does not exist.", session.Id, groupId); + _logger.LogWarning("JoinGroup: {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId); - var error = new GroupUpdate<string>() - { - Type = GroupUpdateType.GroupDoesNotExist - }; + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } if (!group.HasAccessToPlayQueue(user)) { - _logger.LogWarning("JoinGroup: {0} does not have access to some content from the playing queue of group {1}.", session.Id, group.GroupId.ToString()); + _logger.LogWarning("JoinGroup: {SessionId} does not have access to some content from the playing queue of group {GroupId}.", session.Id, group.GroupId.ToString()); - var error = new GroupUpdate<string>() - { - GroupId = group.GroupId.ToString(), - Type = GroupUpdateType.LibraryAccessDenied - }; + var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -287,6 +150,7 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } + AddSessionToGroup(session, group); group.SessionJoin(session, request, cancellationToken); } } @@ -307,21 +171,19 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("LeaveGroup: {0} does not belong to any group.", session.Id); + _logger.LogWarning("LeaveGroup: {SessionId} does not belong to any group.", session.Id); - var error = new GroupUpdate<string>() - { - Type = GroupUpdateType.NotInGroup - }; + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } + RemoveSessionFromGroup(session, group); group.SessionLeave(session, cancellationToken); if (group.IsGroupEmpty()) { - _logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GroupId); + _logger.LogInformation("LeaveGroup: removing empty group {GroupId}.", group.GroupId); _groups.Remove(group.GroupId, out _); } } @@ -338,11 +200,14 @@ namespace Emby.Server.Implementations.SyncPlay var user = _userManager.GetUserById(session.UserId); - return _groups - .Values - .Where(group => group.HasAccessToPlayQueue(user)) - .Select(group => group.GetInfo()) - .ToList(); + lock (_groupsLock) + { + return _groups + .Values + .Where(group => group.HasAccessToPlayQueue(user)) + .Select(group => group.GetInfo()) + .ToList(); + } } /// <inheritdoc /> @@ -360,12 +225,9 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("HandleRequest: {0} does not belong to any group.", session.Id); + _logger.LogWarning("HandleRequest: {SessionId} does not belong to any group.", session.Id); - var error = new GroupUpdate<string>() - { - Type = GroupUpdateType.NotInGroup - }; + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } @@ -374,8 +236,74 @@ namespace Emby.Server.Implementations.SyncPlay } } - /// <inheritdoc /> - public void AddSessionToGroup(SessionInfo session, IGroupController group) + /// <summary> + /// Releases unmanaged and optionally managed resources. + /// </summary> + /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> + protected virtual void Dispose(bool disposing) + { + if (_disposed) + { + return; + } + + _sessionManager.SessionStarted -= OnSessionManagerSessionStarted; + _disposed = true; + } + + private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) + { + var session = e.SessionInfo; + lock (_groupsLock) + { + if (!IsSessionInGroup(session)) + { + return; + } + + var groupId = GetSessionGroup(session); + var request = new JoinGroupRequest(groupId); + JoinGroup(session, groupId, request, CancellationToken.None); + } + } + + /// <summary> + /// Checks if a given session has joined a group. + /// </summary> + /// <remarks> + /// Not thread-safe, call only under groups-lock. + /// </remarks> + /// <param name="session">The session.</param> + /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns> + private bool IsSessionInGroup(SessionInfo session) + { + return _sessionToGroupMap.ContainsKey(session.Id); + } + + /// <summary> + /// Gets the group joined by the given session, if any. + /// </summary> + /// <remarks> + /// Not thread-safe, call only under groups-lock. + /// </remarks> + /// <param name="session">The session.</param> + /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns> + private Guid GetSessionGroup(SessionInfo session) + { + _sessionToGroupMap.TryGetValue(session.Id, out var group); + return group?.GroupId ?? Guid.Empty; + } + + /// <summary> + /// Maps a session to a group. + /// </summary> + /// <remarks> + /// Not thread-safe, call only under groups-lock. + /// </remarks> + /// <param name="session">The session.</param> + /// <param name="group">The group.</param> + /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> + private void AddSessionToGroup(SessionInfo session, IGroupController group) { if (session == null) { @@ -390,8 +318,16 @@ namespace Emby.Server.Implementations.SyncPlay _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); } - /// <inheritdoc /> - public void RemoveSessionFromGroup(SessionInfo session, IGroupController group) + /// <summary> + /// Unmaps a session from a group. + /// </summary> + /// <remarks> + /// Not thread-safe, call only under groups-lock. + /// </remarks> + /// <param name="session">The session.</param> + /// <param name="group">The group.</param> + /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> + private void RemoveSessionFromGroup(SessionInfo session, IGroupController group) { if (session == null) { @@ -414,5 +350,55 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Session was in wrong group!"); } } + + /// <summary> + /// Checks if a given session is allowed to make a given request. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="requestType">The request type.</param> + /// <param name="request">The request.</param> + /// <param name="checkRequest">Whether to check if request is null.</param> + /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns> + private bool IsRequestValid<T>(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true) + { + if (session == null || (request == null && checkRequest)) + { + return false; + } + + var user = _userManager.GetUserById(session.UserId); + + if (user.SyncPlayAccess == SyncPlayAccess.None) + { + _logger.LogWarning("IsRequestValid: {SessionId} does not have access to SyncPlay. Requested {RequestType}.", session.Id, requestType); + + // TODO: rename to a more generic error. Next PR will fix this. + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return false; + } + + if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) + { + _logger.LogWarning("IsRequestValid: {SessionId} does not have permission to create groups.", session.Id); + + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.CreateGroupDenied, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return false; + } + + return true; + } + + /// <summary> + /// Checks if a given session is allowed to make a given type of request. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="requestType">The request type.</param> + /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns> + private bool IsRequestValid(SessionInfo session, GroupRequestType requestType) + { + return IsRequestValid(session, requestType, session, false); + } } } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 9085a71c88..8e9314b4aa 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -53,10 +53,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string groupName) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var newGroupRequest = new NewGroupRequest() - { - GroupName = groupName - }; + var newGroupRequest = new NewGroupRequest(groupName); _syncPlayManager.NewGroup(currentSession, newGroupRequest, CancellationToken.None); return NoContent(); } @@ -73,10 +70,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] Guid groupId) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var joinRequest = new JoinGroupRequest() - { - GroupId = groupId - }; + var joinRequest = new JoinGroupRequest(groupId); _syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None); return NoContent(); } @@ -185,18 +179,18 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to queue items to the playlist of a SyncPlay group. /// </summary> - /// <param name="items">The items to add.</param> + /// <param name="itemIds">The items to add.</param> /// <param name="mode">The mode in which to enqueue the items.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayQueue( - [FromQuery, Required] Guid[] items, + [FromQuery, Required] Guid[] itemIds, [FromQuery, Required] GroupQueueMode mode) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new QueueGroupRequest(items, mode); + var syncPlayRequest = new QueueGroupRequest(itemIds, mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } diff --git a/Jellyfin.Api/Controllers/TimeSyncController.cs b/Jellyfin.Api/Controllers/TimeSyncController.cs index 2dc744e7ca..5de5604173 100644 --- a/Jellyfin.Api/Controllers/TimeSyncController.cs +++ b/Jellyfin.Api/Controllers/TimeSyncController.cs @@ -13,7 +13,7 @@ namespace Jellyfin.Api.Controllers public class TimeSyncController : BaseJellyfinApiController { /// <summary> - /// Gets the current utc time. + /// Gets the current UTC time. /// </summary> /// <response code="200">Time returned.</response> /// <returns>An <see cref="UtcTimeResponse"/> to sync the client and server time.</returns> @@ -22,18 +22,14 @@ namespace Jellyfin.Api.Controllers public ActionResult<UtcTimeResponse> GetUtcTime() { // Important to keep the following line at the beginning - var requestReceptionTime = DateTime.UtcNow.ToUniversalTime().ToString("o", DateTimeFormatInfo.InvariantInfo); + var requestReceptionTime = DateTime.UtcNow.ToUniversalTime(); - var response = new UtcTimeResponse(); - response.RequestReceptionTime = requestReceptionTime; - - // Important to keep the following two lines at the end - var responseTransmissionTime = DateTime.UtcNow.ToUniversalTime().ToString("o", DateTimeFormatInfo.InvariantInfo); - response.ResponseTransmissionTime = responseTransmissionTime; + // Important to keep the following line at the end + var responseTransmissionTime = DateTime.UtcNow.ToUniversalTime(); // Implementing NTP on such a high level results in this useless // information being sent. On the other hand it enables future additions. - return response; + return new UtcTimeResponse(requestReceptionTime, responseTransmissionTime); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index bc2e223802..e5da0ef40f 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -68,7 +68,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (playingItemRemoved && !context.PlayQueue.IsItemPlaying()) { - Logger.LogDebug("HandleRequest: {0} in group {1}, play queue is empty.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, play queue is empty.", request.Type, context.GroupId.ToString()); IGroupState idleState = new IdleGroupState(Logger); context.SetState(idleState); @@ -84,7 +84,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!result) { - Logger.LogError("HandleRequest: {0} in group {1}, unable to move item in play queue.", request.Type, context.GroupId.ToString()); + Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to move item in play queue.", request.Type, context.GroupId.ToString()); return; } @@ -100,7 +100,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!result) { - Logger.LogError("HandleRequest: {0} in group {1}, unable to add items to play queue.", request.Type, context.GroupId.ToString()); + Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to add items to play queue.", request.Type, context.GroupId.ToString()); return; } @@ -203,18 +203,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates protected void SendGroupStateUpdate(IGroupStateContext context, IGroupPlaybackRequest reason, SessionInfo session, CancellationToken cancellationToken) { // Notify relevant state change event. - var stateUpdate = new GroupStateUpdate() - { - State = Type, - Reason = reason.Type - }; + var stateUpdate = new GroupStateUpdate(Type, reason.Type); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); } private void UnhandledRequest(IGroupPlaybackRequest request) { - Logger.LogWarning("HandleRequest: unhandled {0} request for {1} state.", request.Type, Type); + Logger.LogWarning("HandleRequest: unhandled {RequestType} request in {StateType} state.", request.Type, Type); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index 78318dd94d..e33e711fb7 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -103,7 +103,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var unpauseRequest = new UnpauseGroupRequest(); playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); - Logger.LogDebug("SessionLeaving: {0} left the group {1}, notifying others to resume.", session.Id, context.GroupId.ToString()); + Logger.LogDebug("SessionLeaving: {SessionId} left group {GroupId}, notifying others to resume.", session.Id, context.GroupId.ToString()); } else { @@ -111,7 +111,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var pausedState = new PausedGroupState(Logger); context.SetState(pausedState); - Logger.LogDebug("SessionLeaving: {0} left the group {1}, returning to previous state.", session.Id, context.GroupId.ToString()); + Logger.LogDebug("SessionLeaving: {SessionId} left group {GroupId}, returning to previous state.", session.Id, context.GroupId.ToString()); } } } @@ -131,7 +131,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks); if (!setQueueStatus) { - Logger.LogError("HandleRequest: {0} in group {1}, unable to set playing queue.", request.Type, context.GroupId.ToString()); + Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to set playing queue.", request.Type, context.GroupId.ToString()); // Ignore request and return to previous state. IGroupState newState = prevState switch { @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - Logger.LogDebug("HandleRequest: {0} in group {1}, {2} set a new play queue.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} set a new play queue.", request.Type, context.GroupId.ToString(), session.Id); } /// <inheritdoc /> @@ -188,7 +188,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SetState(newState); - Logger.LogDebug("HandleRequest: {0} in group {1}, unable to change current playing item.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, unable to change current playing item.", request.Type, context.GroupId.ToString()); } } @@ -214,13 +214,13 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - Logger.LogDebug("HandleRequest: {0} in group {1}, waiting for all ready events.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, waiting for all ready events.", request.Type, context.GroupId.ToString()); } else { if (ResumePlaying) { - Logger.LogDebug("HandleRequest: {0} in group {1}, ignoring sessions that are not ready and forcing the playback to start.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, ignoring sessions that are not ready and forcing the playback to start.", request.Type, context.GroupId.ToString()); // An Unpause request is forcing the playback to start, ignoring sessions that are not ready. context.SetAllBuffering(false); @@ -326,7 +326,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var updateSession = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -400,7 +400,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {0} in group {1}, {2} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -420,7 +420,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks; if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks) { - Logger.LogWarning("HandleRequest: {0} in group {1}, {2} is not time syncing properly. Ignoring elapsed time.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is not time syncing properly. Ignoring elapsed time.", request.Type, context.GroupId.ToString(), session.Id); elapsedTime = TimeSpan.Zero; } @@ -436,7 +436,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var delayTicks = context.PositionTicks - clientPosition.Ticks; var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks; - Logger.LogDebug("HandleRequest: {0} in group {1}, {2} at {3} (delay of {4} seconds).", request.Type, context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} at {PositionTicks} (delay of {Delay} seconds).", request.Type, context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); if (ResumePlaying) { @@ -454,7 +454,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - Logger.LogWarning("HandleRequest: {0} in group {1}, {2} got lost in time, correcting.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} got lost in time, correcting.", request.Type, context.GroupId.ToString(), session.Id); return; } @@ -468,7 +468,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates command.When = currentTime.AddTicks(delayTicks); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - Logger.LogInformation("HandleRequest: {0} in group {1}, others still buffering, {2} will pause when ready in {3} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogInformation("HandleRequest: {RequestType} in group {GroupId}, others still buffering, {SessionId} will pause when ready in {Delay} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -487,7 +487,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SendCommand(session, filter, command, cancellationToken); - Logger.LogInformation("HandleRequest: {0} in group {1}, {2} is recovering, notifying others to resume in {3} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogInformation("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is recovering, notifying others to resume in {Delay} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -500,7 +500,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - Logger.LogWarning("HandleRequest: {0} in group {1}, {2} resumed playback but did not update others in time. {3} seconds to recover.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} resumed playback but did not update others in time. {Delay} seconds to recover.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); } // Change state. @@ -511,7 +511,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } else { - // Check that session is really ready, tollerate player imperfections under a certain threshold. + // Check that session is really ready, tolerate player imperfections under a certain threshold. if (Math.Abs(context.PositionTicks - requestTicks) > maxPlaybackOffsetTicks) { // Session still not ready. @@ -523,7 +523,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - Logger.LogWarning("HandleRequest: {0} in group {1}, {2} was seeking to wrong position, correcting.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is seeking to wrong position, correcting.", request.Type, context.GroupId.ToString(), session.Id); return; } else @@ -549,7 +549,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates pausedState.HandleRequest(context, Type, request, session, cancellationToken); } - Logger.LogDebug("HandleRequest: {0} in group {1}, {2} is ready, returning to previous state.", request.Type, context.GroupId.ToString(), session.Id); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is ready, returning to previous state.", request.Type, context.GroupId.ToString(), session.Id); } } } @@ -569,7 +569,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} provided the wrong playlist identifier.", request.Type, context.GroupId.ToString(), session.Id); return; } @@ -596,7 +596,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SetState(newState); - Logger.LogDebug("HandleRequest: {0} in group {1}, no next track available.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, no next track available.", request.Type, context.GroupId.ToString()); } } @@ -615,7 +615,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {0} in group {1}, client provided the wrong playlist identifier.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} provided the wrong playlist identifier.", request.Type, context.GroupId.ToString(), session.Id); return; } @@ -642,7 +642,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SetState(newState); - Logger.LogDebug("HandleRequest: {0} in group {1}, no previous track available.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, no previous track available.", request.Type, context.GroupId.ToString()); } } @@ -653,7 +653,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!context.IsBuffering()) { - Logger.LogDebug("HandleRequest: {0} in group {1}, returning to previous state.", request.Type, context.GroupId.ToString()); + Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, returning to previous state.", request.Type, context.GroupId.ToString()); if (ResumePlaying) { diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs index 3609be36b7..13f1b23169 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs @@ -151,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="playingItemPosition">The playing item position in the play queue.</param> /// <param name="startPositionTicks">The start position ticks.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool SetPlayQueue(IEnumerable<Guid> playQueue, int playingItemPosition, long startPositionTicks); + bool SetPlayQueue(IReadOnlyList<Guid> playQueue, int playingItemPosition, long startPositionTicks); /// <summary> /// Sets the playing item. @@ -165,7 +165,7 @@ namespace MediaBrowser.Controller.SyncPlay /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - bool RemoveFromPlayQueue(IEnumerable<string> playlistItemIds); + bool RemoveFromPlayQueue(IReadOnlyList<string> playlistItemIds); /// <summary> /// Moves an item in the play queue. @@ -181,7 +181,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="newItems">The new items to add to the play queue.</param> /// <param name="mode">The mode with which the items will be added.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool AddToPlayQueue(IEnumerable<Guid> newItems, GroupQueueMode mode); + bool AddToPlayQueue(IReadOnlyList<Guid> newItems, GroupQueueMode mode); /// <summary> /// Restarts current item in play queue. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 65146d4ae8..a980016827 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -49,21 +49,5 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Maps a session to a group. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="group">The group.</param> - /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> - void AddSessionToGroup(SessionInfo session, IGroupController group); - - /// <summary> - /// Unmaps a session from a group. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="group">The group.</param> - /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> - void RemoveSessionFromGroup(SessionInfo session, IGroupController group); } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index 306c161ed9..7d27f61518 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -19,9 +19,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="startPositionTicks">The start position ticks.</param> public PlayGroupRequest(Guid[] playingQueue, int playingItemPosition, long startPositionTicks) { - var list = new List<Guid>(); - list.AddRange(playingQueue); - PlayingQueue = list; + PlayingQueue = playingQueue ?? Array.Empty<Guid>(); PlayingItemPosition = playingItemPosition; StartPositionTicks = startPositionTicks; } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index 9580b53154..106daecc8c 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -18,9 +18,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="mode">The enqueue mode.</param> public QueueGroupRequest(Guid[] items, GroupQueueMode mode) { - var list = new List<Guid>(); - list.AddRange(items); - ItemIds = list; + ItemIds = items ?? Array.Empty<Guid>(); Mode = mode; } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index 21c602846e..1e892d8196 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading; using MediaBrowser.Controller.Session; @@ -16,9 +17,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="items">The playlist ids of the items to remove.</param> public RemoveFromPlaylistGroupRequest(string[] items) { - var list = new List<string>(); - list.AddRange(items); - PlaylistItemIds = list; + PlaylistItemIds = items ?? Array.Empty<string>(); } /// <summary> diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 2d1d1533b9..73457f4471 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -94,7 +94,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Sets a new playlist. Playing item is reset. /// </summary> /// <param name="items">The new items of the playlist.</param> - public void SetPlaylist(IEnumerable<Guid> items) + public void SetPlaylist(IReadOnlyList<Guid> items) { SortedPlaylist.Clear(); ShuffledPlaylist.Clear(); @@ -114,7 +114,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Appends new items to the playlist. The specified order is mantained. /// </summary> /// <param name="items">The items to add to the playlist.</param> - public void Queue(IEnumerable<Guid> items) + public void Queue(IReadOnlyList<Guid> items) { var newItems = CreateQueueItemsFromArray(items); @@ -209,7 +209,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Adds new items to the playlist right after the playing item. The specified order is mantained. /// </summary> /// <param name="items">The items to add to the playlist.</param> - public void QueueNext(IEnumerable<Guid> items) + public void QueueNext(IReadOnlyList<Guid> items) { var newItems = CreateQueueItemsFromArray(items); @@ -312,13 +312,12 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - public bool RemoveFromPlaylist(IEnumerable<string> playlistItemIds) + public bool RemoveFromPlaylist(IReadOnlyList<string> playlistItemIds) { var playingItem = GetPlayingItem(); - var playlistItemIdsList = playlistItemIds.ToList(); - SortedPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); - ShuffledPlaylist.RemoveAll(item => playlistItemIdsList.Contains(item.PlaylistItemId)); + SortedPlaylist.RemoveAll(item => playlistItemIds.Contains(item.PlaylistItemId)); + ShuffledPlaylist.RemoveAll(item => playlistItemIds.Contains(item.PlaylistItemId)); LastChange = DateTime.UtcNow; @@ -369,8 +368,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue var queueItem = playlist[oldIndex]; playlist.RemoveAt(oldIndex); - newIndex = Math.Min(newIndex, playlist.Count); - newIndex = Math.Max(newIndex, 0); + newIndex = Math.Clamp(newIndex, 0, playlist.Count); playlist.Insert(newIndex, queueItem); LastChange = DateTime.UtcNow; @@ -489,7 +487,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue } else { - PlayingItemIndex--; + PlayingItemIndex = SortedPlaylist.Count - 1; return false; } } @@ -519,7 +517,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue } else { - PlayingItemIndex++; + PlayingItemIndex = 0; return false; } } @@ -558,7 +556,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Creates a list from the array of items. Each item is given an unique playlist identifier. /// </summary> /// <returns>The list of queue items.</returns> - private List<QueueItem> CreateQueueItemsFromArray(IEnumerable<Guid> items) + private List<QueueItem> CreateQueueItemsFromArray(IReadOnlyList<Guid> items) { var list = new List<QueueItem>(); foreach (var item in items) diff --git a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs index 16a75eb68e..8c0960b830 100644 --- a/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs +++ b/MediaBrowser.Model/SyncPlay/GroupInfoDto.cs @@ -11,41 +11,48 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="GroupInfoDto"/> class. /// </summary> - public GroupInfoDto() + /// <param name="groupId">The group identifier.</param> + /// <param name="groupName">The group name.</param> + /// <param name="state">The group state.</param> + /// <param name="participants">The participants.</param> + /// <param name="lastUpdatedAt">The date when this DTO has been created.</param> + public GroupInfoDto(Guid groupId, string groupName, GroupStateType state, IReadOnlyList<string> participants, DateTime lastUpdatedAt) { - GroupId = string.Empty; - GroupName = string.Empty; - Participants = new List<string>(); + GroupId = groupId; + GroupName = groupName; + State = state; + Participants = participants; + LastUpdatedAt = lastUpdatedAt; } /// <summary> - /// Gets or sets the group identifier. + /// Gets the group identifier. /// </summary> /// <value>The group identifier.</value> - public string GroupId { get; set; } + public Guid GroupId { get; } /// <summary> - /// Gets or sets the group name. + /// Gets the group name. /// </summary> /// <value>The group name.</value> - public string GroupName { get; set; } + public string GroupName { get; } /// <summary> - /// Gets or sets the group state. + /// Gets the group state. /// </summary> /// <value>The group state.</value> - public GroupStateType State { get; set; } + public GroupStateType State { get; } /// <summary> - /// Gets or sets the participants. + /// Gets the participants. /// </summary> /// <value>The participants.</value> - public IReadOnlyList<string> Participants { get; set; } + public IReadOnlyList<string> Participants { get; } /// <summary> - /// Gets or sets the date when this dto has been updated. + /// Gets the date when this DTO has been created. /// </summary> - /// <value>The date when this dto has been updated.</value> - public DateTime LastUpdatedAt { get; set; } + /// <value>The date when this DTO has been created.</value> + public DateTime LastUpdatedAt { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs index 532b5a56f4..7f7deb86bb 100644 --- a/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/GroupStateUpdate.cs @@ -6,15 +6,26 @@ namespace MediaBrowser.Model.SyncPlay public class GroupStateUpdate { /// <summary> - /// Gets or sets the state of the group. + /// Initializes a new instance of the <see cref="GroupStateUpdate"/> class. /// </summary> - /// <value>The state of the group.</value> - public GroupStateType State { get; set; } + /// <param name="state">The state of the group.</param> + /// <param name="reason">The reason of the state change.</param> + public GroupStateUpdate(GroupStateType state, PlaybackRequestType reason) + { + State = state; + Reason = reason; + } /// <summary> - /// Gets or sets the reason of the state change. + /// Gets the state of the group. + /// </summary> + /// <value>The state of the group.</value> + public GroupStateType State { get; } + + /// <summary> + /// Gets the reason of the state change. /// </summary> /// <value>The reason of the state change.</value> - public PlaybackRequestType Reason { get; set; } + public PlaybackRequestType Reason { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs index 12d6058ac3..6f159d653c 100644 --- a/MediaBrowser.Model/SyncPlay/GroupUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/GroupUpdate.cs @@ -1,4 +1,4 @@ -#nullable disable +using System; namespace MediaBrowser.Model.SyncPlay { @@ -9,21 +9,34 @@ namespace MediaBrowser.Model.SyncPlay public class GroupUpdate<T> { /// <summary> - /// Gets or sets the group identifier. + /// Initializes a new instance of the <see cref="GroupUpdate{T}"/> class. + /// </summary> + /// <param name="groupId">The group identifier.</param> + /// <param name="type">The update type.</param> + /// <param name="data">The update data.</param> + public GroupUpdate(Guid groupId, GroupUpdateType type, T data) + { + GroupId = groupId; + Type = type; + Data = data; + } + + /// <summary> + /// Gets the group identifier. /// </summary> /// <value>The group identifier.</value> - public string GroupId { get; set; } + public Guid GroupId { get; } /// <summary> - /// Gets or sets the update type. + /// Gets the update type. /// </summary> /// <value>The update type.</value> - public GroupUpdateType Type { get; set; } + public GroupUpdateType Type { get; } /// <summary> - /// Gets or sets the data. + /// Gets the update data. /// </summary> - /// <value>The data.</value> - public T Data { get; set; } + /// <value>The update data.</value> + public T Data { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs index 27a29b8998..7402c4ce29 100644 --- a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs +++ b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs @@ -8,9 +8,18 @@ namespace MediaBrowser.Model.SyncPlay public class JoinGroupRequest { /// <summary> - /// Gets or sets the group identifier. + /// Initializes a new instance of the <see cref="JoinGroupRequest"/> class. + /// </summary> + /// <param name="groupId">The identifier of the group to join.</param> + public JoinGroupRequest(Guid groupId) + { + GroupId = groupId; + } + + /// <summary> + /// Gets the group identifier. /// </summary> /// <value>The identifier of the group to join.</value> - public Guid GroupId { get; set; } + public Guid GroupId { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs index eb61a68d15..ba4bd3ef1c 100644 --- a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs +++ b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs @@ -8,15 +8,16 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="NewGroupRequest"/> class. /// </summary> - public NewGroupRequest() + /// <param name="groupName">The name of the new group.</param> + public NewGroupRequest(string groupName) { - GroupName = string.Empty; + GroupName = groupName; } /// <summary> - /// Gets or sets the group name. + /// Gets the group name. /// </summary> /// <value>The name of the new group.</value> - public string GroupName { get; set; } + public string GroupName { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs index d193b4c663..a851229f74 100644 --- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdate.cs @@ -11,51 +11,64 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="PlayQueueUpdate"/> class. /// </summary> - public PlayQueueUpdate() + /// <param name="reason">The reason for the update.</param> + /// <param name="lastUpdate">The UTC time of the last change to the playing queue.</param> + /// <param name="playlist">The playlist.</param> + /// <param name="playingItemIndex">The playing item index in the playlist.</param> + /// <param name="startPositionTicks">The start position ticks.</param> + /// <param name="shuffleMode">The shuffle mode.</param> + /// <param name="repeatMode">The repeat mode.</param> + public PlayQueueUpdate(PlayQueueUpdateReason reason, DateTime lastUpdate, IReadOnlyList<QueueItem> playlist, int playingItemIndex, long startPositionTicks, GroupShuffleMode shuffleMode, GroupRepeatMode repeatMode) { - Playlist = new List<QueueItem>(); + Reason = reason; + LastUpdate = lastUpdate; + Playlist = playlist; + PlayingItemIndex = playingItemIndex; + StartPositionTicks = startPositionTicks; + ShuffleMode = shuffleMode; + RepeatMode = repeatMode; } /// <summary> - /// Gets or sets the request type that originated this update. + /// Gets the request type that originated this update. /// </summary> /// <value>The reason for the update.</value> - public PlayQueueUpdateReason Reason { get; set; } + public PlayQueueUpdateReason Reason { get; } /// <summary> - /// Gets or sets the UTC time of the last change to the playing queue. + /// Gets the UTC time of the last change to the playing queue. /// </summary> /// <value>The UTC time of the last change to the playing queue.</value> - public DateTime LastUpdate { get; set; } + public DateTime LastUpdate { get; } /// <summary> - /// Gets or sets the playlist. + /// Gets the playlist. /// </summary> /// <value>The playlist.</value> - public IReadOnlyList<QueueItem> Playlist { get; set; } + public IReadOnlyList<QueueItem> Playlist { get; } /// <summary> - /// Gets or sets the playing item index in the playlist. + /// Gets the playing item index in the playlist. /// </summary> /// <value>The playing item index in the playlist.</value> - public int PlayingItemIndex { get; set; } + public int PlayingItemIndex { get; } /// <summary> - /// Gets or sets the start position ticks. + /// Gets the start position ticks. /// </summary> /// <value>The start position ticks.</value> - public long StartPositionTicks { get; set; } + public long StartPositionTicks { get; } /// <summary> - /// Gets or sets the shuffle mode. + /// Gets the shuffle mode. /// </summary> /// <value>The shuffle mode.</value> - public GroupShuffleMode ShuffleMode { get; set; } + public GroupShuffleMode ShuffleMode { get; } /// <summary> - /// Gets or sets the repeat mode. + /// Gets the repeat mode. /// </summary> /// <value>The repeat mode.</value> - public GroupRepeatMode RepeatMode { get; set; } + public GroupRepeatMode RepeatMode { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs index a3aa54b380..ab4c64130c 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommand.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs @@ -10,23 +10,33 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="SendCommand"/> class. /// </summary> - public SendCommand() + /// <param name="groupId">The group identifier.</param> + /// <param name="playlistItemId">The playlist identifier of the playing item.</param> + /// <param name="when">The UTC time when to execute the command.</param> + /// <param name="command">The command.</param> + /// <param name="positionTicks">The position ticks, for commands that require it.</param> + /// <param name="emittedAt">The UTC time when this command has been emitted.</param> + public SendCommand(Guid groupId, string playlistItemId, DateTime when, SendCommandType command, long? positionTicks, DateTime emittedAt) { - GroupId = string.Empty; - PlaylistItemId = string.Empty; + GroupId = groupId; + PlaylistItemId = playlistItemId; + When = when; + Command = command; + PositionTicks = positionTicks; + EmittedAt = emittedAt; } /// <summary> - /// Gets or sets the group identifier. + /// Gets the group identifier. /// </summary> /// <value>The group identifier.</value> - public string GroupId { get; set; } + public Guid GroupId { get; } /// <summary> - /// Gets or sets the playlist identifier of the playing item. + /// Gets the playlist identifier of the playing item. /// </summary> /// <value>The playlist identifier of the playing item.</value> - public string PlaylistItemId { get; set; } + public string PlaylistItemId { get; } /// <summary> /// Gets or sets the UTC time when to execute the command. @@ -35,21 +45,21 @@ namespace MediaBrowser.Model.SyncPlay public DateTime When { get; set; } /// <summary> - /// Gets or sets the position ticks. + /// Gets the position ticks. /// </summary> /// <value>The position ticks.</value> - public long? PositionTicks { get; set; } + public long? PositionTicks { get; } /// <summary> - /// Gets or sets the command. + /// Gets the command. /// </summary> /// <value>The command.</value> - public SendCommandType Command { get; set; } + public SendCommandType Command { get; } /// <summary> - /// Gets or sets the UTC time when this command has been emitted. + /// Gets the UTC time when this command has been emitted. /// </summary> /// <value>The UTC time when this command has been emitted.</value> - public DateTime EmittedAt { get; set; } + public DateTime EmittedAt { get; } } } diff --git a/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs b/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs index 8ec5eaab3b..219e7b1e0c 100644 --- a/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs +++ b/MediaBrowser.Model/SyncPlay/UtcTimeResponse.cs @@ -1,4 +1,4 @@ -#nullable disable +using System; namespace MediaBrowser.Model.SyncPlay { @@ -8,15 +8,26 @@ namespace MediaBrowser.Model.SyncPlay public class UtcTimeResponse { /// <summary> - /// Gets or sets the UTC time when request has been received. + /// Initializes a new instance of the <see cref="UtcTimeResponse"/> class. /// </summary> - /// <value>The UTC time when request has been received.</value> - public string RequestReceptionTime { get; set; } + /// <param name="requestReceptionTime">The UTC time when request has been received.</param> + /// <param name="responseTransmissionTime">The UTC time when response has been sent.</param> + public UtcTimeResponse(DateTime requestReceptionTime, DateTime responseTransmissionTime) + { + RequestReceptionTime = requestReceptionTime; + ResponseTransmissionTime = responseTransmissionTime; + } /// <summary> - /// Gets or sets the UTC time when response has been sent. + /// Gets the UTC time when request has been received. + /// </summary> + /// <value>The UTC time when request has been received.</value> + public DateTime RequestReceptionTime { get; } + + /// <summary> + /// Gets the UTC time when response has been sent. /// </summary> /// <value>The UTC time when response has been sent.</value> - public string ResponseTransmissionTime { get; set; } + public DateTime ResponseTransmissionTime { get; } } } From f953dd42be87b5188d476f8c8c8c7d39cd395c73 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Mon, 16 Nov 2020 01:09:14 +0800 Subject: [PATCH 0360/1930] remove unused segment option --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 2 +- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 625275171e..fc13fb8735 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1411,7 +1411,7 @@ namespace Jellyfin.Api.Controllers return string.Format( CultureInfo.InvariantCulture, - "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts 0 -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"", + "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -hls_segment_type {8} -start_number {9} -hls_segment_filename \"{10}\" -hls_playlist_type vod -hls_list_size 0 -y \"{11}\"", inputModifier, _encodingHelper.GetInputArgument(state, _encodingOptions), threads, diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 1ced08617a..aebfeab673 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -406,7 +406,7 @@ namespace Jellyfin.Api.Controllers return string.Format( CultureInfo.InvariantCulture, - "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts 0 -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -individual_header_trailer 0 -hls_segment_type {8} -start_number 0 -hls_base_url {9} -hls_playlist_type event -hls_segment_filename \"{10}\" -y \"{11}\"", + "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max_muxing_queue_size {6} -f hls -max_delay 5000000 -hls_time {7} -hls_segment_type {8} -start_number 0 -hls_base_url {9} -hls_playlist_type event -hls_segment_filename \"{10}\" -y \"{11}\"", inputModifier, _encodingHelper.GetInputArgument(state, _encodingOptions), threads, From 547ee885613591021ad5ff5595249b1f8448d742 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 10:58:39 -0700 Subject: [PATCH 0361/1930] Remove api client generator errors --- Jellyfin.Api/Controllers/AudioController.cs | 169 ++++- .../Controllers/DynamicHlsController.cs | 4 +- Jellyfin.Api/Controllers/ImageController.cs | 696 +++++++++++++++++- .../Controllers/InstantMixController.cs | 4 +- Jellyfin.Api/Controllers/ItemsController.cs | 257 ++++++- .../Controllers/SubtitleController.cs | 42 +- .../Controllers/TrailersController.cs | 1 - .../Controllers/VideoAttachmentsController.cs | 3 +- Jellyfin.Api/Controllers/VideosController.cs | 165 ++++- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- 10 files changed, 1289 insertions(+), 54 deletions(-) diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs index d4c6e4af94..330e56614d 100644 --- a/Jellyfin.Api/Controllers/AudioController.cs +++ b/Jellyfin.Api/Controllers/AudioController.cs @@ -85,15 +85,178 @@ namespace Jellyfin.Api.Controllers /// <param name="streamOptions">Optional. The streaming options.</param> /// <response code="200">Audio stream returned.</response> /// <returns>A <see cref="FileResult"/> containing the audio file.</returns> - [HttpGet("{itemId}/stream.{container:required}", Name = "GetAudioStreamByContainer")] [HttpGet("{itemId}/stream", Name = "GetAudioStream")] - [HttpHead("{itemId}/stream.{container:required}", Name = "HeadAudioStreamByContainer")] [HttpHead("{itemId}/stream", Name = "HeadAudioStream")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesAudioFile] public async Task<ActionResult> GetAudioStream( [FromRoute, Required] Guid itemId, - [FromRoute] string? container, + [FromQuery] string? container, + [FromQuery] bool? @static, + [FromQuery] string? @params, + [FromQuery] string? tag, + [FromQuery] string? deviceProfileId, + [FromQuery] string? playSessionId, + [FromQuery] string? segmentContainer, + [FromQuery] int? segmentLength, + [FromQuery] int? minSegments, + [FromQuery] string? mediaSourceId, + [FromQuery] string? deviceId, + [FromQuery] string? audioCodec, + [FromQuery] bool? enableAutoStreamCopy, + [FromQuery] bool? allowVideoStreamCopy, + [FromQuery] bool? allowAudioStreamCopy, + [FromQuery] bool? breakOnNonKeyFrames, + [FromQuery] int? audioSampleRate, + [FromQuery] int? maxAudioBitDepth, + [FromQuery] int? audioBitRate, + [FromQuery] int? audioChannels, + [FromQuery] int? maxAudioChannels, + [FromQuery] string? profile, + [FromQuery] string? level, + [FromQuery] float? framerate, + [FromQuery] float? maxFramerate, + [FromQuery] bool? copyTimestamps, + [FromQuery] long? startTimeTicks, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? videoBitRate, + [FromQuery] int? subtitleStreamIndex, + [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] int? maxRefFrames, + [FromQuery] int? maxVideoBitDepth, + [FromQuery] bool? requireAvc, + [FromQuery] bool? deInterlace, + [FromQuery] bool? requireNonAnamorphic, + [FromQuery] int? transcodingMaxAudioChannels, + [FromQuery] int? cpuCoreLimit, + [FromQuery] string? liveStreamId, + [FromQuery] bool? enableMpegtsM2TsMode, + [FromQuery] string? videoCodec, + [FromQuery] string? subtitleCodec, + [FromQuery] string? transcodingReasons, + [FromQuery] int? audioStreamIndex, + [FromQuery] int? videoStreamIndex, + [FromQuery] EncodingContext? context, + [FromQuery] Dictionary<string, string>? streamOptions) + { + StreamingRequestDto streamingRequest = new StreamingRequestDto + { + Id = itemId, + Container = container, + Static = @static ?? true, + Params = @params, + Tag = tag, + DeviceProfileId = deviceProfileId, + PlaySessionId = playSessionId, + SegmentContainer = segmentContainer, + SegmentLength = segmentLength, + MinSegments = minSegments, + MediaSourceId = mediaSourceId, + DeviceId = deviceId, + AudioCodec = audioCodec, + EnableAutoStreamCopy = enableAutoStreamCopy ?? true, + AllowAudioStreamCopy = allowAudioStreamCopy ?? true, + AllowVideoStreamCopy = allowVideoStreamCopy ?? true, + BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, + AudioSampleRate = audioSampleRate, + MaxAudioChannels = maxAudioChannels, + AudioBitRate = audioBitRate, + MaxAudioBitDepth = maxAudioBitDepth, + AudioChannels = audioChannels, + Profile = profile, + Level = level, + Framerate = framerate, + MaxFramerate = maxFramerate, + CopyTimestamps = copyTimestamps ?? true, + StartTimeTicks = startTimeTicks, + Width = width, + Height = height, + VideoBitRate = videoBitRate, + SubtitleStreamIndex = subtitleStreamIndex, + SubtitleMethod = subtitleMethod, + MaxRefFrames = maxRefFrames, + MaxVideoBitDepth = maxVideoBitDepth, + RequireAvc = requireAvc ?? true, + DeInterlace = deInterlace ?? true, + RequireNonAnamorphic = requireNonAnamorphic ?? true, + TranscodingMaxAudioChannels = transcodingMaxAudioChannels, + CpuCoreLimit = cpuCoreLimit, + LiveStreamId = liveStreamId, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + VideoCodec = videoCodec, + SubtitleCodec = subtitleCodec, + TranscodeReasons = transcodingReasons, + AudioStreamIndex = audioStreamIndex, + VideoStreamIndex = videoStreamIndex, + Context = context ?? EncodingContext.Static, + StreamOptions = streamOptions + }; + + return await _audioHelper.GetAudioStream(_transcodingJobType, streamingRequest).ConfigureAwait(false); + } + + /// <summary> + /// Gets an audio stream. + /// </summary> + /// <param name="itemId">The item id.</param> + /// <param name="container">The audio container.</param> + /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param> + /// <param name="params">The streaming parameters.</param> + /// <param name="tag">The tag.</param> + /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> + /// <param name="playSessionId">The play session id.</param> + /// <param name="segmentContainer">The segment container.</param> + /// <param name="segmentLength">The segment lenght.</param> + /// <param name="minSegments">The minimum number of segments.</param> + /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> + /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> + /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param> + /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param> + /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param> + /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param> + /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param> + /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param> + /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param> + /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param> + /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param> + /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param> + /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param> + /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param> + /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param> + /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param> + /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param> + /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param> + /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param> + /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param> + /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param> + /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param> + /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param> + /// <param name="maxRefFrames">Optional.</param> + /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> + /// <param name="requireAvc">Optional. Whether to require avc.</param> + /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> + /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> + /// <param name="liveStreamId">The live stream id.</param> + /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> + /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> + /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> + /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> + /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> + /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> + /// <param name="streamOptions">Optional. The streaming options.</param> + /// <response code="200">Audio stream returned.</response> + /// <returns>A <see cref="FileResult"/> containing the audio file.</returns> + [HttpGet("{itemId}/stream.{container}", Name = "GetAudioStreamByContainer")] + [HttpHead("{itemId}/stream.{container}", Name = "HeadAudioStreamByContainer")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesAudioFile] + public async Task<ActionResult> GetAudioStreamByContainer( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] string container, [FromQuery] bool? @static, [FromQuery] string? @params, [FromQuery] string? tag, diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index e07690e110..a6b249ccfa 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -833,7 +833,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid itemId, [FromRoute, Required] string playlistId, [FromRoute, Required] int segmentId, - [FromRoute] string container, + [FromRoute, Required] string container, [FromQuery] bool? @static, [FromQuery] string? @params, [FromQuery] string? tag, @@ -1004,7 +1004,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid itemId, [FromRoute, Required] string playlistId, [FromRoute, Required] int segmentId, - [FromRoute] string container, + [FromRoute, Required] string container, [FromQuery] bool? @static, [FromQuery] string? @params, [FromQuery] string? tag, diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 4a67c1aede..bb0f273122 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -85,7 +85,6 @@ namespace Jellyfin.Api.Controllers /// <response code="403">User does not have permission to delete the image.</response> /// <returns>A <see cref="NoContentResult"/>.</returns> [HttpPost("Users/{userId}/Images/{imageType}")] - [HttpPost("Users/{userId}/Images/{imageType}/{index?}", Name = "PostUserImage_2")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] @@ -94,7 +93,53 @@ namespace Jellyfin.Api.Controllers public async Task<ActionResult> PostUserImage( [FromRoute, Required] Guid userId, [FromRoute, Required] ImageType imageType, - [FromRoute] int? index = null) + [FromQuery] int? index = null) + { + if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) + { + return Forbid("User is not allowed to update the image."); + } + + var user = _userManager.GetUserById(userId); + await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false); + + // Handle image/png; charset=utf-8 + var mimeType = Request.ContentType.Split(';').FirstOrDefault(); + var userDataPath = Path.Combine(_serverConfigurationManager.ApplicationPaths.UserConfigurationDirectoryPath, user.Username); + if (user.ProfileImage != null) + { + await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); + } + + user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType))); + + await _providerManager + .SaveImage(memoryStream, mimeType, user.ProfileImage.Path) + .ConfigureAwait(false); + await _userManager.UpdateUserAsync(user).ConfigureAwait(false); + + return NoContent(); + } + + /// <summary> + /// Sets the user image. + /// </summary> + /// <param name="userId">User Id.</param> + /// <param name="imageType">(Unused) Image type.</param> + /// <param name="index">(Unused) Image index.</param> + /// <response code="204">Image updated.</response> + /// <response code="403">User does not have permission to delete the image.</response> + /// <returns>A <see cref="NoContentResult"/>.</returns> + [HttpPost("Users/{userId}/Images/{imageType}/{index}")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")] + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] + public async Task<ActionResult> PostUserImageByIndex( + [FromRoute, Required] Guid userId, + [FromRoute, Required] ImageType imageType, + [FromRoute] int index) { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { @@ -131,8 +176,7 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Image deleted.</response> /// <response code="403">User does not have permission to delete the image.</response> /// <returns>A <see cref="NoContentResult"/>.</returns> - [HttpDelete("Users/{userId}/Images/{itemType}")] - [HttpDelete("Users/{userId}/Images/{itemType}/{index?}", Name = "DeleteUserImage_2")] + [HttpDelete("Users/{userId}/Images/{imageType}")] [Authorize(Policy = Policies.DefaultAuthorization)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] @@ -141,7 +185,46 @@ namespace Jellyfin.Api.Controllers public async Task<ActionResult> DeleteUserImage( [FromRoute, Required] Guid userId, [FromRoute, Required] ImageType imageType, - [FromRoute] int? index = null) + [FromQuery] int? index = null) + { + if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) + { + return Forbid("User is not allowed to delete the image."); + } + + var user = _userManager.GetUserById(userId); + try + { + System.IO.File.Delete(user.ProfileImage.Path); + } + catch (IOException e) + { + _logger.LogError(e, "Error deleting user profile image:"); + } + + await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); + return NoContent(); + } + + /// <summary> + /// Delete the user's image. + /// </summary> + /// <param name="userId">User Id.</param> + /// <param name="imageType">(Unused) Image type.</param> + /// <param name="index">(Unused) Image index.</param> + /// <response code="204">Image deleted.</response> + /// <response code="403">User does not have permission to delete the image.</response> + /// <returns>A <see cref="NoContentResult"/>.</returns> + [HttpDelete("Users/{userId}/Images/{imageType}/{index}")] + [Authorize(Policy = Policies.DefaultAuthorization)] + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")] + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task<ActionResult> DeleteUserImageByIndex( + [FromRoute, Required] Guid userId, + [FromRoute, Required] ImageType imageType, + [FromRoute] int index) { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { @@ -172,14 +255,13 @@ namespace Jellyfin.Api.Controllers /// <response code="404">Item not found.</response> /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns> [HttpDelete("Items/{itemId}/Images/{imageType}")] - [HttpDelete("Items/{itemId}/Images/{imageType}/{imageIndex?}", Name = "DeleteItemImage_2")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> DeleteItemImage( [FromRoute, Required] Guid itemId, [FromRoute, Required] ImageType imageType, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -191,6 +273,65 @@ namespace Jellyfin.Api.Controllers return NoContent(); } + /// <summary> + /// Delete an item's image. + /// </summary> + /// <param name="itemId">Item id.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">The image index.</param> + /// <response code="204">Image deleted.</response> + /// <response code="404">Item not found.</response> + /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns> + [HttpDelete("Items/{itemId}/Images/{imageType}/{imageIndex}")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task<ActionResult> DeleteItemImageByIndex( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] ImageType imageType, + [FromRoute] int imageIndex) + { + var item = _libraryManager.GetItemById(itemId); + if (item == null) + { + return NotFound(); + } + + await item.DeleteImageAsync(imageType, imageIndex).ConfigureAwait(false); + return NoContent(); + } + + /// <summary> + /// Set item image. + /// </summary> + /// <param name="itemId">Item id.</param> + /// <param name="imageType">Image type.</param> + /// <response code="204">Image saved.</response> + /// <response code="404">Item not found.</response> + /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns> + [HttpPost("Items/{itemId}/Images/{imageType}")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] + public async Task<ActionResult> SetItemImage( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] ImageType imageType) + { + var item = _libraryManager.GetItemById(itemId); + if (item == null) + { + return NotFound(); + } + + // Handle image/png; charset=utf-8 + var mimeType = Request.ContentType.Split(';').FirstOrDefault(); + await _providerManager.SaveImage(item, Request.Body, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); + await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false); + + return NoContent(); + } + /// <summary> /// Set item image. /// </summary> @@ -200,16 +341,15 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Image saved.</response> /// <response code="404">Item not found.</response> /// <returns>A <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if item not found.</returns> - [HttpPost("Items/{itemId}/Images/{imageType}")] - [HttpPost("Items/{itemId}/Images/{imageType}/{imageIndex?}", Name = "SetItemImage_2")] + [HttpPost("Items/{itemId}/Images/{imageType}/{imageIndex}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] - public async Task<ActionResult> SetItemImage( + public async Task<ActionResult> SetItemImageByIndex( [FromRoute, Required] Guid itemId, [FromRoute, Required] ImageType imageType, - [FromRoute] int? imageIndex = null) + [FromRoute] int imageIndex) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -349,8 +489,6 @@ namespace Jellyfin.Api.Controllers /// </returns> [HttpGet("Items/{itemId}/Images/{imageType}")] [HttpHead("Items/{itemId}/Images/{imageType}", Name = "HeadItemImage")] - [HttpGet("Items/{itemId}/Images/{imageType}/{imageIndex?}", Name = "GetItemImage_2")] - [HttpHead("Items/{itemId}/Images/{imageType}/{imageIndex?}", Name = "HeadItemImage_2")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -371,7 +509,86 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var item = _libraryManager.GetItemById(itemId); + if (item == null) + { + return NotFound(); + } + + return await GetImageInternal( + itemId, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + item, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase)) + .ConfigureAwait(false); + } + + /// <summary> + /// Gets the item's image. + /// </summary> + /// <param name="itemId">Item id.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="format">Optional. The <see cref="ImageFormat"/> of the returned image.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("Items/{itemId}/Images/{imageType}/{imageIndex}")] + [HttpHead("Items/{itemId}/Images/{imageType}/{imageIndex}", Name = "HeadItemImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetItemImageByIndex( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] ImageType imageType, + [FromRoute] int imageIndex, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] string? tag, + [FromQuery] bool? cropWhitespace, + [FromQuery] ImageFormat? format, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -507,8 +724,8 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("Artists/{name}/Images/{imageType}/{imageIndex?}")] - [HttpHead("Artists/{name}/Images/{imageType}/{imageIndex?}", Name = "HeadArtistImage")] + [HttpGet("Artists/{name}/Images/{imageType}/{imageIndex}")] + [HttpHead("Artists/{name}/Images/{imageType}/{imageIndex}", Name = "HeadArtistImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -586,8 +803,8 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("Genres/{name}/Images/{imageType}/{imageIndex?}")] - [HttpHead("Genres/{name}/Images/{imageType}/{imageIndex?}", Name = "HeadGenreImage")] + [HttpGet("Genres/{name}/Images/{imageType}")] + [HttpHead("Genres/{name}/Images/{imageType}", Name = "HeadGenreImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -608,7 +825,86 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var item = _libraryManager.GetGenre(name); + if (item == null) + { + return NotFound(); + } + + return await GetImageInternal( + item.Id, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + item, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase)) + .ConfigureAwait(false); + } + + /// <summary> + /// Get genre image by name. + /// </summary> + /// <param name="name">Genre name.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("Genres/{name}/Images/{imageType}/{imageIndex}")] + [HttpHead("Genres/{name}/Images/{imageType}/{imageIndex}", Name = "HeadGenreImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetGenreImageByIndex( + [FromRoute, Required] string name, + [FromRoute, Required] ImageType imageType, + [FromRoute, Required] int imageIndex, + [FromQuery] string tag, + [FromQuery] ImageFormat? format, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] bool? cropWhitespace, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetGenre(name); if (item == null) @@ -665,8 +961,8 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("MusicGenres/{name}/Images/{imageType}/{imageIndex?}")] - [HttpHead("MusicGenres/{name}/Images/{imageType}/{imageIndex?}", Name = "HeadMusicGenreImage")] + [HttpGet("MusicGenres/{name}/Images/{imageType}")] + [HttpHead("MusicGenres/{name}/Images/{imageType}", Name = "HeadMusicGenreImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -687,7 +983,86 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var item = _libraryManager.GetMusicGenre(name); + if (item == null) + { + return NotFound(); + } + + return await GetImageInternal( + item.Id, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + item, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase)) + .ConfigureAwait(false); + } + + /// <summary> + /// Get music genre image by name. + /// </summary> + /// <param name="name">Music genre name.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("MusicGenres/{name}/Images/{imageType}/{imageIndex}")] + [HttpHead("MusicGenres/{name}/Images/{imageType}/{imageIndex}", Name = "HeadMusicGenreImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetMusicGenreImageByIndex( + [FromRoute, Required] string name, + [FromRoute, Required] ImageType imageType, + [FromRoute, Required] int imageIndex, + [FromQuery] string tag, + [FromQuery] ImageFormat? format, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] bool? cropWhitespace, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetMusicGenre(name); if (item == null) @@ -744,8 +1119,8 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("Persons/{name}/Images/{imageType}/{imageIndex?}")] - [HttpHead("Persons/{name}/Images/{imageType}/{imageIndex?}", Name = "HeadPersonImage")] + [HttpGet("Persons/{name}/Images/{imageType}")] + [HttpHead("Persons/{name}/Images/{imageType}", Name = "HeadPersonImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -766,7 +1141,86 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var item = _libraryManager.GetPerson(name); + if (item == null) + { + return NotFound(); + } + + return await GetImageInternal( + item.Id, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + item, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase)) + .ConfigureAwait(false); + } + + /// <summary> + /// Get person image by name. + /// </summary> + /// <param name="name">Person name.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("Persons/{name}/Images/{imageType}/{imageIndex}")] + [HttpHead("Persons/{name}/Images/{imageType}/{imageIndex}", Name = "HeadPersonImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetPersonImageByIndex( + [FromRoute, Required] string name, + [FromRoute, Required] ImageType imageType, + [FromRoute, Required] int imageIndex, + [FromQuery] string tag, + [FromQuery] ImageFormat? format, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] bool? cropWhitespace, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetPerson(name); if (item == null) @@ -823,16 +1277,16 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("Studios/{name}/Images/{imageType}/{imageIndex?}")] - [HttpHead("Studios/{name}/Images/{imageType}/{imageIndex?}", Name = "HeadStudioImage")] + [HttpGet("Studios/{name}/Images/{imageType}")] + [HttpHead("Studios/{name}/Images/{imageType}", Name = "HeadStudioImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] public async Task<ActionResult> GetStudioImage( [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, - [FromRoute, Required] string tag, - [FromRoute, Required] ImageFormat format, + [FromQuery] string? tag, + [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, [FromQuery] double? percentPlayed, @@ -845,7 +1299,86 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var item = _libraryManager.GetStudio(name); + if (item == null) + { + return NotFound(); + } + + return await GetImageInternal( + item.Id, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + item, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase)) + .ConfigureAwait(false); + } + + /// <summary> + /// Get studio image by name. + /// </summary> + /// <param name="name">Studio name.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("Studios/{name}/Images/{imageType}/{imageIndex}")] + [HttpHead("Studios/{name}/Images/{imageType}/{imageIndex}", Name = "HeadStudioImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetStudioImageByIndex( + [FromRoute, Required] string name, + [FromRoute, Required] ImageType imageType, + [FromRoute, Required] int imageIndex, + [FromQuery] string? tag, + [FromQuery] ImageFormat? format, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] bool? cropWhitespace, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetStudio(name); if (item == null) @@ -902,8 +1435,8 @@ namespace Jellyfin.Api.Controllers /// A <see cref="FileStreamResult"/> containing the file stream on success, /// or a <see cref="NotFoundResult"/> if item not found. /// </returns> - [HttpGet("Users/{userId}/Images/{imageType}/{imageIndex?}")] - [HttpHead("Users/{userId}/Images/{imageType}/{imageIndex?}", Name = "HeadUserImage")] + [HttpGet("Users/{userId}/Images/{imageType}")] + [HttpHead("Users/{userId}/Images/{imageType}", Name = "HeadUserImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] @@ -924,7 +1457,104 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute] int? imageIndex = null) + [FromQuery] int? imageIndex) + { + var user = _userManager.GetUserById(userId); + if (user == null) + { + return NotFound(); + } + + var info = new ItemImageInfo + { + Path = user.ProfileImage.Path, + Type = ImageType.Profile, + DateModified = user.ProfileImage.LastModified + }; + + if (width.HasValue) + { + info.Width = width.Value; + } + + if (height.HasValue) + { + info.Height = height.Value; + } + + return await GetImageInternal( + user.Id, + imageType, + imageIndex, + tag, + format, + maxWidth, + maxHeight, + percentPlayed, + unplayedCount, + width, + height, + quality, + cropWhitespace, + addPlayedIndicator, + blur, + backgroundColor, + foregroundLayer, + null, + Request.Method.Equals(HttpMethods.Head, StringComparison.OrdinalIgnoreCase), + info) + .ConfigureAwait(false); + } + + /// <summary> + /// Get user profile image. + /// </summary> + /// <param name="userId">User id.</param> + /// <param name="imageType">Image type.</param> + /// <param name="imageIndex">Image index.</param> + /// <param name="tag">Optional. Supply the cache tag from the item object to receive strong caching headers.</param> + /// <param name="format">Determines the output format of the image - original,gif,jpg,png.</param> + /// <param name="maxWidth">The maximum image width to return.</param> + /// <param name="maxHeight">The maximum image height to return.</param> + /// <param name="percentPlayed">Optional. Percent to render for the percent played overlay.</param> + /// <param name="unplayedCount">Optional. Unplayed count overlay to render.</param> + /// <param name="width">The fixed image width to return.</param> + /// <param name="height">The fixed image height to return.</param> + /// <param name="quality">Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases.</param> + /// <param name="cropWhitespace">Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art.</param> + /// <param name="addPlayedIndicator">Optional. Add a played indicator.</param> + /// <param name="blur">Optional. Blur image.</param> + /// <param name="backgroundColor">Optional. Apply a background color for transparent images.</param> + /// <param name="foregroundLayer">Optional. Apply a foreground layer on top of the image.</param> + /// <response code="200">Image stream returned.</response> + /// <response code="404">Item not found.</response> + /// <returns> + /// A <see cref="FileStreamResult"/> containing the file stream on success, + /// or a <see cref="NotFoundResult"/> if item not found. + /// </returns> + [HttpGet("Users/{userId}/Images/{imageType}/{imageIndex}")] + [HttpHead("Users/{userId}/Images/{imageType}/{imageIndex}", Name = "HeadUserImageByIndex")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + public async Task<ActionResult> GetUserImageByIndex( + [FromRoute, Required] Guid userId, + [FromRoute, Required] ImageType imageType, + [FromRoute, Required] int imageIndex, + [FromQuery] string? tag, + [FromQuery] ImageFormat? format, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] double? percentPlayed, + [FromQuery] int? unplayedCount, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? quality, + [FromQuery] bool? cropWhitespace, + [FromQuery] bool? addPlayedIndicator, + [FromQuery] int? blur, + [FromQuery] string? backgroundColor, + [FromQuery] string? foregroundLayer) { var user = _userManager.GetUserById(userId); if (user == null) diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index d17a26db43..efb0ae19bf 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -206,7 +206,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> /// <response code="200">Instant playlist returned.</response> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns> - [HttpGet("Artists/InstantMix")] + [HttpGet("Artists/{id}/InstantMix")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromArtists( [FromRoute, Required] Guid id, @@ -242,7 +242,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> /// <response code="200">Instant playlist returned.</response> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the playlist items.</returns> - [HttpGet("MusicGenres/InstantMix")] + [HttpGet("MusicGenres/{id}/InstantMix")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetInstantMixFromMusicGenres( [FromRoute, Required] Guid id, diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index d8d371ebc3..63985c72af 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -60,7 +60,6 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Gets items based on a query. /// </summary> - /// <param name="uId">The user id supplied in the /Users/{uid}/Items.</param> /// <param name="userId">The user id supplied as query parameter.</param> /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param> /// <param name="hasThemeSong">Optional filter by items with theme songs.</param> @@ -143,10 +142,8 @@ namespace Jellyfin.Api.Controllers /// <param name="enableImages">Optional, include image information in output.</param> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns> [HttpGet("Items")] - [HttpGet("Users/{uId}/Items", Name = "GetItems_2")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetItems( - [FromRoute] Guid? uId, [FromQuery] Guid? userId, [FromQuery] string? maxOfficialRating, [FromQuery] bool? hasThemeSong, @@ -228,9 +225,6 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { - // use user id route parameter over query parameter - userId = uId ?? userId; - var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; @@ -505,6 +499,257 @@ namespace Jellyfin.Api.Controllers return new QueryResult<BaseItemDto> { StartIndex = startIndex.GetValueOrDefault(), TotalRecordCount = result.TotalRecordCount, Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user) }; } + /// <summary> + /// Gets items based on a query. + /// </summary> + /// <param name="userId">The user id supplied as query parameter.</param> + /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param> + /// <param name="hasThemeSong">Optional filter by items with theme songs.</param> + /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param> + /// <param name="hasSubtitles">Optional filter by items with subtitles.</param> + /// <param name="hasSpecialFeature">Optional filter by items with special features.</param> + /// <param name="hasTrailer">Optional filter by items with trailers.</param> + /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param> + /// <param name="parentIndexNumber">Optional filter by parent index number.</param> + /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param> + /// <param name="isHd">Optional filter by items that are HD or not.</param> + /// <param name="is4K">Optional filter by items that are 4K or not.</param> + /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.</param> + /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimeted.</param> + /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param> + /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param> + /// <param name="minCommunityRating">Optional filter by minimum community rating.</param> + /// <param name="minCriticRating">Optional filter by minimum critic rating.</param> + /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param> + /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param> + /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param> + /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param> + /// <param name="hasOverview">Optional filter by items that have an overview or not.</param> + /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param> + /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param> + /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param> + /// <param name="excludeItemIds">Optional. If specified, results will be filtered by exxcluding item ids. This allows multiple, comma delimeted.</param> + /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> + /// <param name="limit">Optional. The maximum number of records to return.</param> + /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param> + /// <param name="searchTerm">Optional. Filter based on a search term.</param> + /// <param name="sortOrder">Sort Order - Ascending,Descending.</param> + /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> + /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param> + /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param> + /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> + /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param> + /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param> + /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param> + /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> + /// <param name="isPlayed">Optional filter by items that are played, or not.</param> + /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimeted.</param> + /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.</param> + /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.</param> + /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.</param> + /// <param name="enableUserData">Optional, include user data.</param> + /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> + /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> + /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param> + /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param> + /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param> + /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.</param> + /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimeted.</param> + /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimeted.</param> + /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param> + /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param> + /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param> + /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimeted.</param> + /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimeted.</param> + /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param> + /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.</param> + /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param> + /// <param name="isLocked">Optional filter by items that are locked.</param> + /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param> + /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param> + /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param> + /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param> + /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param> + /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param> + /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param> + /// <param name="is3D">Optional filter by items that are 3D, or not.</param> + /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimeted.</param> + /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param> + /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param> + /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param> + /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimeted.</param> + /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimeted.</param> + /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param> + /// <param name="enableImages">Optional, include image information in output.</param> + /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns> + [HttpGet("Users/{userId}/Items")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult<QueryResult<BaseItemDto>> GetItemsByUserId( + [FromRoute] Guid userId, + [FromQuery] string? maxOfficialRating, + [FromQuery] bool? hasThemeSong, + [FromQuery] bool? hasThemeVideo, + [FromQuery] bool? hasSubtitles, + [FromQuery] bool? hasSpecialFeature, + [FromQuery] bool? hasTrailer, + [FromQuery] string? adjacentTo, + [FromQuery] int? parentIndexNumber, + [FromQuery] bool? hasParentalRating, + [FromQuery] bool? isHd, + [FromQuery] bool? is4K, + [FromQuery] string? locationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, + [FromQuery] bool? isMissing, + [FromQuery] bool? isUnaired, + [FromQuery] double? minCommunityRating, + [FromQuery] double? minCriticRating, + [FromQuery] DateTime? minPremiereDate, + [FromQuery] DateTime? minDateLastSaved, + [FromQuery] DateTime? minDateLastSavedForUser, + [FromQuery] DateTime? maxPremiereDate, + [FromQuery] bool? hasOverview, + [FromQuery] bool? hasImdbId, + [FromQuery] bool? hasTmdbId, + [FromQuery] bool? hasTvdbId, + [FromQuery] string? excludeItemIds, + [FromQuery] int? startIndex, + [FromQuery] int? limit, + [FromQuery] bool? recursive, + [FromQuery] string? searchTerm, + [FromQuery] string? sortOrder, + [FromQuery] string? parentId, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, + [FromQuery] string? excludeItemTypes, + [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, + [FromQuery] bool? isFavorite, + [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, + [FromQuery] string? sortBy, + [FromQuery] bool? isPlayed, + [FromQuery] string? genres, + [FromQuery] string? officialRatings, + [FromQuery] string? tags, + [FromQuery] string? years, + [FromQuery] bool? enableUserData, + [FromQuery] int? imageTypeLimit, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, + [FromQuery] string? person, + [FromQuery] string? personIds, + [FromQuery] string? personTypes, + [FromQuery] string? studios, + [FromQuery] string? artists, + [FromQuery] string? excludeArtistIds, + [FromQuery] string? artistIds, + [FromQuery] string? albumArtistIds, + [FromQuery] string? contributingArtistIds, + [FromQuery] string? albums, + [FromQuery] string? albumIds, + [FromQuery] string? ids, + [FromQuery] string? videoTypes, + [FromQuery] string? minOfficialRating, + [FromQuery] bool? isLocked, + [FromQuery] bool? isPlaceHolder, + [FromQuery] bool? hasOfficialRating, + [FromQuery] bool? collapseBoxSetItems, + [FromQuery] int? minWidth, + [FromQuery] int? minHeight, + [FromQuery] int? maxWidth, + [FromQuery] int? maxHeight, + [FromQuery] bool? is3D, + [FromQuery] string? seriesStatus, + [FromQuery] string? nameStartsWithOrGreater, + [FromQuery] string? nameStartsWith, + [FromQuery] string? nameLessThan, + [FromQuery] string? studioIds, + [FromQuery] string? genreIds, + [FromQuery] bool enableTotalRecordCount = true, + [FromQuery] bool? enableImages = true) + { + return GetItems( + userId, + maxOfficialRating, + hasThemeSong, + hasThemeVideo, + hasSubtitles, + hasSpecialFeature, + hasTrailer, + adjacentTo, + parentIndexNumber, + hasParentalRating, + isHd, + is4K, + locationTypes, + excludeLocationTypes, + isMissing, + isUnaired, + minCommunityRating, + minCriticRating, + minPremiereDate, + minDateLastSaved, + minDateLastSavedForUser, + maxPremiereDate, + hasOverview, + hasImdbId, + hasTmdbId, + hasTvdbId, + excludeItemIds, + startIndex, + limit, + recursive, + searchTerm, + sortOrder, + parentId, + fields, + excludeItemTypes, + includeItemTypes, + filters, + isFavorite, + mediaTypes, + imageTypes, + sortBy, + isPlayed, + genres, + officialRatings, + tags, + years, + enableUserData, + imageTypeLimit, + enableImageTypes, + person, + personIds, + personTypes, + studios, + artists, + excludeArtistIds, + artistIds, + albumArtistIds, + contributingArtistIds, + albums, + albumIds, + ids, + videoTypes, + minOfficialRating, + isLocked, + isPlaceHolder, + hasOfficialRating, + collapseBoxSetItems, + minWidth, + minHeight, + maxWidth, + maxHeight, + is3D, + seriesStatus, + nameStartsWithOrGreater, + nameStartsWith, + nameLessThan, + studioIds, + genreIds, + enableTotalRecordCount, + enableImages); + } + /// <summary> /// Gets items based on a query. /// </summary> diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index a01ae31a0e..dcb8e803b8 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -193,7 +193,6 @@ namespace Jellyfin.Api.Controllers /// <response code="200">File returned.</response> /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns> [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{format}")] - [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks?}/Stream.{format}", Name = "GetSubtitle_2")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public async Task<ActionResult> GetSubtitle( @@ -204,7 +203,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false, - [FromRoute] long startPositionTicks = 0) + [FromQuery] long startPositionTicks = 0) { if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase)) { @@ -249,6 +248,43 @@ namespace Jellyfin.Api.Controllers MimeTypes.GetMimeType("file." + format)); } + /// <summary> + /// Gets subtitles in a specified format. + /// </summary> + /// <param name="itemId">The item id.</param> + /// <param name="mediaSourceId">The media source id.</param> + /// <param name="index">The subtitle stream index.</param> + /// <param name="startPositionTicks">Optional. The start position of the subtitle in ticks.</param> + /// <param name="format">The format of the returned subtitle.</param> + /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param> + /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param> + /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param> + /// <response code="200">File returned.</response> + /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns> + [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks}/Stream.{format}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesFile("text/*")] + public Task<ActionResult> GetSubtitleWithTicks( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] string mediaSourceId, + [FromRoute, Required] int index, + [FromRoute, Required] long startPositionTicks, + [FromRoute, Required] string format, + [FromQuery] long? endPositionTicks, + [FromQuery] bool copyTimestamps = false, + [FromQuery] bool addVttTimeMap = false) + { + return GetSubtitle( + itemId, + mediaSourceId, + index, + format, + endPositionTicks, + copyTimestamps, + addVttTimeMap, + startPositionTicks); + } + /// <summary> /// Gets an HLS subtitle playlist. /// </summary> @@ -335,6 +371,7 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Subtitle uploaded.</response> /// <returns>A <see cref="NoContentResult"/>.</returns> [HttpPost("Videos/{itemId}/Subtitles")] + [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task<ActionResult> UploadSubtitle( [FromRoute, Required] Guid itemId, [FromBody, Required] UploadSubtitleDto body) @@ -446,6 +483,7 @@ namespace Jellyfin.Api.Controllers [HttpGet("FallbackFont/Fonts/{name}")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesFile("font/*")] public ActionResult GetFallbackFont([FromRoute, Required] string name) { var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index d78adcbcdc..ffdbb15df4 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -197,7 +197,6 @@ namespace Jellyfin.Api.Controllers return _itemsController .GetItems( - userId, userId, maxOfficialRating, hasThemeSong, diff --git a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs index 418c0c1230..c2bb0dfffe 100644 --- a/Jellyfin.Api/Controllers/VideoAttachmentsController.cs +++ b/Jellyfin.Api/Controllers/VideoAttachmentsController.cs @@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations; using System.Net.Mime; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Api.Attributes; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -43,7 +44,7 @@ namespace Jellyfin.Api.Controllers /// <response code="404">Video or attachment not found.</response> /// <returns>An <see cref="FileStreamResult"/> containing the attachment stream on success, or a <see cref="NotFoundResult"/> if the attachment could not be found.</returns> [HttpGet("{videoId}/{mediaSourceId}/Attachments/{index}")] - [Produces(MediaTypeNames.Application.Octet)] + [ProducesFile(MediaTypeNames.Application.Octet)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> GetAttachment( diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 4de7aac71d..1a23076f14 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -326,15 +326,13 @@ namespace Jellyfin.Api.Controllers /// <param name="streamOptions">Optional. The streaming options.</param> /// <response code="200">Video stream returned.</response> /// <returns>A <see cref="FileResult"/> containing the audio file.</returns> - [HttpGet("{itemId}/{stream=stream}.{container?}", Name = "GetVideoStreamWithExt")] [HttpGet("{itemId}/stream")] - [HttpHead("{itemId}/{stream=stream}.{container?}", Name = "HeadVideoStreamWithExt")] [HttpHead("{itemId}/stream", Name = "HeadVideoStream")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesVideoFile] public async Task<ActionResult> GetVideoStream( [FromRoute, Required] Guid itemId, - [FromRoute] string? container, + [FromQuery] string? container, [FromQuery] bool? @static, [FromQuery] string? @params, [FromQuery] string? tag, @@ -529,5 +527,166 @@ namespace Jellyfin.Api.Controllers _transcodingJobType, cancellationTokenSource).ConfigureAwait(false); } + + /// <summary> + /// Gets a video stream. + /// </summary> + /// <param name="itemId">The item id.</param> + /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, mpg, avi, 3gp, wmv, wtv, m2ts, mov, iso, flv. </param> + /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use either no url extension or the original file extension. true/false.</param> + /// <param name="params">The streaming parameters.</param> + /// <param name="tag">The tag.</param> + /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> + /// <param name="playSessionId">The play session id.</param> + /// <param name="segmentContainer">The segment container.</param> + /// <param name="segmentLength">The segment lenght.</param> + /// <param name="minSegments">The minimum number of segments.</param> + /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> + /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> + /// <param name="audioCodec">Optional. Specify a audio codec to encode to, e.g. mp3. If omitted the server will auto-select using the url's extension. Options: aac, mp3, vorbis, wma.</param> + /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the original source. Defaults to true.</param> + /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param> + /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param> + /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param> + /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param> + /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param> + /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param> + /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param> + /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param> + /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, high.</param> + /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param> + /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param> + /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally this should be omitted unless the device has specific requirements.</param> + /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to false.</param> + /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param> + /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param> + /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param> + /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be left to encoder defaults.</param> + /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.</param> + /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param> + /// <param name="maxRefFrames">Optional.</param> + /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> + /// <param name="requireAvc">Optional. Whether to require avc.</param> + /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> + /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> + /// <param name="liveStreamId">The live stream id.</param> + /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> + /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> + /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> + /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> + /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> + /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> + /// <param name="streamOptions">Optional. The streaming options.</param> + /// <response code="200">Video stream returned.</response> + /// <returns>A <see cref="FileResult"/> containing the audio file.</returns> + [HttpGet("{itemId}/{stream=stream}.{container}")] + [HttpHead("{itemId}/{stream=stream}.{container}", Name = "HeadVideoStreamByContainer")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesVideoFile] + public Task<ActionResult> GetVideoStreamByContainer( + [FromRoute, Required] Guid itemId, + [FromRoute, Required] string container, + [FromQuery] bool? @static, + [FromQuery] string? @params, + [FromQuery] string? tag, + [FromQuery] string? deviceProfileId, + [FromQuery] string? playSessionId, + [FromQuery] string? segmentContainer, + [FromQuery] int? segmentLength, + [FromQuery] int? minSegments, + [FromQuery] string? mediaSourceId, + [FromQuery] string? deviceId, + [FromQuery] string? audioCodec, + [FromQuery] bool? enableAutoStreamCopy, + [FromQuery] bool? allowVideoStreamCopy, + [FromQuery] bool? allowAudioStreamCopy, + [FromQuery] bool? breakOnNonKeyFrames, + [FromQuery] int? audioSampleRate, + [FromQuery] int? maxAudioBitDepth, + [FromQuery] int? audioBitRate, + [FromQuery] int? audioChannels, + [FromQuery] int? maxAudioChannels, + [FromQuery] string? profile, + [FromQuery] string? level, + [FromQuery] float? framerate, + [FromQuery] float? maxFramerate, + [FromQuery] bool? copyTimestamps, + [FromQuery] long? startTimeTicks, + [FromQuery] int? width, + [FromQuery] int? height, + [FromQuery] int? videoBitRate, + [FromQuery] int? subtitleStreamIndex, + [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] int? maxRefFrames, + [FromQuery] int? maxVideoBitDepth, + [FromQuery] bool? requireAvc, + [FromQuery] bool? deInterlace, + [FromQuery] bool? requireNonAnamorphic, + [FromQuery] int? transcodingMaxAudioChannels, + [FromQuery] int? cpuCoreLimit, + [FromQuery] string? liveStreamId, + [FromQuery] bool? enableMpegtsM2TsMode, + [FromQuery] string? videoCodec, + [FromQuery] string? subtitleCodec, + [FromQuery] string? transcodingReasons, + [FromQuery] int? audioStreamIndex, + [FromQuery] int? videoStreamIndex, + [FromQuery] EncodingContext context, + [FromQuery] Dictionary<string, string> streamOptions) + { + return GetVideoStream( + itemId, + container, + @static, + @params, + tag, + deviceProfileId, + playSessionId, + segmentContainer, + segmentLength, + minSegments, + mediaSourceId, + deviceId, + audioCodec, + enableAutoStreamCopy, + allowVideoStreamCopy, + allowAudioStreamCopy, + breakOnNonKeyFrames, + audioSampleRate, + maxAudioBitDepth, + audioBitRate, + audioChannels, + maxAudioChannels, + profile, + level, + framerate, + maxFramerate, + copyTimestamps, + startTimeTicks, + width, + height, + videoBitRate, + subtitleStreamIndex, + subtitleMethod, + maxRefFrames, + maxVideoBitDepth, + requireAvc, + deInterlace, + requireNonAnamorphic, + transcodingMaxAudioChannels, + cpuCoreLimit, + liveStreamId, + enableMpegtsM2TsMode, + videoCodec, + subtitleCodec, + transcodingReasons, + audioStreamIndex, + videoStreamIndex, + context, + streamOptions); + } } } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 13234c3813..4959a9b922 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1647,7 +1647,7 @@ namespace MediaBrowser.Model.Dlna // strip spaces to avoid having to encode var values = value - .Split('|', StringSplitOptions.RemoveEmptyEntries); + .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny) { From 53697ac39a624d3a32b79883f4e0321b3a7ecb49 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 10:59:56 -0700 Subject: [PATCH 0362/1930] revert --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 4959a9b922..13234c3813 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1647,7 +1647,7 @@ namespace MediaBrowser.Model.Dlna // strip spaces to avoid having to encode var values = value - .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + .Split('|', StringSplitOptions.RemoveEmptyEntries); if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny) { From 3f313206c606662d2b5bcfa2c2a99a5c218f5ff2 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 11:35:36 -0700 Subject: [PATCH 0363/1930] Suggestions from review --- Jellyfin.Api/Helpers/HlsHelpers.cs | 2 +- .../Users/DefaultPasswordResetProvider.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 7fd784806e..45ce905668 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -48,7 +48,7 @@ namespace Jellyfin.Api.Helpers if (line == null) { // Nothing currently in buffer. - continue; + break; } if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index e71d419e0c..334f27f859 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -54,7 +54,7 @@ namespace Jellyfin.Server.Implementations.Users var usersReset = new List<string>(); foreach (var resetFile in Directory.EnumerateFiles(_passwordResetFileBaseDir, $"{BaseResetFileName}*")) { - SerializablePasswordReset? spr; + SerializablePasswordReset spr; await using (var str = File.OpenRead(resetFile)) { spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false) From 056c44010b437b0f718cb10b1ed66a7f38d61874 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 12:19:07 -0700 Subject: [PATCH 0364/1930] Fix tests --- .../ModelBinders/CommaDelimitedArrayModelBinderTests.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs index 94f2800d46..3ae6ae5bdd 100644 --- a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs +++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedArrayModelBinderTests.cs @@ -177,7 +177,7 @@ namespace Jellyfin.Api.Tests.ModelBinders { var queryParamName = "test"; var queryParamString = "🔥,😢"; - var queryParamType = typeof(TestType[]); + var queryParamType = typeof(IReadOnlyList<TestType>); var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); var valueProvider = new QueryStringValueProvider( @@ -192,7 +192,7 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Empty((TestType[])bindingContextMock.Object.Result.Model); + Assert.Empty((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model); } [Fact] @@ -201,7 +201,7 @@ namespace Jellyfin.Api.Tests.ModelBinders var queryParamName = "test"; var queryParamString1 = "How"; var queryParamString2 = "😱"; - var queryParamType = typeof(TestType[]); + var queryParamType = typeof(IReadOnlyList<TestType>); var modelBinder = new CommaDelimitedArrayModelBinder(new NullLogger<CommaDelimitedArrayModelBinder>()); @@ -220,7 +220,7 @@ namespace Jellyfin.Api.Tests.ModelBinders await modelBinder.BindModelAsync(bindingContextMock.Object); Assert.True(bindingContextMock.Object.Result.IsModelSet); - Assert.Single((TestType[])bindingContextMock.Object.Result.Model); + Assert.Single((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model); } } } From 185fac0677fd5c5ce46e5dc8156a852efb3e21c8 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 13:31:47 -0700 Subject: [PATCH 0365/1930] Upgrade all netcore3.1 to net5.0 --- .vscode/launch.json | 4 ++-- README.md | 2 +- .../Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj | 2 +- debian/control | 2 +- deployment/Dockerfile.centos.amd64 | 2 +- deployment/Dockerfile.debian.amd64 | 2 +- deployment/Dockerfile.debian.arm64 | 2 +- deployment/Dockerfile.debian.armhf | 2 +- deployment/Dockerfile.docker.amd64 | 2 +- deployment/Dockerfile.docker.arm64 | 2 +- deployment/Dockerfile.docker.armhf | 2 +- deployment/Dockerfile.fedora.amd64 | 2 +- deployment/Dockerfile.linux.amd64 | 2 +- deployment/Dockerfile.macos | 2 +- deployment/Dockerfile.portable | 2 +- deployment/Dockerfile.ubuntu.amd64 | 2 +- deployment/Dockerfile.ubuntu.arm64 | 2 +- deployment/Dockerfile.ubuntu.armhf | 2 +- deployment/Dockerfile.windows.amd64 | 2 +- deployment/build.debian.amd64 | 4 ++-- deployment/build.debian.arm64 | 4 ++-- deployment/build.debian.armhf | 4 ++-- deployment/build.ubuntu.amd64 | 4 ++-- deployment/build.ubuntu.arm64 | 4 ++-- deployment/build.ubuntu.armhf | 4 ++-- fedora/jellyfin.spec | 2 +- 26 files changed, 33 insertions(+), 33 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 05f60cfa69..e55ea22485 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,7 +6,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.1/jellyfin.dll", + "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net5.0/jellyfin.dll", "args": [], "cwd": "${workspaceFolder}/Jellyfin.Server", "console": "internalConsole", @@ -22,7 +22,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp3.1/jellyfin.dll", + "program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/net5.0/jellyfin.dll", "args": ["--nowebclient"], "cwd": "${workspaceFolder}/Jellyfin.Server", "console": "internalConsole", diff --git a/README.md b/README.md index 1786ed8de5..1ab246f84f 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ A second option is to build the project and then run the resulting executable fi ```bash dotnet build # Build the project - cd bin/Debug/netcoreapp3.1 # Change into the build output directory + cd bin/Debug/net5.0 # Change into the build output directory ``` 2. Execute the build output. On Linux, Mac, etc. use `./jellyfin` and on Windows use `jellyfin.exe`. diff --git a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj b/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj index 47aeed05ef..c564e86e9e 100644 --- a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj +++ b/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj @@ -2,7 +2,7 @@ <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> </PropertyGroup> <ItemGroup> diff --git a/debian/control b/debian/control index 9216d24fe3..9675d36ca6 100644 --- a/debian/control +++ b/debian/control @@ -3,7 +3,7 @@ Section: misc Priority: optional Maintainer: Jellyfin Team <team@jellyfin.org> Build-Depends: debhelper (>= 9), - dotnet-sdk-3.1, + dotnet-sdk-5.0, libc6-dev, libcurl4-openssl-dev, libfontconfig1-dev, diff --git a/deployment/Dockerfile.centos.amd64 b/deployment/Dockerfile.centos.amd64 index 39788cc0ee..01fc1aaac2 100644 --- a/deployment/Dockerfile.centos.amd64 +++ b/deployment/Dockerfile.centos.amd64 @@ -2,7 +2,7 @@ FROM centos:7 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index 1f28748b2f..f0d9188c17 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index 9bd51ad8c3..8132ee8873 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index fe54e5b47e..31f534838b 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.docker.amd64 b/deployment/Dockerfile.docker.amd64 index e04442606e..b61185f8c0 100644 --- a/deployment/Dockerfile.docker.amd64 +++ b/deployment/Dockerfile.docker.amd64 @@ -1,4 +1,4 @@ -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster diff --git a/deployment/Dockerfile.docker.arm64 b/deployment/Dockerfile.docker.arm64 index a7ac40492a..7420b2137a 100644 --- a/deployment/Dockerfile.docker.arm64 +++ b/deployment/Dockerfile.docker.arm64 @@ -1,4 +1,4 @@ -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster diff --git a/deployment/Dockerfile.docker.armhf b/deployment/Dockerfile.docker.armhf index b5a42f55ff..38e72ad850 100644 --- a/deployment/Dockerfile.docker.armhf +++ b/deployment/Dockerfile.docker.armhf @@ -1,4 +1,4 @@ -ARG DOTNET_VERSION=3.1 +ARG DOTNET_VERSION=5.0 FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64 index 01b99deb6d..a73f5d3cd5 100644 --- a/deployment/Dockerfile.fedora.amd64 +++ b/deployment/Dockerfile.fedora.amd64 @@ -2,7 +2,7 @@ FROM fedora:31 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 4d00bc4997..2bedafcc5a 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index 85f3fc6424..d470f9b749 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index 3253d2141a..d2007c0751 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index d4fa596a3b..084159d459 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -2,7 +2,7 @@ FROM ubuntu:bionic # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index 5fd19a2fc5..c2caf4cf8e 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -2,7 +2,7 @@ FROM ubuntu:bionic # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index d73ea92fbd..719b3a85b6 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -2,7 +2,7 @@ FROM ubuntu:bionic # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 0c99f6954d..e6905c906d 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -2,7 +2,7 @@ FROM debian:10 # Docker build arguments ARG SOURCE_DIR=/jellyfin ARG ARTIFACT_DIR=/dist -ARG SDK_VERSION=3.1 +ARG SDK_VERSION=5.0 # Docker run environment ENV SOURCE_DIR=/jellyfin ENV ARTIFACT_DIR=/dist diff --git a/deployment/build.debian.amd64 b/deployment/build.debian.amd64 index 012e1cebf6..145e28d871 100755 --- a/deployment/build.debian.amd64 +++ b/deployment/build.debian.amd64 @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/deployment/build.debian.arm64 b/deployment/build.debian.arm64 index 12ce3e874d..5699133a01 100755 --- a/deployment/build.debian.arm64 +++ b/deployment/build.debian.arm64 @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/deployment/build.debian.armhf b/deployment/build.debian.armhf index 3089eab585..20af2ddfbe 100755 --- a/deployment/build.debian.armhf +++ b/deployment/build.debian.armhf @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/deployment/build.ubuntu.amd64 b/deployment/build.ubuntu.amd64 index 0eac9cdd10..0c29286c02 100755 --- a/deployment/build.ubuntu.amd64 +++ b/deployment/build.ubuntu.amd64 @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/deployment/build.ubuntu.arm64 b/deployment/build.ubuntu.arm64 index 5b11fd543b..65d67f80f7 100755 --- a/deployment/build.ubuntu.arm64 +++ b/deployment/build.ubuntu.arm64 @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/deployment/build.ubuntu.armhf b/deployment/build.ubuntu.armhf index 4734cf6588..370370abc1 100755 --- a/deployment/build.ubuntu.armhf +++ b/deployment/build.ubuntu.armhf @@ -9,9 +9,9 @@ set -o xtrace pushd ${SOURCE_DIR} if [[ ${IS_DOCKER} == YES ]]; then - # Remove build-dep for dotnet-sdk-3.1, since it's installed manually + # Remove build-dep for dotnet-sdk-5.0, since it's installed manually cp -a debian/control /tmp/control.orig - sed -i '/dotnet-sdk-3.1,/d' debian/control + sed -i '/dotnet-sdk-5.0,/d' debian/control fi # Modify changelog to unstable configuration if IS_UNSTABLE diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 93fb9fb411..22f5949aee 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -27,7 +27,7 @@ BuildRequires: libcurl-devel, fontconfig-devel, freetype-devel, openssl-devel, # Requirements not packaged in main repos # COPR @dotnet-sig/dotnet or # https://packages.microsoft.com/rhel/7/prod/ -BuildRequires: dotnet-runtime-3.1, dotnet-sdk-3.1 +BuildRequires: dotnet-runtime-5.0, dotnet-sdk-5.0 Requires: %{name}-server = %{version}-%{release}, %{name}-web >= 10.6, %{name}-web < 10.7 # Disable Automatic Dependency Processing AutoReqProv: no From cfb7523ea8461ee4cb19ea8bb8511196d336d0e4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2020 20:47:21 +0000 Subject: [PATCH 0366/1930] Bump Moq from 4.14.7 to 4.15.1 Bumps [Moq](https://github.com/moq/moq4) from 4.14.7 to 4.15.1. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/master/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/commits) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 5bf322f071..14eed30e03 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,7 +22,7 @@ <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> - <PackageReference Include="Moq" Version="4.14.7" /> + <PackageReference Include="Moq" Version="4.15.1" /> </ItemGroup> <!-- Code Analyzers --> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index b960fda723..547f80ed96 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -17,7 +17,7 @@ <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> - <PackageReference Include="Moq" Version="4.14.7" /> + <PackageReference Include="Moq" Version="4.15.1" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> From 809556eb98d3d57ac2e5b4c50ccdccdc70389e07 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2020 20:47:32 +0000 Subject: [PATCH 0367/1930] Bump PlaylistsNET from 1.1.2 to 1.1.3 Bumps [PlaylistsNET](https://github.com/tmk907/PlaylistsNET) from 1.1.2 to 1.1.3. - [Release notes](https://github.com/tmk907/PlaylistsNET/releases) - [Commits](https://github.com/tmk907/PlaylistsNET/commits) Signed-off-by: dependabot[bot] <support@github.com> --- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index fd3f9f4c7e..accdea36e4 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -20,7 +20,7 @@ <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" /> - <PackageReference Include="PlaylistsNET" Version="1.1.2" /> + <PackageReference Include="PlaylistsNET" Version="1.1.3" /> <PackageReference Include="TMDbLib" Version="1.7.3-alpha" /> <PackageReference Include="TvDbSharper" Version="3.2.2" /> </ItemGroup> From 24839e68909d7064718344de07ccefa1ab4d0167 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2020 20:47:33 +0000 Subject: [PATCH 0368/1930] Bump Mono.Nat from 3.0.0 to 3.0.1 Bumps [Mono.Nat](https://github.com/mono/Mono.Nat) from 3.0.0 to 3.0.1. - [Release notes](https://github.com/mono/Mono.Nat/releases) - [Commits](https://github.com/mono/Mono.Nat/compare/release-v3.0.0...release-v3.0.1) Signed-off-by: dependabot[bot] <support@github.com> --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index f3052f5445..d360bb00f2 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -36,7 +36,7 @@ <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> - <PackageReference Include="Mono.Nat" Version="3.0.0" /> + <PackageReference Include="Mono.Nat" Version="3.0.1" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.0" /> <PackageReference Include="ServiceStack.Text.Core" Version="5.10.0" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> From 3432db4998ec97b2a04a59a6d77dc0827913481f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 13:51:09 -0700 Subject: [PATCH 0369/1930] dedup migration --- Jellyfin.Server/Migrations/MigrationRunner.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index 7966f03d73..ad80604c58 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -24,7 +24,6 @@ namespace Jellyfin.Server.Migrations typeof(Routines.MigrateUserDb), typeof(Routines.ReaddDefaultPluginRepository), typeof(Routines.MigrateDisplayPreferencesDb), - typeof(Routines.MigrateDisplayPreferencesDb), typeof(Routines.RemoveDownloadImagesInAdvance), typeof(Routines.DownloadTheTvdbPlugin) }; From d76afb209fb793641ff5dd72d0bf9b3a0739705d Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Sun, 15 Nov 2020 18:48:59 -0500 Subject: [PATCH 0370/1930] update dotnet 5.0 image Step 5/23 : FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster as builder manifest for mcr.microsoft.com/dotnet/sdk:5.0-buster not found: manifest unknown: manifest tagged by "5.0-buster" is not found arm not tested --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 639a1196c6..963027b49c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine- && yarn install \ && mv dist /dist -FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster as builder +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 From 81d5eb4db5918debe3194236288492f26ad135bb Mon Sep 17 00:00:00 2001 From: Ryan Petris <ryan@petris.net> Date: Sun, 15 Nov 2020 19:44:11 -0700 Subject: [PATCH 0371/1930] Return a Task object and discard it instead of using async void. --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 5a95b28b5b..4a16cda4ef 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -114,7 +114,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var taskCompletionSource = new TaskCompletionSource<bool>(); - StartStreaming( + _ = StartStreaming( udpClient, hdHomerunManager, remoteAddress, @@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun await taskCompletionSource.Task.ConfigureAwait(false); } - private async void StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken) + private async Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken) { using (udpClient) using (hdHomerunManager) From e2e10e672fb3a8f343f62b6b6ef8d5a2f1628fee Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 15 Nov 2020 21:08:02 -0700 Subject: [PATCH 0372/1930] User buster-slim instead of non existent buster --- deployment/Dockerfile.docker.amd64 | 2 +- deployment/Dockerfile.docker.arm64 | 2 +- deployment/Dockerfile.docker.armhf | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/deployment/Dockerfile.docker.amd64 b/deployment/Dockerfile.docker.amd64 index b61185f8c0..e1787acadd 100644 --- a/deployment/Dockerfile.docker.amd64 +++ b/deployment/Dockerfile.docker.amd64 @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster-slim ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin diff --git a/deployment/Dockerfile.docker.arm64 b/deployment/Dockerfile.docker.arm64 index 7420b2137a..08240111af 100644 --- a/deployment/Dockerfile.docker.arm64 +++ b/deployment/Dockerfile.docker.arm64 @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster-slim ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin diff --git a/deployment/Dockerfile.docker.armhf b/deployment/Dockerfile.docker.armhf index 38e72ad850..68c7b7d656 100644 --- a/deployment/Dockerfile.docker.armhf +++ b/deployment/Dockerfile.docker.armhf @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster-slim ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin From 099563cd6bef600be58020991731f1195545b243 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Mon, 16 Nov 2020 12:56:37 +0800 Subject: [PATCH 0373/1930] comply with dotnet-5 --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 4 ++-- Jellyfin.Api/Helpers/HlsHelpers.cs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 2e89e0b039..a4da54cfdf 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -515,7 +515,7 @@ namespace Jellyfin.Api.Helpers && state.VideoStream != null && state.VideoStream.Level.HasValue) { - levelString = state.VideoStream.Level.ToString(); + levelString = state.VideoStream.Level.ToString() ?? string.Empty; } else { @@ -557,7 +557,7 @@ namespace Jellyfin.Api.Helpers } else if (!string.IsNullOrEmpty(codec)) { - profileString = state.GetRequestedProfiles(codec).FirstOrDefault(); + profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty; if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { profileString = profileString ?? "high"; diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index d265e80b2c..1c874e4bdb 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -100,8 +100,9 @@ namespace Jellyfin.Api.Helpers /// <returns>The string text of #EXT-X-MAP.</returns> public static string GetFmp4InitFileName(string outputPath, StreamState state, bool isOsDepends) { + var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); - var outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), outputFileNameWithoutExtension); + var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension); var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); // on Linux/Unix From 5fe4ea2f4a7134d3d92de13fde7cd3570a42a772 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Mon, 16 Nov 2020 21:15:42 +0800 Subject: [PATCH 0374/1930] add video range info to title --- Emby.Server.Implementations/Localization/Core/en-US.json | 3 +++ MediaBrowser.Model/Entities/MediaStream.cs | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/Emby.Server.Implementations/Localization/Core/en-US.json b/Emby.Server.Implementations/Localization/Core/en-US.json index 6d8b222b44..f8f595faa3 100644 --- a/Emby.Server.Implementations/Localization/Core/en-US.json +++ b/Emby.Server.Implementations/Localization/Core/en-US.json @@ -9,11 +9,13 @@ "Channels": "Channels", "ChapterNameValue": "Chapter {0}", "Collections": "Collections", + "Default": "Default", "DeviceOfflineWithName": "{0} has disconnected", "DeviceOnlineWithName": "{0} is connected", "FailedLoginAttemptWithUserName": "Failed login attempt from {0}", "Favorites": "Favorites", "Folders": "Folders", + "Forced": "Forced", "Genres": "Genres", "HeaderAlbumArtists": "Album Artists", "HeaderContinueWatching": "Continue Watching", @@ -77,6 +79,7 @@ "Sync": "Sync", "System": "System", "TvShows": "TV Shows", + "Undefined": "Undefined", "User": "User", "UserCreatedWithName": "User {0} has been created", "UserDeletedWithName": "User {0} has been deleted", diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index fa3c9aaa2f..ca0b93c30f 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -191,6 +191,11 @@ namespace MediaBrowser.Model.Entities attributes.Add(Codec.ToUpperInvariant()); } + if (!string.IsNullOrEmpty(VideoRange)) + { + attributes.Add(VideoRange.ToUpperInvariant()); + } + if (!string.IsNullOrEmpty(Title)) { var result = new StringBuilder(Title); From 9481fd07476a99c30a0db99f4c6171e2fbc84a8f Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 16 Nov 2020 17:17:49 +0000 Subject: [PATCH 0375/1930] Upgraded to .Net5 --- MediaBrowser.Common/Configuration/IConfigurationManager.cs | 2 ++ MediaBrowser.Common/Net/IPNetAddress.cs | 4 ++-- MediaBrowser.Common/Net/IPObject.cs | 2 +- MediaBrowser.Controller/IServerApplicationHost.cs | 1 + 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 4c2b3a742a..790121274e 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -56,6 +56,8 @@ namespace MediaBrowser.Common.Configuration /// <summary> /// Gets the configuration. /// </summary> + /// /// <param name="key">The key.</param> + /// <returns>System.Object.</returns> object GetConfiguration(string key); /// <summary> diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index bcd049f3d5..0d28c35cb8 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -106,7 +106,7 @@ namespace MediaBrowser.Common.Net addr = addr.Trim(); // Try to parse it as is. - if (IPAddress.TryParse(addr, out IPAddress res)) + if (IPAddress.TryParse(addr, out IPAddress? res)) { ip = new IPNetAddress(res); return true; @@ -130,7 +130,7 @@ namespace MediaBrowser.Common.Net } // Is the subnet in x.y.a.b form? - if (IPAddress.TryParse(tokens[1], out IPAddress mask)) + if (IPAddress.TryParse(tokens[1], out IPAddress? mask)) { ip = new IPNetAddress(res, MaskToCidr(mask)); return true; diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index a08694c266..36f3357cce 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -381,7 +381,7 @@ namespace MediaBrowser.Common.Net } /// <inheritdoc/> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as IPObject); } diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index eced9bf697..2456da826f 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Plugins; using MediaBrowser.Model.System; +using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller { From 979de240cb758acc7866095e6a50ed5ccc6f1d38 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 16 Nov 2020 17:30:27 +0000 Subject: [PATCH 0376/1930] Updated tests to .Net5 --- Emby.Dlna/Main/DlnaEntryPoint.cs | 3 - .../Jellyfin.Networking.csproj | 2 +- .../Jellyfin.Networking.Tests.csproj | 21 ++++- .../NetworkTesting/UnitTesting.cs | 92 +++++++++++++++---- 4 files changed, 93 insertions(+), 25 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 463ed8d67a..fb4454a343 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -259,8 +259,6 @@ namespace Emby.Dlna.Main private void RegisterServerEndpoints() { - var addresses = await _appHost.GetLocalIpAddresses().ConfigureAwait(false); - var udn = CreateUuid(_appHost.SystemId); var descriptorUri = "/dlna/" + udn + "/description.xml"; @@ -292,7 +290,6 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); - var descriptorUri = "/dlna/" + udn + "/description.xml"; var uri = new Uri(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); var device = new SsdpRootDevice diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index 1747a1dc7a..cbda74361f 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -1,6 +1,6 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFramework>netstandard2.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index fa18316dff..703d43210b 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -6,23 +6,34 @@ </PropertyGroup> <PropertyGroup> - <TargetFramework>netcoreapp3.1</TargetFramework> + <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> - <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <Nullable>enable</Nullable> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> - <PackageReference Include="coverlet.collector" Version="1.2.1" /> + <PackageReference Include="coverlet.collector" Version="1.3.0" /> <PackageReference Include="Moq" Version="4.14.5" /> </ItemGroup> + <!-- Code Analyzers--> + <ItemGroup Condition=" '$(Configuration)' == 'Debug' "> + <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" /> + <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" /> + <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" /> + </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" /> <ProjectReference Include="..\..\..\MediaBrowser.Common\MediaBrowser.Common.csproj" /> </ItemGroup> - + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> + <CodeAnalysisRuleSet>../../jellyfin-tests.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> + <DefineConstants>DEBUG</DefineConstants> + </PropertyGroup> </Project> diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index c96c7defd7..03b733a9ab 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -43,8 +43,7 @@ namespace NetworkTesting return false; } - - private IConfigurationManager GetMockConfig(NetworkConfiguration conf) + private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) { var configManager = new Mock<IConfigurationManager> { @@ -64,11 +63,11 @@ namespace NetworkTesting { EnableIPV6 = true, EnableIPV4 = true, - LocalNetworkSubnets = lan.Split(';') + LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; NetworkManager.MockNetworkSettings = interfaces; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; Assert.True(string.Equals(nm.GetInternalBindAddresses().AsString(), value, StringComparison.Ordinal)); @@ -78,6 +77,11 @@ namespace NetworkTesting [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")] public void TextIsInNetwork(string network, string value) { + if (network == null) + { + throw new ArgumentNullException(nameof(network)); + } + var conf = new NetworkConfiguration() { EnableIPV6 = true, @@ -85,7 +89,7 @@ namespace NetworkTesting LocalNetworkSubnets = network.Split(',') }; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); Assert.True(!nm.IsInLocalNetwork(value)); } @@ -153,16 +157,21 @@ namespace NetworkTesting "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5) { + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } + var conf = new NetworkConfiguration() { EnableIPV6 = true, EnableIPV4 = true, }; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); // Test included, IP6. - NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); + NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); Assert.True(string.Equals(nc?.AsString(), result1, System.StringComparison.OrdinalIgnoreCase)); // Text excluded, non IP6. @@ -194,13 +203,29 @@ namespace NetworkTesting [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")] public void UnionCheck(string settings, string compare, string result) { + if (settings == null) + { + throw new ArgumentNullException(nameof(settings)); + } + + if (compare == null) + { + throw new ArgumentNullException(nameof(compare)); + } + + if (result == null) + { + throw new ArgumentNullException(nameof(result)); + } + + var conf = new NetworkConfiguration() { EnableIPV6 = true, EnableIPV4 = true, }; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false); NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false); @@ -276,12 +301,7 @@ namespace NetworkTesting { Assert.True(TryParse(network, out IPObject? networkObj)); Assert.True(TryParse(ip, out IPObject? ipObj)); - -#pragma warning disable CS8602 // Dereference of a possibly null reference. -#pragma warning disable CS8604 // Possible null reference argument. Assert.True(networkObj.Contains(ipObj)); -#pragma warning restore CS8604 // Possible null reference argument. -#pragma warning restore CS8602 // Dereference of a possibly null reference. } [Theory] @@ -293,13 +313,28 @@ namespace NetworkTesting public void TestMatches(string source, string dest, string result) { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (dest == null) + { + throw new ArgumentNullException(nameof(dest)); + } + + if (result == null) + { + throw new ArgumentNullException(nameof(result)); + } + var conf = new NetworkConfiguration() { EnableIPV6 = true, EnableIPV4 = true }; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); // Test included, IP6. NetCollection ncSource = nm.CreateIPCollection(source.Split(",")); @@ -343,6 +378,21 @@ namespace NetworkTesting [InlineData("", "", false, "eth16")] public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result) { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (bindAddresses == null) + { + throw new ArgumentNullException(nameof(bindAddresses)); + } + + if (result == null) + { + throw new ArgumentNullException(nameof(result)); + } + var conf = new NetworkConfiguration() { LocalNetworkAddresses = bindAddresses.Split(','), @@ -351,7 +401,7 @@ namespace NetworkTesting }; NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; _ = nm.TryParseInterface(result, out NetCollection? resultObj); @@ -398,6 +448,16 @@ namespace NetworkTesting public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result) { + if (lan == null) + { + throw new ArgumentNullException(nameof(lan)); + } + + if (bindAddresses == null) + { + throw new ArgumentNullException(nameof(bindAddresses)); + } + var conf = new NetworkConfiguration() { LocalNetworkSubnets = lan.Split(','), @@ -408,7 +468,7 @@ namespace NetworkTesting }; NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; - var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; if (nm.TryParseInterface(result, out NetCollection? resultObj) && resultObj != null) From a3ca36cb54a3e6e743fbcf90f19f0d76ba71aebc Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 16 Nov 2020 17:40:19 +0100 Subject: [PATCH 0377/1930] Review logging and minor changes in SyncPlay --- .../SyncPlay/GroupController.cs | 83 +++++++------- .../SyncPlay/SyncPlayManager.cs | 28 +++-- .../SyncPlay/GroupMember.cs | 13 ++- .../GroupStates/AbstractGroupState.cs | 28 +++-- .../SyncPlay/GroupStates/IdleGroupState.cs | 21 ++-- .../SyncPlay/GroupStates/PausedGroupState.cs | 29 +++-- .../SyncPlay/GroupStates/PlayingGroupState.cs | 29 +++-- .../SyncPlay/GroupStates/WaitingGroupState.cs | 105 +++++++++--------- .../SyncPlay/Queue/PlayQueueManager.cs | 32 ++---- 9 files changed, 201 insertions(+), 167 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 48596bb421..4efc671ffa 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -28,7 +28,12 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// The logger. /// </summary> - private readonly ILogger _logger; + private readonly ILogger<GroupController> _logger; + + /// <summary> + /// The logger factory. + /// </summary> + private readonly ILoggerFactory _loggerFactory; /// <summary> /// The user manager. @@ -45,6 +50,12 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> private readonly ILibraryManager _libraryManager; + /// <summary> + /// The participants, or members of the group. + /// </summary> + private readonly Dictionary<string, GroupMember> _participants = + new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase); + /// <summary> /// Internal group state. /// </summary> @@ -54,37 +65,41 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="GroupController" /> class. /// </summary> - /// <param name="logger">The logger.</param> + /// <param name="loggerFactory">The logger factory.</param> /// <param name="userManager">The user manager.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="libraryManager">The library manager.</param> public GroupController( - ILogger logger, + ILoggerFactory loggerFactory, IUserManager userManager, ISessionManager sessionManager, ILibraryManager libraryManager) { - _logger = logger; + _loggerFactory = loggerFactory; _userManager = userManager; _sessionManager = sessionManager; _libraryManager = libraryManager; + _logger = loggerFactory.CreateLogger<GroupController>(); - _state = new IdleGroupState(_logger); + _state = new IdleGroupState(loggerFactory); } /// <summary> /// Gets the default ping value used for sessions. /// </summary> + /// <value>The default ping.</value> public long DefaultPing { get; } = 500; /// <summary> /// Gets the maximum time offset error accepted for dates reported by clients, in milliseconds. /// </summary> + /// <value>The maximum time offset error.</value> public long TimeSyncOffset { get; } = 2000; /// <summary> /// Gets the maximum offset error accepted for position reported by clients, in milliseconds. /// </summary> + /// <value>The maximum offset error.</value> public long MaxPlaybackOffset { get; } = 500; /// <summary> @@ -123,24 +138,16 @@ namespace Emby.Server.Implementations.SyncPlay /// <value>The last activity.</value> public DateTime LastActivity { get; set; } - /// <summary> - /// Gets the participants. - /// </summary> - /// <value>The participants, or members of the group.</value> - public Dictionary<string, GroupMember> Participants { get; } = - new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase); - /// <summary> /// Adds the session to the group. /// </summary> /// <param name="session">The session.</param> private void AddSession(SessionInfo session) { - Participants.TryAdd( + _participants.TryAdd( session.Id, - new GroupMember + new GroupMember(session) { - Session = session, Ping = DefaultPing, IsBuffering = false }); @@ -152,7 +159,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="session">The session.</param> private void RemoveSession(SessionInfo session) { - Participants.Remove(session.Id); + _participants.Remove(session.Id); } /// <summary> @@ -166,14 +173,14 @@ namespace Emby.Server.Implementations.SyncPlay return type switch { SyncPlayBroadcastType.CurrentSession => new SessionInfo[] { from }, - SyncPlayBroadcastType.AllGroup => Participants + SyncPlayBroadcastType.AllGroup => _participants .Values .Select(session => session.Session), - SyncPlayBroadcastType.AllExceptCurrentSession => Participants + SyncPlayBroadcastType.AllExceptCurrentSession => _participants .Values .Select(session => session.Session) .Where(session => !session.Id.Equals(from.Id, StringComparison.OrdinalIgnoreCase)), - SyncPlayBroadcastType.AllReady => Participants + SyncPlayBroadcastType.AllReady => _participants .Values .Where(session => !session.IsBuffering) .Select(session => session.Session), @@ -204,7 +211,7 @@ namespace Emby.Server.Implementations.SyncPlay private bool HasAccessToQueue(User user, IReadOnlyList<Guid> queue) { // Check if queue is empty. - if (!queue?.Any() ?? true) + if (queue == null || queue.Count == 0) { return true; } @@ -229,13 +236,13 @@ namespace Emby.Server.Implementations.SyncPlay private bool AllUsersHaveAccessToQueue(IReadOnlyList<Guid> queue) { // Check if queue is empty. - if (!queue?.Any() ?? true) + if (queue == null || queue.Count == 0) { return true; } // Get list of users. - var users = Participants + var users = _participants .Values .Select(participant => _userManager.GetUserById(participant.Session.UserId)); @@ -247,7 +254,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool IsGroupEmpty() => Participants.Count == 0; + public bool IsGroupEmpty() => _participants.Count == 0; /// <inheritdoc /> public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) @@ -268,8 +275,8 @@ namespace Emby.Server.Implementations.SyncPlay RunTimeTicks = session.FullNowPlayingItem.RunTimeTicks ?? 0; PositionTicks = session.PlayState.PositionTicks ?? 0; - // Mantain playstate. - var waitingState = new WaitingGroupState(_logger) + // Maintain playstate. + var waitingState = new WaitingGroupState(_loggerFactory) { ResumePlaying = !session.PlayState.IsPaused }; @@ -281,7 +288,7 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("InitGroup: {SessionId} created group {GroupId}.", session.Id, GroupId.ToString()); + _logger.LogInformation("Session {SessionId} created group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -297,7 +304,7 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionJoin: {SessionId} joined group {GroupId}.", session.Id, GroupId.ToString()); + _logger.LogInformation("Session {SessionId} joined group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -311,7 +318,7 @@ namespace Emby.Server.Implementations.SyncPlay _state.SessionJoined(this, _state.Type, session, cancellationToken); - _logger.LogInformation("SessionRestore: {SessionId} re-joined group {GroupId}.", session.Id, GroupId.ToString()); + _logger.LogInformation("Session {SessionId} re-joined group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -327,7 +334,7 @@ namespace Emby.Server.Implementations.SyncPlay var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName); SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - _logger.LogInformation("SessionLeave: {SessionId} left group {GroupId}.", session.Id, GroupId.ToString()); + _logger.LogInformation("Session {SessionId} left group {GroupId}.", session.Id, GroupId.ToString()); } /// <inheritdoc /> @@ -336,14 +343,14 @@ namespace Emby.Server.Implementations.SyncPlay // The server's job is to maintain a consistent state for clients to reference // and notify clients of state changes. The actual syncing of media playback // happens client side. Clients are aware of the server's time and use it to sync. - _logger.LogInformation("HandleRequest: {SessionId} requested {RequestType}, group {GroupId} is {StateType}.", session.Id, request.Type, GroupId.ToString(), _state.Type); + _logger.LogInformation("Session {SessionId} requested {RequestType} in group {GroupId} that is {StateType}.", session.Id, request.Type, GroupId.ToString(), _state.Type); request.Apply(this, _state, session, cancellationToken); } /// <inheritdoc /> public GroupInfoDto GetInfo() { - var participants = Participants.Values.Select(session => session.Session.UserName).Distinct().ToList(); + var participants = _participants.Values.Select(session => session.Session.UserName).Distinct().ToList(); return new GroupInfoDto(GroupId, GroupName, _state.Type, participants, DateTime.UtcNow); } @@ -357,7 +364,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetIgnoreGroupWait(SessionInfo session, bool ignoreGroupWait) { - if (Participants.TryGetValue(session.Id, out GroupMember value)) + if (_participants.TryGetValue(session.Id, out GroupMember value)) { value.IgnoreGroupWait = ignoreGroupWait; } @@ -366,7 +373,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetState(IGroupState state) { - _logger.LogInformation("SetState: {GroupId} switching from {FromStateType} to {ToStateType}.", GroupId.ToString(), _state.Type, state.Type); + _logger.LogInformation("Group {GroupId} switching from {FromStateType} to {ToStateType}.", GroupId.ToString(), _state.Type, state.Type); this._state = state; } @@ -426,7 +433,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void UpdatePing(SessionInfo session, long ping) { - if (Participants.TryGetValue(session.Id, out GroupMember value)) + if (_participants.TryGetValue(session.Id, out GroupMember value)) { value.Ping = ping; } @@ -436,7 +443,7 @@ namespace Emby.Server.Implementations.SyncPlay public long GetHighestPing() { long max = long.MinValue; - foreach (var session in Participants.Values) + foreach (var session in _participants.Values) { max = Math.Max(max, session.Ping); } @@ -447,7 +454,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetBuffering(SessionInfo session, bool isBuffering) { - if (Participants.TryGetValue(session.Id, out GroupMember value)) + if (_participants.TryGetValue(session.Id, out GroupMember value)) { value.IsBuffering = isBuffering; } @@ -456,7 +463,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void SetAllBuffering(bool isBuffering) { - foreach (var session in Participants.Values) + foreach (var session in _participants.Values) { session.IsBuffering = isBuffering; } @@ -465,7 +472,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public bool IsBuffering() { - foreach (var session in Participants.Values) + foreach (var session in _participants.Values) { if (session.IsBuffering && !session.IgnoreGroupWait) { diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index ee75580cc1..fdaa12a04a 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -21,6 +21,11 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> private readonly ILogger<SyncPlayManager> _logger; + /// <summary> + /// The logger factory. + /// </summary> + private readonly ILoggerFactory _loggerFactory; + /// <summary> /// The user manager. /// </summary> @@ -58,20 +63,21 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// Initializes a new instance of the <see cref="SyncPlayManager" /> class. /// </summary> - /// <param name="logger">The logger.</param> + /// <param name="loggerFactory">The logger factory.</param> /// <param name="userManager">The user manager.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="libraryManager">The library manager.</param> public SyncPlayManager( - ILogger<SyncPlayManager> logger, + ILoggerFactory loggerFactory, IUserManager userManager, ISessionManager sessionManager, ILibraryManager libraryManager) { - _logger = logger; + _loggerFactory = loggerFactory; _userManager = userManager; _sessionManager = sessionManager; _libraryManager = libraryManager; + _logger = loggerFactory.CreateLogger<SyncPlayManager>(); _sessionManager.SessionStarted += OnSessionManagerSessionStarted; } @@ -98,7 +104,7 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, cancellationToken); } - var group = new GroupController(_logger, _userManager, _sessionManager, _libraryManager); + var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager); _groups[group.GroupId] = group; AddSessionToGroup(session, group); @@ -123,7 +129,7 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("JoinGroup: {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId); + _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); @@ -132,7 +138,7 @@ namespace Emby.Server.Implementations.SyncPlay if (!group.HasAccessToPlayQueue(user)) { - _logger.LogWarning("JoinGroup: {SessionId} does not have access to some content from the playing queue of group {GroupId}.", session.Id, group.GroupId.ToString()); + _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString()); var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); @@ -171,7 +177,7 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("LeaveGroup: {SessionId} does not belong to any group.", session.Id); + _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); @@ -183,7 +189,7 @@ namespace Emby.Server.Implementations.SyncPlay if (group.IsGroupEmpty()) { - _logger.LogInformation("LeaveGroup: removing empty group {GroupId}.", group.GroupId); + _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId); _groups.Remove(group.GroupId, out _); } } @@ -225,7 +231,7 @@ namespace Emby.Server.Implementations.SyncPlay if (group == null) { - _logger.LogWarning("HandleRequest: {SessionId} does not belong to any group.", session.Id); + _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); @@ -370,7 +376,7 @@ namespace Emby.Server.Implementations.SyncPlay if (user.SyncPlayAccess == SyncPlayAccess.None) { - _logger.LogWarning("IsRequestValid: {SessionId} does not have access to SyncPlay. Requested {RequestType}.", session.Id, requestType); + _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, requestType); // TODO: rename to a more generic error. Next PR will fix this. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty); @@ -380,7 +386,7 @@ namespace Emby.Server.Implementations.SyncPlay if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) { - _logger.LogWarning("IsRequestValid: {SessionId} does not have permission to create groups.", session.Id); + _logger.LogWarning("Session {SessionId} does not have permission to create groups.", session.Id); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.CreateGroupDenied, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); diff --git a/MediaBrowser.Controller/SyncPlay/GroupMember.cs b/MediaBrowser.Controller/SyncPlay/GroupMember.cs index 9a9d30277f..5fb982e85a 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupMember.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupMember.cs @@ -8,10 +8,19 @@ namespace MediaBrowser.Controller.SyncPlay public class GroupMember { /// <summary> - /// Gets or sets the session. + /// Initializes a new instance of the <see cref="GroupMember"/> class. + /// </summary> + /// <param name="session">The session.</param> + public GroupMember(SessionInfo session) + { + Session = session; + } + + /// <summary> + /// Gets the session. /// </summary> /// <value>The session.</value> - public SessionInfo Session { get; set; } + public SessionInfo Session { get; } /// <summary> /// Gets or sets the ping, in milliseconds. diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index e5da0ef40f..057488d6b4 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -14,22 +14,28 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// </remarks> public abstract class AbstractGroupState : IGroupState { + /// <summary> + /// The logger. + /// </summary> + private readonly ILogger<AbstractGroupState> _logger; + /// <summary> /// Initializes a new instance of the <see cref="AbstractGroupState"/> class. /// </summary> - /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> - protected AbstractGroupState(ILogger logger) + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + protected AbstractGroupState(ILoggerFactory loggerFactory) { - Logger = logger; + LoggerFactory = loggerFactory; + _logger = loggerFactory.CreateLogger<AbstractGroupState>(); } /// <inheritdoc /> public abstract GroupStateType Type { get; } /// <summary> - /// Gets the logger. + /// Gets the logger factory. /// </summary> - protected ILogger Logger { get; } + protected ILoggerFactory LoggerFactory { get; } /// <inheritdoc /> public abstract void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); @@ -52,7 +58,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// <inheritdoc /> public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -68,9 +74,9 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (playingItemRemoved && !context.PlayQueue.IsItemPlaying()) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, play queue is empty.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("Play queue in group {GroupId} is now empty.", context.GroupId.ToString()); - IGroupState idleState = new IdleGroupState(Logger); + IGroupState idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); var stopRequest = new StopGroupRequest(); idleState.HandleRequest(context, Type, stopRequest, session, cancellationToken); @@ -84,7 +90,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!result) { - Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to move item in play queue.", request.Type, context.GroupId.ToString()); + _logger.LogError("Unable to move item in group {GroupId}.", context.GroupId.ToString()); return; } @@ -100,7 +106,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!result) { - Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to add items to play queue.", request.Type, context.GroupId.ToString()); + _logger.LogError("Unable to add items to play queue in group {GroupId}.", context.GroupId.ToString()); return; } @@ -210,7 +216,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates private void UnhandledRequest(IGroupPlaybackRequest request) { - Logger.LogWarning("HandleRequest: unhandled {RequestType} request in {StateType} state.", request.Type, Type); + _logger.LogWarning("Unhandled request of type {RequestType} in {StateType} state.", request.Type, Type); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index 660afb607d..7730a298c2 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -14,14 +14,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// </remarks> public class IdleGroupState : AbstractGroupState { + /// <summary> + /// The logger. + /// </summary> + private readonly ILogger<IdleGroupState> _logger; + /// <summary> /// Initializes a new instance of the <see cref="IdleGroupState"/> class. /// </summary> - /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> - public IdleGroupState(ILogger logger) - : base(logger) + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + public IdleGroupState(ILoggerFactory loggerFactory) + : base(loggerFactory) { - // Do nothing. + _logger = LoggerFactory.CreateLogger<IdleGroupState>(); } /// <inheritdoc /> @@ -43,7 +48,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -52,7 +57,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -91,7 +96,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -100,7 +105,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index 29942898e6..90411f61bc 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -15,14 +15,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// </remarks> public class PausedGroupState : AbstractGroupState { + /// <summary> + /// The logger. + /// </summary> + private readonly ILogger<PausedGroupState> _logger; + /// <summary> /// Initializes a new instance of the <see cref="PausedGroupState"/> class. /// </summary> - /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> - public PausedGroupState(ILogger logger) - : base(logger) + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + public PausedGroupState(ILoggerFactory loggerFactory) + : base(loggerFactory) { - // Do nothing. + _logger = LoggerFactory.CreateLogger<PausedGroupState>(); } /// <inheritdoc /> @@ -32,7 +37,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Wait for session to be ready. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.SessionJoined(context, Type, session, cancellationToken); } @@ -47,7 +52,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -56,7 +61,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var playingState = new PlayingGroupState(Logger); + var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); playingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -96,7 +101,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var idleState = new IdleGroupState(Logger); + var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); idleState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -105,7 +110,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -114,7 +119,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -143,7 +148,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -152,7 +157,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index c5d73dedb8..aab87d9c39 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -15,14 +15,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// </remarks> public class PlayingGroupState : AbstractGroupState { + /// <summary> + /// The logger. + /// </summary> + private readonly ILogger<PlayingGroupState> _logger; + /// <summary> /// Initializes a new instance of the <see cref="PlayingGroupState"/> class. /// </summary> - /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> - public PlayingGroupState(ILogger logger) - : base(logger) + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + public PlayingGroupState(ILoggerFactory loggerFactory) + : base(loggerFactory) { - // Do nothing. + _logger = LoggerFactory.CreateLogger<PlayingGroupState>(); } /// <inheritdoc /> @@ -37,7 +42,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Wait for session to be ready. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.SessionJoined(context, Type, session, cancellationToken); } @@ -52,7 +57,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -89,7 +94,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var pausedState = new PausedGroupState(Logger); + var pausedState = new PausedGroupState(LoggerFactory); context.SetState(pausedState); pausedState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -98,7 +103,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var idleState = new IdleGroupState(Logger); + var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); idleState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -107,7 +112,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -121,7 +126,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -146,7 +151,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -155,7 +160,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. - var waitingState = new WaitingGroupState(Logger); + var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); waitingState.HandleRequest(context, Type, request, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index e33e711fb7..fefb8067fe 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -15,14 +15,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates /// </remarks> public class WaitingGroupState : AbstractGroupState { + /// <summary> + /// The logger. + /// </summary> + private readonly ILogger<WaitingGroupState> _logger; + /// <summary> /// Initializes a new instance of the <see cref="WaitingGroupState"/> class. /// </summary> - /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> - public WaitingGroupState(ILogger logger) - : base(logger) + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + public WaitingGroupState(ILoggerFactory loggerFactory) + : base(loggerFactory) { - // Do nothing. + _logger = LoggerFactory.CreateLogger<WaitingGroupState>(); } /// <inheritdoc /> @@ -97,21 +102,21 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates { if (ResumePlaying) { + _logger.LogDebug("Session {SessionId} left group {GroupId}, notifying others to resume.", session.Id, context.GroupId.ToString()); + // Client, that was buffering, left the group. - var playingState = new PlayingGroupState(Logger); + var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); - - Logger.LogDebug("SessionLeaving: {SessionId} left group {GroupId}, notifying others to resume.", session.Id, context.GroupId.ToString()); } else { - // Group is ready, returning to previous state. - var pausedState = new PausedGroupState(Logger); - context.SetState(pausedState); + _logger.LogDebug("Session {SessionId} left group {GroupId}, returning to previous state.", session.Id, context.GroupId.ToString()); - Logger.LogDebug("SessionLeaving: {SessionId} left group {GroupId}, returning to previous state.", session.Id, context.GroupId.ToString()); + // Group is ready, returning to previous state. + var pausedState = new PausedGroupState(LoggerFactory); + context.SetState(pausedState); } } } @@ -131,13 +136,13 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var setQueueStatus = context.SetPlayQueue(request.PlayingQueue, request.PlayingItemPosition, request.StartPositionTicks); if (!setQueueStatus) { - Logger.LogError("HandleRequest: {RequestType} in group {GroupId}, unable to set playing queue.", request.Type, context.GroupId.ToString()); + _logger.LogError("Unable to set playing queue in group {GroupId}.", context.GroupId.ToString()); // Ignore request and return to previous state. IGroupState newState = prevState switch { - GroupStateType.Playing => new PlayingGroupState(Logger), - GroupStateType.Paused => new PausedGroupState(Logger), - _ => new IdleGroupState(Logger) + GroupStateType.Playing => new PlayingGroupState(LoggerFactory), + GroupStateType.Paused => new PausedGroupState(LoggerFactory), + _ => new IdleGroupState(LoggerFactory) }; context.SetState(newState); @@ -151,7 +156,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} set a new play queue.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogDebug("Session {SessionId} set a new play queue in group {GroupId}.", session.Id, context.GroupId.ToString()); } /// <inheritdoc /> @@ -181,14 +186,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Return to old state. IGroupState newState = prevState switch { - GroupStateType.Playing => new PlayingGroupState(Logger), - GroupStateType.Paused => new PausedGroupState(Logger), - _ => new IdleGroupState(Logger) + GroupStateType.Playing => new PlayingGroupState(LoggerFactory), + GroupStateType.Paused => new PausedGroupState(LoggerFactory), + _ => new IdleGroupState(LoggerFactory) }; context.SetState(newState); - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, unable to change current playing item.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("Unable to change current playing item in group {GroupId}.", context.GroupId.ToString()); } } @@ -214,19 +219,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Reset status of sessions and await for all Ready events. context.SetAllBuffering(true); - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, waiting for all ready events.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("Group {GroupId} is waiting for all ready events.", context.GroupId.ToString()); } else { if (ResumePlaying) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, ignoring sessions that are not ready and forcing the playback to start.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("Forcing the playback to start in group {GroupId}. Group-wait is disabled until next state change.", context.GroupId.ToString()); // An Unpause request is forcing the playback to start, ignoring sessions that are not ready. context.SetAllBuffering(false); // Change state. - var playingState = new PlayingGroupState(Logger) + var playingState = new PlayingGroupState(LoggerFactory) { IgnoreBuffering = true }; @@ -272,7 +277,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } // Change state. - var idleState = new IdleGroupState(Logger); + var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); idleState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -326,7 +331,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString()); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var updateSession = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -400,7 +405,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client is playing the correct item. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} has wrong playlist item.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString()); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.SetCurrentItem); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); @@ -420,7 +425,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var timeSyncThresholdTicks = TimeSpan.FromMilliseconds(context.TimeSyncOffset).Ticks; if (Math.Abs(elapsedTime.Ticks) > timeSyncThresholdTicks) { - Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is not time syncing properly. Ignoring elapsed time.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogWarning("Session {SessionId} is not time syncing properly. Ignoring elapsed time.", session.Id); elapsedTime = TimeSpan.Zero; } @@ -436,7 +441,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var delayTicks = context.PositionTicks - clientPosition.Ticks; var maxPlaybackOffsetTicks = TimeSpan.FromMilliseconds(context.MaxPlaybackOffset).Ticks; - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} at {PositionTicks} (delay of {Delay} seconds).", request.Type, context.GroupId.ToString(), session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds); + _logger.LogDebug("Session {SessionId} is at {PositionTicks} (delay of {Delay} seconds) in group {GroupId}.", session.Id, clientPosition, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString()); if (ResumePlaying) { @@ -454,7 +459,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} got lost in time, correcting.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogWarning("Session {SessionId} got lost in time, correcting.", session.Id); return; } @@ -468,7 +473,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates command.When = currentTime.AddTicks(delayTicks); context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken); - Logger.LogInformation("HandleRequest: {RequestType} in group {GroupId}, others still buffering, {SessionId} will pause when ready in {Delay} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + _logger.LogInformation("Session {SessionId} will pause when ready in {Delay} seconds. Group {GroupId} is waiting for all ready events.", session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds, context.GroupId.ToString()); } else { @@ -487,7 +492,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SendCommand(session, filter, command, cancellationToken); - Logger.LogInformation("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is recovering, notifying others to resume in {Delay} seconds.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + _logger.LogInformation("Session {SessionId} is recovering, group {GroupId} will resume in {Delay} seconds.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds); } else { @@ -500,11 +505,11 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var command = context.NewSyncPlayCommand(SendCommandType.Unpause); context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken); - Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} resumed playback but did not update others in time. {Delay} seconds to recover.", request.Type, context.GroupId.ToString(), session.Id, TimeSpan.FromTicks(delayTicks).TotalSeconds); + _logger.LogWarning("Session {SessionId} resumed playback, group {GroupId} has {Delay} seconds to recover.", session.Id, context.GroupId.ToString(), TimeSpan.FromTicks(delayTicks).TotalSeconds); } // Change state. - var playingState = new PlayingGroupState(Logger); + var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); playingState.HandleRequest(context, Type, request, session, cancellationToken); } @@ -523,7 +528,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Notify relevant state change event. SendGroupStateUpdate(context, request, session, cancellationToken); - Logger.LogWarning("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is seeking to wrong position, correcting.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogWarning("Session {SessionId} is seeking to wrong position, correcting.", session.Id); return; } else @@ -534,8 +539,10 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!context.IsBuffering()) { + _logger.LogDebug("Session {SessionId} is ready, group {GroupId} is ready.", session.Id, context.GroupId.ToString()); + // Group is ready, returning to previous state. - var pausedState = new PausedGroupState(Logger); + var pausedState = new PausedGroupState(LoggerFactory); context.SetState(pausedState); if (InitialState.Equals(GroupStateType.Playing)) @@ -548,8 +555,6 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates { pausedState.HandleRequest(context, Type, request, session, cancellationToken); } - - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} is ready, returning to previous state.", request.Type, context.GroupId.ToString(), session.Id); } } } @@ -569,7 +574,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} provided the wrong playlist identifier.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString()); return; } @@ -589,14 +594,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Return to old state. IGroupState newState = prevState switch { - GroupStateType.Playing => new PlayingGroupState(Logger), - GroupStateType.Paused => new PausedGroupState(Logger), - _ => new IdleGroupState(Logger) + GroupStateType.Playing => new PlayingGroupState(LoggerFactory), + GroupStateType.Paused => new PausedGroupState(LoggerFactory), + _ => new IdleGroupState(LoggerFactory) }; context.SetState(newState); - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, no next track available.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("No next track available in group {GroupId}.", context.GroupId.ToString()); } } @@ -615,7 +620,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Make sure the client knows the playing item, to avoid duplicate requests. if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, {SessionId} provided the wrong playlist identifier.", request.Type, context.GroupId.ToString(), session.Id); + _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString()); return; } @@ -635,14 +640,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Return to old state. IGroupState newState = prevState switch { - GroupStateType.Playing => new PlayingGroupState(Logger), - GroupStateType.Paused => new PausedGroupState(Logger), - _ => new IdleGroupState(Logger) + GroupStateType.Playing => new PlayingGroupState(LoggerFactory), + GroupStateType.Paused => new PausedGroupState(LoggerFactory), + _ => new IdleGroupState(LoggerFactory) }; context.SetState(newState); - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, no previous track available.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("No previous track available in group {GroupId}.", context.GroupId.ToString()); } } @@ -653,12 +658,12 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (!context.IsBuffering()) { - Logger.LogDebug("HandleRequest: {RequestType} in group {GroupId}, returning to previous state.", request.Type, context.GroupId.ToString()); + _logger.LogDebug("Ignoring session {SessionId}, group {GroupId} is ready.", session.Id, context.GroupId.ToString()); if (ResumePlaying) { // Client, that was buffering, stopped following playback. - var playingState = new PlayingGroupState(Logger); + var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); @@ -666,7 +671,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates else { // Group is ready, returning to previous state. - var pausedState = new PausedGroupState(Logger); + var pausedState = new PausedGroupState(LoggerFactory); context.SetState(pausedState); } } diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index 73457f4471..bfb9d1e4c1 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -20,7 +20,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Random number generator used to shuffle lists. /// </summary> /// <value>The random number generator.</value> - private readonly Random randomNumberGenerator = new Random(); + private readonly Random _randomNumberGenerator = new Random(); /// <summary> /// Initializes a new instance of the <see cref="PlayQueueManager" /> class. @@ -102,7 +102,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue SortedPlaylist = CreateQueueItemsFromArray(items); if (ShuffleMode.Equals(GroupShuffleMode.Shuffle)) { - ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist = new List<QueueItem>(SortedPlaylist); Shuffle(ShuffledPlaylist); } @@ -134,17 +134,17 @@ namespace MediaBrowser.Controller.SyncPlay.Queue { if (PlayingItemIndex == NoPlayingItemIndex) { - ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist = new List<QueueItem>(SortedPlaylist); Shuffle(ShuffledPlaylist); } else if (ShuffleMode.Equals(GroupShuffleMode.Sorted)) { // First time shuffle. var playingItem = SortedPlaylist[PlayingItemIndex]; - ShuffledPlaylist = SortedPlaylist.ToList(); + ShuffledPlaylist = new List<QueueItem>(SortedPlaylist); ShuffledPlaylist.RemoveAt(PlayingItemIndex); Shuffle(ShuffledPlaylist); - ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); + ShuffledPlaylist.Insert(0, playingItem); PlayingItemIndex = 0; } else @@ -153,7 +153,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue var playingItem = ShuffledPlaylist[PlayingItemIndex]; ShuffledPlaylist.RemoveAt(PlayingItemIndex); Shuffle(ShuffledPlaylist); - ShuffledPlaylist = ShuffledPlaylist.Prepend(playingItem).ToList(); + ShuffledPlaylist.Insert(0, playingItem); PlayingItemIndex = 0; } @@ -236,14 +236,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue public string GetPlayingItemPlaylistId() { var playingItem = GetPlayingItem(); - if (playingItem != null) - { - return playingItem.PlaylistItemId; - } - else - { - return null; - } + return playingItem?.PlaylistItemId; } /// <summary> @@ -253,14 +246,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue public Guid GetPlayingItemId() { var playingItem = GetPlayingItem(); - if (playingItem != null) - { - return playingItem.ItemId; - } - else - { - return Guid.Empty; - } + return playingItem?.ItemId ?? Guid.Empty; } /// <summary> @@ -536,7 +522,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue while (n > 1) { n--; - int k = randomNumberGenerator.Next(n + 1); + int k = _randomNumberGenerator.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; From 426e258f1fb9b0e92d32b64f860f82778f11ddd6 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 16 Nov 2020 20:25:13 +0100 Subject: [PATCH 0378/1930] Improve locking logic in SyncPlay manager --- .../SyncPlay/SyncPlayManager.cs | 231 +++++++++++------- 1 file changed, 138 insertions(+), 93 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index fdaa12a04a..4df8e3ba77 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -54,10 +54,15 @@ namespace Emby.Server.Implementations.SyncPlay new Dictionary<Guid, IGroupController>(); /// <summary> - /// Lock used for accesing any group. + /// Lock used for accesing the list of groups. /// </summary> private readonly object _groupsLock = new object(); + /// <summary> + /// Lock used for accesing the session-to-group map. + /// </summary> + private readonly object _mapsLock = new object(); + private bool _disposed = false; /// <summary> @@ -97,18 +102,24 @@ namespace Emby.Server.Implementations.SyncPlay return; } + // Locking required to access list of groups. lock (_groupsLock) { - if (IsSessionInGroup(session)) + // Locking required as session-to-group map will be edited. + // Locking the group is not required as it is not visible yet. + lock (_mapsLock) { - LeaveGroup(session, cancellationToken); + if (IsSessionInGroup(session)) + { + LeaveGroup(session, cancellationToken); + } + + var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager); + _groups[group.GroupId] = group; + + AddSessionToGroup(session, group); + group.CreateGroup(session, request, cancellationToken); } - - var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager); - _groups[group.GroupId] = group; - - AddSessionToGroup(session, group); - group.CreateGroup(session, request, cancellationToken); } } @@ -123,6 +134,7 @@ namespace Emby.Server.Implementations.SyncPlay var user = _userManager.GetUserById(session.UserId); + // Locking required to access list of groups. lock (_groupsLock) { _groups.TryGetValue(groupId, out IGroupController group); @@ -136,28 +148,36 @@ namespace Emby.Server.Implementations.SyncPlay return; } - if (!group.HasAccessToPlayQueue(user)) + // Locking required as session-to-group map will be edited. + lock (_mapsLock) { - _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString()); - - var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return; - } - - if (IsSessionInGroup(session)) - { - if (GetSessionGroup(session).Equals(groupId)) + // Group lock required to let other requests end first. + lock (group) { - group.SessionRestore(session, request, cancellationToken); - return; + if (!group.HasAccessToPlayQueue(user)) + { + _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString()); + + var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return; + } + + if (IsSessionInGroup(session)) + { + if (FindJoinedGroupId(session).Equals(groupId)) + { + group.SessionRestore(session, request, cancellationToken); + return; + } + + LeaveGroup(session, cancellationToken); + } + + AddSessionToGroup(session, group); + group.SessionJoin(session, request, cancellationToken); } - - LeaveGroup(session, cancellationToken); } - - AddSessionToGroup(session, group); - group.SessionJoin(session, request, cancellationToken); } } @@ -170,27 +190,34 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // TODO: determine what happens to users that are in a group and get their permissions revoked. + // Locking required to access list of groups. lock (_groupsLock) { - _sessionToGroupMap.TryGetValue(session.Id, out var group); - - if (group == null) + // Locking required as session-to-group map will be edited. + lock (_mapsLock) { - _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); + var group = FindJoinedGroup(session); + if (group == null) + { + _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); - var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return; - } + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return; + } - RemoveSessionFromGroup(session, group); - group.SessionLeave(session, cancellationToken); + // Group lock required to let other requests end first. + lock (group) + { + RemoveSessionFromGroup(session, group); + group.SessionLeave(session, cancellationToken); - if (group.IsGroupEmpty()) - { - _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId); - _groups.Remove(group.GroupId, out _); + if (group.IsGroupEmpty()) + { + _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId); + _groups.Remove(group.GroupId, out _); + } + } } } } @@ -205,15 +232,25 @@ namespace Emby.Server.Implementations.SyncPlay } var user = _userManager.GetUserById(session.UserId); + List<GroupInfoDto> list = new List<GroupInfoDto>(); + // Locking required to access list of groups. lock (_groupsLock) { - return _groups - .Values - .Where(group => group.HasAccessToPlayQueue(user)) - .Select(group => group.GetInfo()) - .ToList(); + foreach (var group in _groups.Values) + { + // Locking required as group is not thread-safe. + lock (group) + { + if (group.HasAccessToPlayQueue(user)) + { + list.Add(group.GetInfo()); + } + } + } } + + return list; } /// <inheritdoc /> @@ -225,19 +262,19 @@ namespace Emby.Server.Implementations.SyncPlay return; } - lock (_groupsLock) + var group = FindJoinedGroup(session); + if (group == null) { - _sessionToGroupMap.TryGetValue(session.Id, out var group); + _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); - if (group == null) - { - _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); - - var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return; - } + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return; + } + // Group lock required as GroupController is not thread-safe. + lock (group) + { group.HandleRequest(session, request, cancellationToken); } } @@ -260,52 +297,57 @@ namespace Emby.Server.Implementations.SyncPlay private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) { var session = e.SessionInfo; - lock (_groupsLock) - { - if (!IsSessionInGroup(session)) - { - return; - } - var groupId = GetSessionGroup(session); - var request = new JoinGroupRequest(groupId); - JoinGroup(session, groupId, request, CancellationToken.None); + Guid groupId = FindJoinedGroupId(session); + if (groupId.Equals(Guid.Empty)) + { + return; } + + var request = new JoinGroupRequest(groupId); + JoinGroup(session, groupId, request, CancellationToken.None); } /// <summary> /// Checks if a given session has joined a group. /// </summary> - /// <remarks> - /// Not thread-safe, call only under groups-lock. - /// </remarks> /// <param name="session">The session.</param> /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns> private bool IsSessionInGroup(SessionInfo session) { - return _sessionToGroupMap.ContainsKey(session.Id); + lock (_mapsLock) + { + return _sessionToGroupMap.ContainsKey(session.Id); + } } /// <summary> /// Gets the group joined by the given session, if any. /// </summary> - /// <remarks> - /// Not thread-safe, call only under groups-lock. - /// </remarks> + /// <param name="session">The session.</param> + /// <returns>The group.</returns> + private IGroupController FindJoinedGroup(SessionInfo session) + { + lock (_mapsLock) + { + _sessionToGroupMap.TryGetValue(session.Id, out var group); + return group; + } + } + + /// <summary> + /// Gets the group identifier joined by the given session, if any. + /// </summary> /// <param name="session">The session.</param> /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns> - private Guid GetSessionGroup(SessionInfo session) + private Guid FindJoinedGroupId(SessionInfo session) { - _sessionToGroupMap.TryGetValue(session.Id, out var group); - return group?.GroupId ?? Guid.Empty; + return FindJoinedGroup(session)?.GroupId ?? Guid.Empty; } /// <summary> /// Maps a session to a group. /// </summary> - /// <remarks> - /// Not thread-safe, call only under groups-lock. - /// </remarks> /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> @@ -316,20 +358,20 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Session is null!"); } - if (IsSessionInGroup(session)) + lock (_mapsLock) { - throw new InvalidOperationException("Session in other group already!"); - } + if (IsSessionInGroup(session)) + { + throw new InvalidOperationException("Session in other group already!"); + } - _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); + _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); + } } /// <summary> /// Unmaps a session from a group. /// </summary> - /// <remarks> - /// Not thread-safe, call only under groups-lock. - /// </remarks> /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> @@ -345,15 +387,18 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Group is null!"); } - if (!IsSessionInGroup(session)) + lock (_mapsLock) { - throw new InvalidOperationException("Session not in any group!"); - } + if (!IsSessionInGroup(session)) + { + throw new InvalidOperationException("Session not in any group!"); + } - _sessionToGroupMap.Remove(session.Id, out var tempGroup); - if (!tempGroup.GroupId.Equals(group.GroupId)) - { - throw new InvalidOperationException("Session was in wrong group!"); + _sessionToGroupMap.Remove(session.Id, out var tempGroup); + if (!tempGroup.GroupId.Equals(group.GroupId)) + { + throw new InvalidOperationException("Session was in wrong group!"); + } } } From 978aa38f3bd19a55ed4f3587bf5fd7d583c317f5 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 16 Nov 2020 19:37:38 +0000 Subject: [PATCH 0379/1930] Updated PR1 code. --- .../Configuration/NetworkConfiguration.cs | 50 +++---- Jellyfin.Networking/Manager/NetworkManager.cs | 141 +++++++++--------- MediaBrowser.Common/Net/INetworkManager.cs | 38 ++--- MediaBrowser.Common/Net/IPHost.cs | 33 ++-- MediaBrowser.Common/Net/IPObject.cs | 56 +++---- MediaBrowser.Common/Net/NetworkExtensions.cs | 70 ++++----- 6 files changed, 188 insertions(+), 200 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 301e432511..e710eb3c76 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -11,12 +11,12 @@ namespace Jellyfin.Networking.Configuration public class NetworkConfiguration { /// <summary> - /// Gets the default http port. + /// The default value for <see cref="HttpServerPortNumber"/>. /// </summary> public const int DefaultHttpPort = 8096; /// <summary> - /// Gets the default https port. + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. /// </summary> public const int DefaultHttpsPort = 8920; @@ -94,124 +94,124 @@ namespace Jellyfin.Networking.Configuration public int PublicPort { get; set; } = DefaultHttpPort; /// <summary> - /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.. + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. /// </summary> public bool UPnPCreateHttpPortMap { get; set; } /// <summary> /// Gets or sets the UDPPortRange - /// Gets or sets client udp port range.. + /// Gets or sets client udp port range. /// </summary> public string UDPPortRange { get; set; } = string.Empty; /// <summary> - /// Gets or sets a value indicating whether gets or sets IPV6 capability.. + /// Gets or sets a value indicating whether gets or sets IPV6 capability. /// </summary> public bool EnableIPV6 { get; set; } /// <summary> - /// Gets or sets a value indicating whether gets or sets IPV4 capability.. + /// Gets or sets a value indicating whether gets or sets IPV4 capability. /// </summary> public bool EnableIPV4 { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. - /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. /// </summary> public bool EnableSSDPTracing { get; set; } /// <summary> /// Gets or sets the SSDPTracingFilter /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. - /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. /// </summary> public string SSDPTracingFilter { get; set; } = string.Empty; /// <summary> - /// Gets or sets the number of times SSDP UDP messages are sent.. + /// Gets or sets the number of times SSDP UDP messages are sent. /// </summary> public int UDPSendCount { get; set; } = 2; /// <summary> - /// Gets or sets the delay between each groups of SSDP messages (in ms).. + /// Gets or sets the delay between each groups of SSDP messages (in ms). /// </summary> public int UDPSendDelay { get; set; } = 100; /// <summary> - /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.. + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding. /// </summary> public bool IgnoreVirtualInterfaces { get; set; } = true; /// <summary> /// Gets or sets the VirtualInterfaceNames - /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.. + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>. /// </summary> public string VirtualInterfaceNames { get; set; } = "vEthernet*"; /// <summary> - /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.. + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. /// </summary> public int GatewayMonitorPeriod { get; set; } = 60; /// <summary> - /// Gets a value indicating whether multi-socket binding is available.. + /// Gets a value indicating whether multi-socket binding is available. /// </summary> public bool EnableMultiSocketBinding { get; } = true; /// <summary> /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. - /// Depending on the address range implemented ULA ranges might not be used.. + /// Depending on the address range implemented ULA ranges might not be used. /// </summary> public bool TrustAllIP6Interfaces { get; set; } /// <summary> - /// Gets or sets the ports that HDHomerun uses.. + /// Gets or sets the ports that HDHomerun uses. /// </summary> public string HDHomerunPortRange { get; set; } = string.Empty; /// <summary> /// Gets or sets the PublishedServerUriBySubnet - /// Gets or sets PublishedServerUri to advertise for specific subnets.. + /// Gets or sets PublishedServerUri to advertise for specific subnets. /// </summary> public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.. + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. /// </summary> public bool AutoDiscoveryTracing { get; set; } /// <summary> - /// Gets or sets a value indicating whether Autodiscovery is enabled.. + /// Gets or sets a value indicating whether Autodiscovery is enabled. /// </summary> public bool AutoDiscovery { get; set; } = true; /// <summary> - /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.. + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>. /// </summary> public string[] RemoteIPFilter { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.. + /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. /// </summary> public bool IsRemoteIPFilterBlacklist { get; set; } /// <summary> - /// Gets or sets a value indicating whether to enable automatic port forwarding.. + /// Gets or sets a value indicating whether to enable automatic port forwarding. /// </summary> public bool EnableUPnP { get; set; } /// <summary> - /// Gets or sets a value indicating whether access outside of the LAN is permitted.. + /// Gets or sets a value indicating whether access outside of the LAN is permitted. /// </summary> public bool EnableRemoteAccess { get; set; } = true; /// <summary> - /// Gets or sets the subnets that are deemed to make up the LAN.. + /// Gets or sets the subnets that are deemed to make up the LAN. /// </summary> public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.. + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. /// </summary> public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 289b1dc720..00711f1620 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,7 +1,6 @@ -#pragma warning disable CA1021 // Avoid out parameters - using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; @@ -13,14 +12,12 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace Jellyfin.Networking.Manager { /// <summary> /// Class to take care of network interface management. - /// - /// Note: The normal collection methods and properties will not work with NetCollection. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. + /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. /// </summary> public class NetworkManager : INetworkManager, IDisposable { @@ -37,7 +34,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// List of all interface addresses and masks. /// </summary> - private readonly NetCollection _interfaceAddresses; + private readonly Collection<IPObject> _interfaceAddresses; /// <summary> /// List of all interface MAC addresses. @@ -61,30 +58,30 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// <summary> - /// Unfiltered user defined LAN subnets. (Configuration.LocalNetworkSubnets). + /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>) /// or internal interface network subnets if undefined by user. /// </summary> - private NetCollection _lanSubnets; + private Collection<IPObject> _lanSubnets; /// <summary> /// User defined list of subnets to excluded from the LAN. /// </summary> - private NetCollection _excludedSubnets; + private Collection<IPObject> _excludedSubnets; /// <summary> /// List of interface addresses to bind the WS. /// </summary> - private NetCollection _bindAddresses; + private Collection<IPObject> _bindAddresses; /// <summary> /// List of interface addresses to exclude from bind. /// </summary> - private NetCollection _bindExclusions; + private Collection<IPObject> _bindExclusions; /// <summary> /// Caches list of all internal filtered interface addresses and masks. /// </summary> - private NetCollection _internalInterfaces; + private Collection<IPObject> _internalInterfaces; /// <summary> /// Flag set when no custom LAN has been defined in the config. @@ -107,7 +104,7 @@ namespace Jellyfin.Networking.Manager _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); - _interfaceAddresses = new NetCollection(); + _interfaceAddresses = new Collection<IPObject>(); _macAddresses = new List<PhysicalAddress>(); _interfaceNames = new Dictionary<string, int>(); _publishedServerUrls = new Dictionary<IPNetAddress, string>(); @@ -143,7 +140,7 @@ namespace Jellyfin.Networking.Manager public bool IsIP4Enabled { get; set; } /// <inheritdoc/> - public NetCollection RemoteAddressFilter { get; private set; } + public Collection<IPObject> RemoteAddressFilter { get; private set; } /// <summary> /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -160,9 +157,9 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="source">Items to assign the collection, or null.</param> /// <returns>The collection created.</returns> - public static NetCollection CreateCollection(IEnumerable<IPObject>? source = null) + public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null) { - var result = new NetCollection(); + var result = new Collection<IPObject>(); if (source != null) { foreach (var item in source) @@ -189,22 +186,22 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public bool IsGatewayInterface(object? addressObj) + public bool IsGatewayInterface(IPObject? addressObj) { - var address = addressObj switch - { - IPAddress addressIp => addressIp, - IPObject addressIpObj => addressIpObj.Address, - _ => IPAddress.None - }; - + var address = addressObj?.Address ?? IPAddress.None; return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); } /// <inheritdoc/> - public NetCollection GetLoopbacks() + public bool IsGatewayInterface(IPAddress? addressObj) { - NetCollection nc = new NetCollection(); + return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0); + } + + /// <inheritdoc/> + public Collection<IPObject> GetLoopbacks() + { + Collection<IPObject> nc = new Collection<IPObject>(); if (IsIP4Enabled) { nc.AddItem(IPAddress.Loopback); @@ -231,9 +228,9 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection CreateIPCollection(string[] values, bool bracketed = false) + public Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false) { - NetCollection col = new NetCollection(); + Collection<IPObject> col = new Collection<IPObject>(); if (values == null) { return col; @@ -256,7 +253,7 @@ namespace Jellyfin.Networking.Manager { if (bracketed) { - AddToCollection(col, v.Substring(1)); + AddToCollection(col, v[1..]); } } else if (!bracketed) @@ -266,7 +263,7 @@ namespace Jellyfin.Networking.Manager } catch (ArgumentException e) { - _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); + _logger.LogWarning(e, "Ignoring LAN value {value}.", v); } } @@ -274,7 +271,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) + public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false) { int count = _bindAddresses.Count; @@ -288,11 +285,11 @@ namespace Jellyfin.Networking.Manager if (individualInterfaces) { - return new NetCollection(_interfaceAddresses); + return new Collection<IPObject>(_interfaceAddresses); } // No bind address and no exclusions, so listen on all interfaces. - NetCollection result = new NetCollection(); + Collection<IPObject> result = new Collection<IPObject>(); if (IsIP4Enabled) { @@ -376,7 +373,7 @@ namespace Jellyfin.Networking.Manager if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) { - _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, res, port); + _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); return res; } } @@ -429,7 +426,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection GetInternalBindAddresses() + public Collection<IPObject> GetInternalBindAddresses() { int count = _bindAddresses.Count; @@ -445,7 +442,7 @@ namespace Jellyfin.Networking.Manager return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } - return new NetCollection(_bindAddresses); + return new Collection<IPObject>(_bindAddresses); } /// <inheritdoc/> @@ -526,7 +523,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) + public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null) { if (filter == null) { @@ -543,7 +540,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public bool TryParseInterface(string token, out NetCollection? result) + public bool TryParseInterface(string token, out Collection<IPObject>? result) { result = null; if (string.IsNullOrEmpty(token)) @@ -553,16 +550,16 @@ namespace Jellyfin.Networking.Manager if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) { - result = new NetCollection(); + result = new Collection<IPObject>(); _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (Math.Abs(iface.Tag) == index && - ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || - (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { result.AddItem(iface); } @@ -577,8 +574,8 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Reloads all settings and re-initialises the instance. /// </summary> - /// <param name="configuration">The configuration to use.</param> - public void UpdateSettings(object configuration) + /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> + public void UpdateSettings(NetworkConfiguration configuration) { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); @@ -622,7 +619,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Protected implementation of Dispose pattern. /// </summary> - /// <param name="disposing">True to dispose the managed state.</param> + /// <param name="disposing"><c>True</c> to dispose the managed state.</param> protected virtual void Dispose(bool disposing) { if (!_disposed) @@ -639,11 +636,11 @@ namespace Jellyfin.Networking.Manager } /// <summary> - /// Trys to identify the string and return an object of that class. + /// Tries to identify the string and return an object of that class. /// </summary> /// <param name="addr">String to parse.</param> /// <param name="result">IPObject to return.</param> - /// <returns>True if the value parsed successfully.</returns> + /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns> private static bool TryParse(string addr, out IPObject result) { if (!string.IsNullOrEmpty(addr)) @@ -671,7 +668,7 @@ namespace Jellyfin.Networking.Manager /// Ipv6 addresses are returned in [ ], with their scope removed. /// </summary> /// <param name="address">Address to convert.</param> - /// <returns>URI save conversion of the address.</returns> + /// <returns>URI safe conversion of the address.</returns> private static string FormatIP6String(IPAddress address) { var str = address.ToString(); @@ -694,7 +691,7 @@ namespace Jellyfin.Networking.Manager { if (evt.Key.Equals("network", StringComparison.Ordinal)) { - UpdateSettings(evt.NewConfiguration); + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } } @@ -703,7 +700,7 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="token">String to check.</param> /// <param name="index">Interface index number.</param> - /// <returns>True if an interface name matches the token.</returns> + /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns> private bool IsInterface(string token, out int index) { index = -1; @@ -720,8 +717,8 @@ namespace Jellyfin.Networking.Manager foreach ((string interfc, int interfcIndex) in _interfaceNames) { - if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || - (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) + if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) + || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) { index = interfcIndex; return true; @@ -733,11 +730,11 @@ namespace Jellyfin.Networking.Manager } /// <summary> - /// Parses strings into the collection, replacing any interface references. + /// Parses a string and adds it into the the collection, replacing any interface references. /// </summary> - /// <param name="col">Collection.</param> - /// <param name="token">String to parse.</param> - private void AddToCollection(NetCollection col, string token) + /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param> + /// <param name="token">String value to parse.</param> + private void AddToCollection(Collection<IPObject> col, string token) { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. @@ -748,9 +745,9 @@ namespace Jellyfin.Networking.Manager // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (Math.Abs(iface.Tag) == index && - ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || - (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { col.AddItem(iface); } @@ -791,7 +788,7 @@ namespace Jellyfin.Networking.Manager /// Handler for network change events. /// </summary> /// <param name="sender">Sender.</param> - /// <param name="e">Network availability information.</param> + /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param> private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { _logger.LogDebug("Network availability changed."); @@ -802,7 +799,7 @@ namespace Jellyfin.Networking.Manager /// Handler for network change events. /// </summary> /// <param name="sender">Sender.</param> - /// <param name="e">Event arguments.</param> + /// <param name="e">An <see cref="EventArgs"/>.</param> private void OnNetworkAddressChanged(object? sender, EventArgs e) { _logger.LogDebug("Network address change detected."); @@ -812,7 +809,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// </summary> - /// <returns>The network change async.</returns> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task OnNetworkChangeAsync() { try @@ -883,7 +880,7 @@ namespace Jellyfin.Networking.Manager { _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; } - else if (TryParseInterface(parts[0], out NetCollection? addresses) && addresses != null) + else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null) { foreach (IPNetAddress na in addresses) { @@ -903,6 +900,9 @@ namespace Jellyfin.Networking.Manager } } + /// <summary> + /// Initialises the network bind addresses. + /// </summary> private void InitialiseBind(NetworkConfiguration config) { string[] lanAddresses = config.LocalNetworkAddresses; @@ -931,6 +931,9 @@ namespace Jellyfin.Networking.Manager _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } + /// <summary> + /// Initialises the remote address values. + /// </summary> private void InitialiseRemote(NetworkConfiguration config) { RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); @@ -964,7 +967,7 @@ namespace Jellyfin.Networking.Manager _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); // Subnets are the same as the calculated internal interface. - _lanSubnets = new NetCollection(); + _lanSubnets = new Collection<IPObject>(); // We must listen on loopback for LiveTV to function regardless of the settings. if (IsIP6Enabled) @@ -1131,7 +1134,7 @@ namespace Jellyfin.Networking.Manager /// <param name="isExternal">True if the source is in the external subnet.</param> /// <param name="bindPreference">The published server url that matches the source address.</param> /// <param name="port">The resultant port, if one exists.</param> - /// <returns>True if a match is found.</returns> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port) { bindPreference = string.Empty; @@ -1185,7 +1188,7 @@ namespace Jellyfin.Networking.Manager /// <param name="source">IP source address to use.</param> /// <param name="isExternal">True if the source is in the external subnet.</param> /// <param name="result">The result, if a match is found.</param> - /// <returns>True if a match is found.</returns> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> private bool MatchesBindInterface(IPObject source, bool isExternal, out string result) { result = string.Empty; @@ -1202,7 +1205,7 @@ namespace Jellyfin.Networking.Manager { // Check to see if any of the bind interfaces are in the same subnet. - NetCollection bindResult; + Collection<IPObject> bindResult; IPAddress? defaultGateway = null; IPAddress? bindAddress; @@ -1246,7 +1249,6 @@ namespace Jellyfin.Networking.Manager if (isExternal) { - // TODO: remove this after testing. _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source); } @@ -1261,7 +1263,7 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="source">IP source address to use.</param> /// <param name="result">The result, if a match is found.</param> - /// <returns>True if a match is found.</returns> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> private bool MatchesExternalInterface(IPObject source, out string result) { result = string.Empty; @@ -1292,7 +1294,6 @@ namespace Jellyfin.Networking.Manager // Have to return something, so return an internal address - // TODO: remove this after testing. _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source); return false; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index a7beabbdcb..43562afe38 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,10 +1,11 @@ #nullable enable using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Net; using System.Net.NetworkInformation; +using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace MediaBrowser.Common.Net { @@ -31,7 +32,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Gets the remote address filter. /// </summary> - NetCollection RemoteAddressFilter { get; } + Collection<IPObject> RemoteAddressFilter { get; } /// <summary> /// Gets or sets a value indicating whether iP6 is enabled. @@ -46,17 +47,17 @@ namespace MediaBrowser.Common.Net /// <summary> /// Calculates the list of interfaces to use for Kestrel. /// </summary> - /// <returns>A NetCollection object containing all the interfaces to bind. + /// <returns>A Collection{IPObject} object containing all the interfaces to bind. /// If all the interfaces are specified, and none are excluded, it returns zero items /// to represent any address.</returns> /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param> - NetCollection GetAllBindInterfaces(bool individualInterfaces = false); + Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false); /// <summary> /// Returns a collection containing the loopback interfaces. /// </summary> - /// <returns>Netcollection.</returns> - NetCollection GetLoopbacks(); + /// <returns>Collection{IPObject}.</returns> + Collection<IPObject> GetLoopbacks(); /// <summary> /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -137,7 +138,14 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> /// <returns>Result of the check.</returns> - bool IsGatewayInterface(object? addressObj); + bool IsGatewayInterface(IPObject? addressObj); + + /// <summary> + /// Checks to see if the IP Address provided matches an interface that has a gateway. + /// </summary> + /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> + /// <returns>Result of the check.</returns> + bool IsGatewayInterface(IPAddress? addressObj); /// <summary> /// Returns true if the address is a private address. @@ -178,21 +186,21 @@ namespace MediaBrowser.Common.Net /// <param name="token">Token to parse.</param> /// <param name="result">Resultant object's ip addresses, if successful.</param> /// <returns>Success of the operation.</returns> - bool TryParseInterface(string token, out NetCollection? result); + bool TryParseInterface(string token, out Collection<IPObject>? result); /// <summary> - /// Parses an array of strings into a NetCollection. + /// Parses an array of strings into a Collection{IPObject}. /// </summary> /// <param name="values">Values to parse.</param> /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> /// <returns>IPCollection object containing the value strings.</returns> - NetCollection CreateIPCollection(string[] values, bool bracketed = false); + Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false); /// <summary> /// Returns all the internal Bind interface addresses. /// </summary> /// <returns>An internal list of interfaces addresses.</returns> - NetCollection GetInternalBindAddresses(); + Collection<IPObject> GetInternalBindAddresses(); /// <summary> /// Checks to see if an IP address is still a valid interface address. @@ -220,12 +228,6 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="filter">Optional filter for the list.</param> /// <returns>Returns a filtered list of LAN addresses.</returns> - NetCollection GetFilteredLANSubnets(NetCollection? filter = null); - - /// <summary> - /// Reloads all settings and re-initialises the instance. - /// </summary> - /// <param name="configuration">The configuration to use.</param> - void UpdateSettings(object configuration); + Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null); } } diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 80052727af..f9e1568efc 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -19,7 +19,7 @@ namespace MediaBrowser.Common.Net public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); /// <summary> - /// Time when last resolved. + /// Time when last resolved in ticks. /// </summary> private long _lastResolved; @@ -63,7 +63,8 @@ namespace MediaBrowser.Common.Net set { - // Not implemented. + // Not implemented, as a host's address is determined by DNS. + throw new NotImplementedException("The address of a host is determined by DNS."); } } @@ -75,12 +76,14 @@ namespace MediaBrowser.Common.Net { get { - return (byte)(ResolveHost() ? 128 : 0); + return (byte)(ResolveHost() ? 128 : 32); } set { - // Not implemented. + // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length, + // which is automatically determined by it's IP type. Anything else is meaningless. + throw new NotImplementedException("The prefix length on a host cannot be set."); } } @@ -92,13 +95,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Gets a value indicating whether the address has a value. /// </summary> - public bool HasAddress - { - get - { - return _addresses.Length > 0; - } - } + public bool HasAddress => _addresses.Length != 0; /// <summary> /// Gets the host name of this object. @@ -128,7 +125,7 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="host">Host name to parse.</param> /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param> - /// <returns>Success result of the parsing.</returns> + /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns> public static bool TryParse(string host, out IPHost hostObj) { if (!string.IsNullOrEmpty(host)) @@ -142,7 +139,7 @@ namespace MediaBrowser.Common.Net else { // See if it's an IPv6 in [] with no port. - i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); + i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase); if (i != -1) { return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); @@ -394,19 +391,19 @@ namespace MediaBrowser.Common.Net /// <summary> /// Attempt to resolve the ip address of a host. /// </summary> - /// <returns>The result of the comparison function.</returns> + /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns> private bool ResolveHost() { // When was the last time we resolved? if (_lastResolved == 0) { - _lastResolved = DateTime.Now.Ticks; + _lastResolved = DateTime.UtcNow.Ticks; } // If we haven't resolved before, or out timer has run out... - if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.Now.Ticks - _lastResolved).TotalMinutes > Timeout)) + if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.UtcNow.Ticks - _lastResolved).TotalMinutes > Timeout)) { - _lastResolved = DateTime.Now.Ticks; + _lastResolved = DateTime.UtcNow.Ticks; ResolveHostInternal().GetAwaiter().GetResult(); Resolved = true; } @@ -417,7 +414,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Task that looks up a Host name and returns its IP addresses. /// </summary> - /// <returns>Array of IPAddress objects.</returns> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task ResolveHostInternal() { if (!string.IsNullOrEmpty(HostName)) diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index 36f3357cce..d18ac98933 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Common.Net private IPObject? _networkAddress; /// <summary> - /// Gets or sets the user defined functions that need storage in this object. + /// Gets or sets a user defined value that is associated with this object. /// </summary> public int Tag { get; set; } @@ -38,18 +38,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Gets the object's network address. /// </summary> - public IPObject NetworkAddress - { - get - { - if (_networkAddress == null) - { - _networkAddress = CalculateNetworkAddress(); - } - - return _networkAddress; - } - } + public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); /// <summary> /// Gets or sets the object's IP address. @@ -92,22 +81,33 @@ namespace MediaBrowser.Common.Net return (Address: address, PrefixLength: prefixLength); } + // An ip address is just a list of bytes, each one representing a segment on the network. + // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the + // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out. + // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept. + byte[] addressBytes = address.GetAddressBytes(); int div = prefixLength / 8; int mod = prefixLength % 8; if (mod != 0) { + // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear. mod = 8 - mod; + + // Shift out the bits from the octet that we don't want, by moving right then back left. addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod); + // Move on the next byte. div++; } + // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0) for (int octet = div; octet < addressBytes.Length; octet++) { addressBytes[octet] = 0; } + // Return the network address for the prefix. return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); } @@ -179,18 +179,18 @@ namespace MediaBrowser.Common.Net byte[] octet = address.GetAddressBytes(); - return (octet[0] == 10) || - (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) || // RFC1918 - (octet[0] == 192 && octet[1] == 168) || // RFC1918 - (octet[0] == 127); // RFC1122 + return (octet[0] == 10) + || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918 + || (octet[0] == 192 && octet[1] == 168) // RFC1918 + || (octet[0] == 127); // RFC1122 } else { byte[] octet = address.GetAddressBytes(); uint word = (uint)(octet[0] << 8) + octet[1]; - return (word >= 0xfe80 && word <= 0xfebf) || // fe80::/10 :Local link. - (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. + return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link. + || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. } } @@ -202,7 +202,8 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="address">IPAddress object to check.</param> /// <returns>True if it is a local link address.</returns> - /// <remarks>See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// <remarks> + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. /// </remarks> public static bool IsIPv6LinkLocal(IPAddress address) @@ -237,11 +238,10 @@ namespace MediaBrowser.Common.Net public static IPAddress CidrToMask(byte cidr, AddressFamily family) { uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); - addr = - ((addr & 0xff000000) >> 24) | - ((addr & 0x00ff0000) >> 8) | - ((addr & 0x0000ff00) << 8) | - ((addr & 0x000000ff) << 24); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); return new IPAddress(addr); } @@ -304,7 +304,7 @@ namespace MediaBrowser.Common.Net /// <param name="family">Type of address to remove.</param> public virtual void Remove(AddressFamily family) { - // This method only peforms a function in the IPHost implementation of IPObject. + // This method only performs a function in the IPHost implementation of IPObject. } /// <summary> @@ -352,9 +352,9 @@ namespace MediaBrowser.Common.Net /// <returns>Equality result.</returns> public virtual bool Equals(IPObject? other) { - if (other != null && other is IPObject otherObj) + if (other != null) { - return !Address.Equals(IPAddress.None) && Address.Equals(otherObj.Address); + return !Address.Equals(IPAddress.None) && Address.Equals(other.Address); } return false; diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index e801de5eb8..d07bba249b 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -2,10 +2,10 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Net; using System.Runtime.CompilerServices; using System.Text; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace MediaBrowser.Common.Net { @@ -17,9 +17,9 @@ namespace MediaBrowser.Common.Net /// <summary> /// Add an address to the collection. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="ip">Item to add.</param> - public static void AddItem(this NetCollection source, IPAddress ip) + public static void AddItem(this Collection<IPObject> source, IPAddress ip) { if (!source.ContainsAddress(ip)) { @@ -30,9 +30,9 @@ namespace MediaBrowser.Common.Net /// <summary> /// Adds a network to the collection. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="item">Item to add.</param> - public static void AddItem(this NetCollection source, IPObject item) + public static void AddItem(this Collection<IPObject> source, IPObject item) { if (!source.ContainsAddress(item)) { @@ -43,33 +43,21 @@ namespace MediaBrowser.Common.Net /// <summary> /// Converts this object to a string. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <returns>Returns a string representation of this object.</returns> - public static string AsString(this NetCollection source) + public static string AsString(this Collection<IPObject> source) { - var sb = new StringBuilder(); - string output = "["; - if (source.Count > 0) - { - foreach (var i in source) - { - output += $"{i},"; - } - - output = output[0..^1]; - } - - return $"{output}]"; + return $"[{string.Join(',', source)}]"; } /// <summary> /// Returns true if the collection contains an item with the ip address, /// or the ip address falls within any of the collection's network ranges. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="item">The item to look for.</param> /// <returns>True if the collection contains the item.</returns> - public static bool ContainsAddress(this NetCollection source, IPAddress item) + public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item) { if (source.Count == 0) { @@ -101,10 +89,10 @@ namespace MediaBrowser.Common.Net /// Returns true if the collection contains an item with the ip address, /// or the ip address falls within any of the collection's network ranges. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="item">The item to look for.</param> /// <returns>True if the collection contains the item.</returns> - public static bool ContainsAddress(this NetCollection source, IPObject item) + public static bool ContainsAddress(this Collection<IPObject> source, IPObject item) { if (source.Count == 0) { @@ -128,12 +116,12 @@ namespace MediaBrowser.Common.Net } /// <summary> - /// Compares two NetCollection objects. The order is ignored. + /// Compares two Collection{IPObject} objects. The order is ignored. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="dest">Item to compare to.</param> /// <returns>True if both are equal.</returns> - public static bool Compare(this NetCollection source, NetCollection dest) + public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest) { if (dest == null || source.Count != dest.Count) { @@ -164,16 +152,16 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns a collection containing the subnets of this collection given. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> - /// <returns>NetCollection object containing the subnets.</returns> - public static NetCollection AsNetworks(this NetCollection source) + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <returns>Collection{IPObject} object containing the subnets.</returns> + public static Collection<IPObject> AsNetworks(this Collection<IPObject> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } - NetCollection res = new NetCollection(); + Collection<IPObject> res = new Collection<IPObject>(); foreach (IPObject i in source) { @@ -184,10 +172,10 @@ namespace MediaBrowser.Common.Net na.Tag = i.Tag; res.AddItem(na); } - else + else if (i is IPHost ipHost) { // Flatten out IPHost and add all its ip addresses. - foreach (var addr in ((IPHost)i).GetAddresses()) + foreach (var addr in ipHost.GetAddresses()) { IPNetAddress host = new IPNetAddress(addr) { @@ -205,17 +193,17 @@ namespace MediaBrowser.Common.Net /// <summary> /// Excludes all the items from this list that are found in excludeList. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="excludeList">Items to exclude.</param> /// <returns>A new collection, with the items excluded.</returns> - public static NetCollection Exclude(this NetCollection source, NetCollection excludeList) + public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList) { if (source.Count == 0 || excludeList == null) { - return new NetCollection(source); + return new Collection<IPObject>(source); } - NetCollection results = new NetCollection(); + Collection<IPObject> results = new Collection<IPObject>(); bool found; foreach (var outer in source) @@ -243,14 +231,14 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns all items that co-exist in this object and target. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> /// <param name="target">Collection to compare with.</param> /// <returns>A collection containing all the matches.</returns> - public static NetCollection Union(this NetCollection source, NetCollection target) + public static Collection<IPObject> Union(this Collection<IPObject> source, Collection<IPObject> target) { if (source.Count == 0) { - return new NetCollection(); + return new Collection<IPObject>(); } if (target == null) @@ -258,7 +246,7 @@ namespace MediaBrowser.Common.Net throw new ArgumentNullException(nameof(target)); } - NetCollection nc = new NetCollection(); + Collection<IPObject> nc = new Collection<IPObject>(); foreach (IPObject i in source) { From 60a6627140a83408b8157b9543e62ff48918ef7a Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 16 Nov 2020 19:45:21 +0000 Subject: [PATCH 0380/1930] Removing left over edits left from the acceptance of previous PR's. --- Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs | 1 - Jellyfin.Api/Controllers/ConfigurationController.cs | 2 -- .../Jellyfin.Server.Implementations.csproj | 1 - MediaBrowser.Common/Configuration/IConfigurationManager.cs | 2 +- 4 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 76b039672c..4f72c8ce15 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -10,7 +10,6 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.IO; using MediaBrowser.Model.Serialization; -using Microsoft.EntityFrameworkCore.Migrations.Operations; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.AppBase diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index 53f94cf375..e1c9f69f61 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -4,9 +4,7 @@ using System.Text.Json; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; -using Jellyfin.Api.Migrations; using Jellyfin.Api.Models.ConfigurationDtos; -using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index b626bf1702..e663798da0 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -37,7 +37,6 @@ <ItemGroup> <ProjectReference Include="..\Jellyfin.Data\Jellyfin.Data.csproj" /> - <ProjectReference Include="..\Jellyfin.Networking\Jellyfin.Networking.csproj" /> <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" /> <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" /> </ItemGroup> diff --git a/MediaBrowser.Common/Configuration/IConfigurationManager.cs b/MediaBrowser.Common/Configuration/IConfigurationManager.cs index 790121274e..fc63d93503 100644 --- a/MediaBrowser.Common/Configuration/IConfigurationManager.cs +++ b/MediaBrowser.Common/Configuration/IConfigurationManager.cs @@ -56,7 +56,7 @@ namespace MediaBrowser.Common.Configuration /// <summary> /// Gets the configuration. /// </summary> - /// /// <param name="key">The key.</param> + /// <param name="key">The key.</param> /// <returns>System.Object.</returns> object GetConfiguration(string key); From 7b42b7e8bd40ef7bd6bb6a533cb3c9dfcd00c63f Mon Sep 17 00:00:00 2001 From: Ygor Lhano <ygor.lhano@gmail.com> Date: Mon, 16 Nov 2020 23:35:05 +0000 Subject: [PATCH 0381/1930] Translated using Weblate (Portuguese (Brazil)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt_BR/ --- Emby.Server.Implementations/Localization/Core/pt-BR.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt-BR.json b/Emby.Server.Implementations/Localization/Core/pt-BR.json index 5e49ca702e..8d25e27f6b 100644 --- a/Emby.Server.Implementations/Localization/Core/pt-BR.json +++ b/Emby.Server.Implementations/Localization/Core/pt-BR.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "Canais da Internet", "TasksApplicationCategory": "Aplicativo", "TasksLibraryCategory": "Biblioteca", - "TasksMaintenanceCategory": "Manutenção" + "TasksMaintenanceCategory": "Manutenção", + "TaskCleanActivityLogDescription": "Apaga o registro de atividades mais antigo que a idade configurada.", + "TaskCleanActivityLog": "Limpar Registro de Atividades" } From 1d96167e8d58ff59859ae5b9afc1f9e0f6bed74f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 16 Nov 2020 17:05:31 -0700 Subject: [PATCH 0382/1930] Fix builders --- deployment/Dockerfile.docker.amd64 | 2 +- deployment/Dockerfile.docker.arm64 | 2 +- deployment/Dockerfile.docker.armhf | 2 +- fedora/jellyfin.spec | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/deployment/Dockerfile.docker.amd64 b/deployment/Dockerfile.docker.amd64 index b61185f8c0..926dd0cae7 100644 --- a/deployment/Dockerfile.docker.amd64 +++ b/deployment/Dockerfile.docker.amd64 @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin diff --git a/deployment/Dockerfile.docker.arm64 b/deployment/Dockerfile.docker.arm64 index 7420b2137a..8fb03fcd06 100644 --- a/deployment/Dockerfile.docker.arm64 +++ b/deployment/Dockerfile.docker.arm64 @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin diff --git a/deployment/Dockerfile.docker.armhf b/deployment/Dockerfile.docker.armhf index 38e72ad850..d2c7fa3ff9 100644 --- a/deployment/Dockerfile.docker.armhf +++ b/deployment/Dockerfile.docker.armhf @@ -1,6 +1,6 @@ ARG DOTNET_VERSION=5.0 -FROM mcr.microsoft.com/dotnet/core/sdk:${DOTNET_VERSION}-buster +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster ARG SOURCE_DIR=/src ARG ARTIFACT_DIR=/jellyfin diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 22f5949aee..13305488e2 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -82,7 +82,6 @@ EOF %{_libdir}/jellyfin/* # Needs 755 else only root can run it since binary build by dotnet is 722 %attr(755,root,root) %{_libdir}/jellyfin/jellyfin -%{_libdir}/jellyfin/SOS_README.md %{_unitdir}/jellyfin.service %{_libexecdir}/jellyfin/restart.sh %{_prefix}/lib/firewalld/services/jellyfin.xml From 001bf95d105e9ad849b0d4fc06acc23e7d12c7ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= <oddstr13@openshell.no> Date: Tue, 17 Nov 2020 03:56:17 +0100 Subject: [PATCH 0383/1930] Fedora: install systemd as build dependency --- deployment/Dockerfile.fedora.amd64 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64 index f881890348..ffb08f9e2b 100644 --- a/deployment/Dockerfile.fedora.amd64 +++ b/deployment/Dockerfile.fedora.amd64 @@ -10,7 +10,7 @@ ENV IS_DOCKER=YES # Prepare Fedora environment RUN dnf update -y \ - && dnf install -y @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel + && dnf install -y @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel systemd # Install DotNET SDK RUN rpm --import https://packages.microsoft.com/keys/microsoft.asc \ From 3cc0dd7e12380a7e4a0ef86591890ece8421b14c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 16 Nov 2020 20:29:46 -0700 Subject: [PATCH 0384/1930] Reduce RequestHelpers.Split usage and remove RequestHelpers.GetGuids usage. --- .../Channels/ChannelManager.cs | 2 +- .../Data/SqliteItemRepository.cs | 8 +- .../Library/LibraryManager.cs | 2 +- .../Playlists/PlaylistManager.cs | 6 +- Jellyfin.Api/Controllers/ArtistsController.cs | 100 ++++---- .../Controllers/CollectionController.cs | 17 +- Jellyfin.Api/Controllers/GenresController.cs | 10 +- Jellyfin.Api/Controllers/ItemsController.cs | 103 ++++---- Jellyfin.Api/Controllers/LibraryController.cs | 13 +- Jellyfin.Api/Controllers/LiveTvController.cs | 28 +-- .../Controllers/MusicGenresController.cs | 10 +- Jellyfin.Api/Controllers/PersonsController.cs | 8 +- .../Controllers/PlaylistsController.cs | 13 +- Jellyfin.Api/Controllers/SearchController.cs | 13 +- Jellyfin.Api/Controllers/SessionController.cs | 8 +- Jellyfin.Api/Controllers/StudiosController.cs | 13 +- .../Controllers/SuggestionsController.cs | 9 +- .../Controllers/TrailersController.cs | 38 +-- .../Controllers/UniversalAudioController.cs | 8 +- .../Controllers/UserLibraryController.cs | 4 +- .../Controllers/UserViewsController.cs | 7 +- Jellyfin.Api/Controllers/VideosController.cs | 5 +- Jellyfin.Api/Controllers/YearsController.cs | 18 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 43 ---- .../PipeDelimitedArrayModelBinder.cs | 90 +++++++ .../Models/LiveTvDtos/GetProgramsDto.cs | 9 +- .../Models/PlaylistDtos/CreatePlaylistDto.cs | 6 +- .../JsonPipeDelimitedArrayConverter.cs | 74 ++++++ .../JsonPipeDelimitedArrayConverterFactory.cs | 28 +++ .../MediaBrowser.Common.csproj | 2 +- MediaBrowser.Controller/Entities/Folder.cs | 6 +- .../Entities/InternalItemsQuery.cs | 6 +- .../Entities/UserViewBuilder.cs | 4 +- .../Playlists/IPlaylistManager.cs | 2 +- .../Playlists/PlaylistCreationRequest.cs | 8 +- .../PipeDelimitedArrayModelBinderTests.cs | 226 ++++++++++++++++++ 36 files changed, 659 insertions(+), 288 deletions(-) create mode 100644 Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs create mode 100644 MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs create mode 100644 MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs create mode 100644 tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 19045b72b4..3d97a6ca8d 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -634,7 +634,7 @@ namespace Emby.Server.Implementations.Channels { var channels = GetAllChannels().Where(i => i is ISupportsLatestMedia).ToArray(); - if (query.ChannelIds.Length > 0) + if (query.ChannelIds.Count > 0) { // Avoid implicitly captured closure var ids = query.ChannelIds; diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 638c7a9b49..7e01bd4b64 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -3611,12 +3611,12 @@ namespace Emby.Server.Implementations.Data whereClauses.Add($"type in ({inClause})"); } - if (query.ChannelIds.Length == 1) + if (query.ChannelIds.Count == 1) { whereClauses.Add("ChannelId=@ChannelId"); statement?.TryBind("@ChannelId", query.ChannelIds[0].ToString("N", CultureInfo.InvariantCulture)); } - else if (query.ChannelIds.Length > 1) + else if (query.ChannelIds.Count > 1) { var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); whereClauses.Add($"ChannelId in ({inClause})"); @@ -4076,7 +4076,7 @@ namespace Emby.Server.Implementations.Data whereClauses.Add(clause); } - if (query.GenreIds.Length > 0) + if (query.GenreIds.Count > 0) { var clauses = new List<string>(); var index = 0; @@ -4097,7 +4097,7 @@ namespace Emby.Server.Implementations.Data whereClauses.Add(clause); } - if (query.Genres.Length > 0) + if (query.Genres.Count > 0) { var clauses = new List<string>(); var index = 0; diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 8ab5e4aef1..03bf1c8747 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1503,7 +1503,7 @@ namespace Emby.Server.Implementations.Library { if (query.AncestorIds.Length == 0 && query.ParentId.Equals(Guid.Empty) && - query.ChannelIds.Length == 0 && + query.ChannelIds.Count == 0 && query.TopParentIds.Length == 0 && string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) && string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) && diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index d3b64fb318..932f721ab4 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -150,7 +150,7 @@ namespace Emby.Server.Implementations.Playlists await playlist.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(_fileSystem)) { ForceSave = true }, CancellationToken.None) .ConfigureAwait(false); - if (options.ItemIdList.Length > 0) + if (options.ItemIdList.Count > 0) { await AddToPlaylistInternal(playlist.Id, options.ItemIdList, user, new DtoOptions(false) { @@ -184,7 +184,7 @@ namespace Emby.Server.Implementations.Playlists return Playlist.GetPlaylistItems(playlistMediaType, items, user, options); } - public Task AddToPlaylistAsync(Guid playlistId, ICollection<Guid> itemIds, Guid userId) + public Task AddToPlaylistAsync(Guid playlistId, IReadOnlyCollection<Guid> itemIds, Guid userId) { var user = userId.Equals(Guid.Empty) ? null : _userManager.GetUserById(userId); @@ -194,7 +194,7 @@ namespace Emby.Server.Implementations.Playlists }); } - private async Task AddToPlaylistInternal(Guid playlistId, ICollection<Guid> newItemIds, User user, DtoOptions options) + private async Task AddToPlaylistInternal(Guid playlistId, IReadOnlyCollection<Guid> newItemIds, User user, DtoOptions options) { // Retrieve the existing playlist var playlist = _libraryManager.GetItemById(playlistId) as Playlist diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 9bad206e02..0123bb8fa3 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -89,24 +89,24 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, [FromQuery] string? studios, - [FromQuery] string? studioIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, @@ -131,30 +131,26 @@ namespace Jellyfin.Api.Controllers parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); } - var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true); - var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true); - var mediaTypesArr = RequestHelpers.Split(mediaTypes, ',', true); - var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypesArr, - IncludeItemTypes = includeItemTypesArr, - MediaTypes = mediaTypesArr, + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, + MediaTypes = mediaTypes, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), + Tags = tags, + OfficialRatings = officialRatings, + Genres = genres, + GenreIds = genreIds, + StudioIds = studioIds, Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(), + PersonIds = personIds, + PersonTypes = personTypes, + Years = years, MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, @@ -230,7 +226,7 @@ namespace Jellyfin.Api.Controllers var (baseItem, itemCounts) = i; var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - if (!string.IsNullOrWhiteSpace(includeItemTypes)) + if (includeItemTypes.Length != 0) { dto.ChildCount = itemCounts.ItemCount; dto.ProgramCount = itemCounts.ProgramCount; @@ -297,24 +293,24 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, - [FromQuery] string? genres, - [FromQuery] string? genreIds, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, [FromQuery] string? studios, - [FromQuery] string? studioIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, @@ -339,30 +335,26 @@ namespace Jellyfin.Api.Controllers parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); } - var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true); - var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true); - var mediaTypesArr = RequestHelpers.Split(mediaTypes, ',', true); - var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypesArr, - IncludeItemTypes = includeItemTypesArr, - MediaTypes = mediaTypesArr, + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, + MediaTypes = mediaTypes, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, NameLessThan = nameLessThan, NameStartsWith = nameStartsWith, NameStartsWithOrGreater = nameStartsWithOrGreater, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), + Tags = tags, + OfficialRatings = officialRatings, + Genres = genres, + GenreIds = genreIds, + StudioIds = studioIds, Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(), + PersonIds = personIds, + PersonTypes = personTypes, + Years = years, MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, @@ -438,7 +430,7 @@ namespace Jellyfin.Api.Controllers var (baseItem, itemCounts) = i; var dto = _dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user); - if (!string.IsNullOrWhiteSpace(includeItemTypes)) + if (includeItemTypes.Length != 0) { dto.ChildCount = itemCounts.ItemCount; dto.ProgramCount = itemCounts.ProgramCount; diff --git a/Jellyfin.Api/Controllers/CollectionController.cs b/Jellyfin.Api/Controllers/CollectionController.cs index eae06b767c..2a342c2cbe 100644 --- a/Jellyfin.Api/Controllers/CollectionController.cs +++ b/Jellyfin.Api/Controllers/CollectionController.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Net; @@ -54,7 +55,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public async Task<ActionResult<CollectionCreationResult>> CreateCollection( [FromQuery] string? name, - [FromQuery] string? ids, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] ids, [FromQuery] Guid? parentId, [FromQuery] bool isLocked = false) { @@ -65,7 +66,7 @@ namespace Jellyfin.Api.Controllers IsLocked = isLocked, Name = name, ParentId = parentId, - ItemIdList = RequestHelpers.Split(ids, ',', true), + ItemIdList = ids, UserIds = new[] { userId } }).ConfigureAwait(false); @@ -88,9 +89,11 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("{collectionId}/Items")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task<ActionResult> AddToCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids) + public async Task<ActionResult> AddToCollection( + [FromRoute, Required] Guid collectionId, + [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids) { - await _collectionManager.AddToCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(true); + await _collectionManager.AddToCollectionAsync(collectionId, ids).ConfigureAwait(true); return NoContent(); } @@ -103,9 +106,11 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpDelete("{collectionId}/Items")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task<ActionResult> RemoveFromCollection([FromRoute, Required] Guid collectionId, [FromQuery, Required] string ids) + public async Task<ActionResult> RemoveFromCollection( + [FromRoute, Required] Guid collectionId, + [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids) { - await _collectionManager.RemoveFromCollectionAsync(collectionId, RequestHelpers.GetGuids(ids)).ConfigureAwait(false); + await _collectionManager.RemoveFromCollectionAsync(collectionId, ids).ConfigureAwait(false); return NoContent(); } } diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 9c222135d0..2dd504770d 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -74,8 +74,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -96,8 +96,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, @@ -133,7 +133,7 @@ namespace Jellyfin.Api.Controllers result = _libraryManager.GetGenres(query); } - var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes); + var shouldIncludeItemTypes = includeItemTypes.Length != 0; return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index d8d371ebc3..cff06aafe7 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -173,7 +173,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasImdbId, [FromQuery] bool? hasTmdbId, [FromQuery] bool? hasTvdbId, - [FromQuery] string? excludeItemIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] bool? recursive, @@ -181,34 +181,34 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, - [FromQuery] string? genres, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, [FromQuery] string? studios, [FromQuery] string? artists, - [FromQuery] string? excludeArtistIds, - [FromQuery] string? artistIds, - [FromQuery] string? albumArtistIds, - [FromQuery] string? contributingArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds, [FromQuery] string? albums, - [FromQuery] string? albumIds, - [FromQuery] string? ids, - [FromQuery] string? videoTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes, [FromQuery] string? minOfficialRating, [FromQuery] bool? isLocked, [FromQuery] bool? isPlaceHolder, @@ -223,8 +223,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, - [FromQuery] string? studioIds, - [FromQuery] string? genreIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { @@ -238,8 +238,9 @@ namespace Jellyfin.Api.Controllers .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); - if (string.Equals(includeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase)) + if (includeItemTypes.Length == 1 + && (includeItemTypes[0].Equals("Playlist", StringComparison.OrdinalIgnoreCase) + || includeItemTypes[0].Equals("BoxSet", StringComparison.OrdinalIgnoreCase))) { parentId = null; } @@ -262,7 +263,7 @@ namespace Jellyfin.Api.Controllers && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase)) { recursive = true; - includeItemTypes = "Playlist"; + includeItemTypes = new[] { "Playlist" }; } bool isInEnabledFolder = user!.GetPreference(PreferenceKind.EnabledFolders).Any(i => new Guid(i) == item.Id) @@ -291,14 +292,14 @@ namespace Jellyfin.Api.Controllers return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}."); } - if ((recursive.HasValue && recursive.Value) || !string.IsNullOrEmpty(ids) || !(item is UserRootFolder)) + if ((recursive.HasValue && recursive.Value) || ids.Length != 0 || !(item is UserRootFolder)) { var query = new InternalItemsQuery(user!) { IsPlayed = isPlayed, - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), + MediaTypes = mediaTypes, + IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = excludeItemTypes, Recursive = recursive ?? false, OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder), IsFavorite = isFavorite, @@ -330,28 +331,28 @@ namespace Jellyfin.Api.Controllers HasTrailer = hasTrailer, IsHD = isHd, Is4K = is4K, - Tags = RequestHelpers.Split(tags, '|', true), - OfficialRatings = RequestHelpers.Split(officialRatings, '|', true), - Genres = RequestHelpers.Split(genres, '|', true), - ArtistIds = RequestHelpers.GetGuids(artistIds), - AlbumArtistIds = RequestHelpers.GetGuids(albumArtistIds), - ContributingArtistIds = RequestHelpers.GetGuids(contributingArtistIds), - GenreIds = RequestHelpers.GetGuids(genreIds), - StudioIds = RequestHelpers.GetGuids(studioIds), + Tags = tags, + OfficialRatings = officialRatings, + Genres = genres, + ArtistIds = artistIds, + AlbumArtistIds = albumArtistIds, + ContributingArtistIds = contributingArtistIds, + GenreIds = genreIds, + StudioIds = studioIds, Person = person, - PersonIds = RequestHelpers.GetGuids(personIds), - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - Years = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(), + PersonIds = personIds, + PersonTypes = personTypes, + Years = years, ImageTypes = imageTypes, - VideoTypes = RequestHelpers.Split(videoTypes, ',', true).Select(v => Enum.Parse<VideoType>(v, true)).ToArray(), + VideoTypes = videoTypes, AdjacentTo = adjacentTo, - ItemIds = RequestHelpers.GetGuids(ids), + ItemIds = ids, MinCommunityRating = minCommunityRating, MinCriticRating = minCriticRating, ParentId = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId), ParentIndexNumber = parentIndexNumber, EnableTotalRecordCount = enableTotalRecordCount, - ExcludeItemIds = RequestHelpers.GetGuids(excludeItemIds), + ExcludeItemIds = excludeItemIds, DtoOptions = dtoOptions, SearchTerm = searchTerm, MinDateLastSaved = minDateLastSaved?.ToUniversalTime(), @@ -360,7 +361,7 @@ namespace Jellyfin.Api.Controllers MaxPremiereDate = maxPremiereDate?.ToUniversalTime(), }; - if (!string.IsNullOrWhiteSpace(ids) || !string.IsNullOrWhiteSpace(searchTerm)) + if (ids.Length != 0 || !string.IsNullOrWhiteSpace(searchTerm)) { query.CollapseBoxSetItems = false; } @@ -449,14 +450,14 @@ namespace Jellyfin.Api.Controllers } // ExcludeArtistIds - if (!string.IsNullOrWhiteSpace(excludeArtistIds)) + if (excludeArtistIds.Length != 0) { - query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds); + query.ExcludeArtistIds = excludeArtistIds; } - if (!string.IsNullOrWhiteSpace(albumIds)) + if (albumIds.Length != 0) { - query.AlbumIds = RequestHelpers.GetGuids(albumIds); + query.AlbumIds = albumIds; } // Albums @@ -533,12 +534,12 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { @@ -569,13 +570,13 @@ namespace Jellyfin.Api.Controllers ParentId = parentIdGuid, Recursive = true, DtoOptions = dtoOptions, - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), + MediaTypes = mediaTypes, IsVirtualItem = false, CollapseBoxSetItems = false, EnableTotalRecordCount = enableTotalRecordCount, AncestorIds = ancestorIds, - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), + IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = excludeItemTypes, SearchTerm = searchTerm }); diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 1b115d800b..3ff77e8e01 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -362,15 +362,14 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - public ActionResult DeleteItems([FromQuery] string? ids) + public ActionResult DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] ids) { - if (string.IsNullOrEmpty(ids)) + if (ids.Length == 0) { return NoContent(); } - var itemIds = RequestHelpers.Split(ids, ',', true); - foreach (var i in itemIds) + foreach (var i in ids) { var item = _libraryManager.GetItemById(i); var auth = _authContext.GetAuthorizationInfo(Request); @@ -691,7 +690,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetSimilarItems( [FromRoute, Required] Guid itemId, - [FromQuery] string? excludeArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, [FromQuery] Guid? userId, [FromQuery] int? limit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields) @@ -753,9 +752,9 @@ namespace Jellyfin.Api.Controllers }; // ExcludeArtistIds - if (!string.IsNullOrEmpty(excludeArtistIds)) + if (excludeArtistIds.Length != 0) { - query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds); + query.ExcludeArtistIds = excludeArtistIds; } List<BaseItem> itemsResult = _libraryManager.GetItemList(query); diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 29c0f1df4d..eb8b42b341 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -150,7 +150,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] SortOrder? sortOrder, [FromQuery] bool enableFavoriteSorting = false, [FromQuery] bool addCurrentProgram = true) @@ -175,7 +175,7 @@ namespace Jellyfin.Api.Controllers IsNews = isNews, IsKids = isKids, IsSports = isSports, - SortBy = RequestHelpers.Split(sortBy, ',', true), + SortBy = sortBy, SortOrder = sortOrder ?? SortOrder.Ascending, AddCurrentProgram = addCurrentProgram }, @@ -539,7 +539,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [Authorize(Policy = Policies.DefaultAuthorization)] public async Task<ActionResult<QueryResult<BaseItemDto>>> GetLiveTvPrograms( - [FromQuery] string? channelIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] channelIds, [FromQuery] Guid? userId, [FromQuery] DateTime? minStartDate, [FromQuery] bool? hasAired, @@ -556,8 +556,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] string? sortBy, [FromQuery] string? sortOrder, - [FromQuery] string? genres, - [FromQuery] string? genreIds, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -573,8 +573,7 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ChannelIds = RequestHelpers.Split(channelIds, ',', true) - .Select(i => new Guid(i)).ToArray(), + ChannelIds = channelIds, HasAired = hasAired, IsAiring = isAiring, EnableTotalRecordCount = enableTotalRecordCount, @@ -591,8 +590,8 @@ namespace Jellyfin.Api.Controllers IsKids = isKids, IsSports = isSports, SeriesTimerId = seriesTimerId, - Genres = RequestHelpers.Split(genres, '|', true), - GenreIds = RequestHelpers.GetGuids(genreIds) + Genres = genres, + GenreIds = genreIds }; if (librarySeriesId != null && !librarySeriesId.Equals(Guid.Empty)) @@ -628,8 +627,7 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ChannelIds = RequestHelpers.Split(body.ChannelIds, ',', true) - .Select(i => new Guid(i)).ToArray(), + ChannelIds = body.ChannelIds, HasAired = body.HasAired, IsAiring = body.IsAiring, EnableTotalRecordCount = body.EnableTotalRecordCount, @@ -646,8 +644,8 @@ namespace Jellyfin.Api.Controllers IsKids = body.IsKids, IsSports = body.IsSports, SeriesTimerId = body.SeriesTimerId, - Genres = RequestHelpers.Split(body.Genres, '|', true), - GenreIds = RequestHelpers.GetGuids(body.GenreIds) + Genres = body.Genres, + GenreIds = body.GenreIds }; if (!body.LibrarySeriesId.Equals(Guid.Empty)) @@ -703,7 +701,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, - [FromQuery] string? genreIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? enableUserData, [FromQuery] bool enableTotalRecordCount = true) @@ -723,7 +721,7 @@ namespace Jellyfin.Api.Controllers IsNews = isNews, IsSports = isSports, EnableTotalRecordCount = enableTotalRecordCount, - GenreIds = RequestHelpers.GetGuids(genreIds) + GenreIds = genreIds }; var dtoOptions = new DtoOptions { Fields = fields } diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 229d9ff022..8c61043028 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -74,8 +74,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -96,8 +96,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, @@ -123,7 +123,7 @@ namespace Jellyfin.Api.Controllers var result = _libraryManager.GetMusicGenres(query); - var shouldIncludeItemTypes = !string.IsNullOrWhiteSpace(includeItemTypes); + var shouldIncludeItemTypes = includeItemTypes.Length != 0; return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 6ac3e6417a..9dc79b3884 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -77,8 +77,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, - [FromQuery] string? excludePersonTypes, - [FromQuery] string? personTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludePersonTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, [FromQuery] string? appearsInItemId, [FromQuery] Guid? userId, [FromQuery] bool? enableImages = true) @@ -97,8 +97,8 @@ namespace Jellyfin.Api.Controllers var isFavoriteInFilters = filters.Any(f => f == ItemFilter.IsFavorite); var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery { - PersonTypes = RequestHelpers.Split(personTypes, ',', true), - ExcludePersonTypes = RequestHelpers.Split(excludePersonTypes, ',', true), + PersonTypes = personTypes, + ExcludePersonTypes = excludePersonTypes, NameContains = searchTerm, User = user, IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite, diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 4b3d8d3d39..bc47ecbd1c 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -63,11 +63,10 @@ namespace Jellyfin.Api.Controllers public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist( [FromBody, Required] CreatePlaylistDto createPlaylistRequest) { - Guid[] idGuidArray = RequestHelpers.GetGuids(createPlaylistRequest.Ids); var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest { Name = createPlaylistRequest.Name, - ItemIdList = idGuidArray, + ItemIdList = createPlaylistRequest.Ids, UserId = createPlaylistRequest.UserId, MediaType = createPlaylistRequest.MediaType }).ConfigureAwait(false); @@ -87,10 +86,10 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task<ActionResult> AddToPlaylist( [FromRoute, Required] Guid playlistId, - [FromQuery] string? ids, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, [FromQuery] Guid? userId) { - await _playlistManager.AddToPlaylistAsync(playlistId, RequestHelpers.GetGuids(ids), userId ?? Guid.Empty).ConfigureAwait(false); + await _playlistManager.AddToPlaylistAsync(playlistId, ids, userId ?? Guid.Empty).ConfigureAwait(false); return NoContent(); } @@ -122,9 +121,11 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="NoContentResult"/> on success.</returns> [HttpDelete("{playlistId}/Items")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task<ActionResult> RemoveFromPlaylist([FromRoute, Required] string playlistId, [FromQuery] string? entryIds) + public async Task<ActionResult> RemoveFromPlaylist( + [FromRoute, Required] string playlistId, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] entryIds) { - await _playlistManager.RemoveFromPlaylistAsync(playlistId, RequestHelpers.Split(entryIds, ',', true)).ConfigureAwait(false); + await _playlistManager.RemoveFromPlaylistAsync(playlistId, entryIds).ConfigureAwait(false); return NoContent(); } diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs index e75f0d06bb..076fe58f11 100644 --- a/Jellyfin.Api/Controllers/SearchController.cs +++ b/Jellyfin.Api/Controllers/SearchController.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -82,9 +83,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] Guid? userId, [FromQuery, Required] string searchTerm, - [FromQuery] string? includeItemTypes, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery] string? parentId, [FromQuery] bool? isMovie, [FromQuery] bool? isSeries, @@ -108,9 +109,9 @@ namespace Jellyfin.Api.Controllers IncludeStudios = includeStudios, StartIndex = startIndex, UserId = userId ?? Guid.Empty, - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), - ExcludeItemTypes = RequestHelpers.Split(excludeItemTypes, ',', true), - MediaTypes = RequestHelpers.Split(mediaTypes, ',', true), + IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = excludeItemTypes, + MediaTypes = mediaTypes, ParentId = parentId, IsKids = isKids, diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index e506ac7bf1..6c9b9050e6 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -160,12 +160,12 @@ namespace Jellyfin.Api.Controllers public ActionResult Play( [FromRoute, Required] string sessionId, [FromQuery, Required] PlayCommand playCommand, - [FromQuery, Required] string itemIds, + [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds, [FromQuery] long? startPositionTicks) { var playRequest = new PlayRequest { - ItemIds = RequestHelpers.GetGuids(itemIds), + ItemIds = itemIds, StartPositionTicks = startPositionTicks, PlayCommand = playCommand }; @@ -378,7 +378,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult PostCapabilities( [FromQuery] string? id, - [FromQuery] string? playableMediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] playableMediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] GeneralCommandType[] supportedCommands, [FromQuery] bool supportsMediaControl = false, [FromQuery] bool supportsSync = false, @@ -391,7 +391,7 @@ namespace Jellyfin.Api.Controllers _sessionManager.ReportCapabilities(id, new ClientCapabilities { - PlayableMediaTypes = RequestHelpers.Split(playableMediaTypes, ',', true), + PlayableMediaTypes = playableMediaTypes, SupportedCommands = supportedCommands, SupportsMediaControl = supportsMediaControl, SupportsSync = supportsSync, diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 27dcd51bc2..af28b4f597 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -73,8 +73,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -94,13 +94,10 @@ namespace Jellyfin.Api.Controllers var parentItem = _libraryManager.GetParentItem(parentId, userId); - var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true); - var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true); - var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypesArr, - IncludeItemTypes = includeItemTypesArr, + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, @@ -125,7 +122,7 @@ namespace Jellyfin.Api.Controllers } var result = _libraryManager.GetStudios(query); - var shouldIncludeItemTypes = !string.IsNullOrEmpty(includeItemTypes); + var shouldIncludeItemTypes = includeItemTypes.Length != 0; return RequestHelpers.CreateQueryResult(result, dtoOptions, _dtoService, shouldIncludeItemTypes, user); } diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index ad64adfbad..69292186e5 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -4,6 +4,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -58,8 +59,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryResult<BaseItemDto>> GetSuggestions( [FromRoute, Required] Guid userId, - [FromQuery] string? mediaType, - [FromQuery] string? type, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaType, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] type, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] bool enableTotalRecordCount = false) @@ -70,8 +71,8 @@ namespace Jellyfin.Api.Controllers var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user) { OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple<string, SortOrder>(i, SortOrder.Descending)).ToArray(), - MediaTypes = RequestHelpers.Split(mediaType!, ',', true), - IncludeItemTypes = RequestHelpers.Split(type!, ',', true), + MediaTypes = mediaType, + IncludeItemTypes = type, IsVirtualItem = false, StartIndex = startIndex, Limit = limit, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index d78adcbcdc..f09a6a91aa 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -139,7 +139,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasImdbId, [FromQuery] bool? hasTmdbId, [FromQuery] bool? hasTvdbId, - [FromQuery] string? excludeItemIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] bool? recursive, @@ -147,33 +147,33 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, - [FromQuery] string? genres, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, [FromQuery] string? studios, [FromQuery] string? artists, - [FromQuery] string? excludeArtistIds, - [FromQuery] string? artistIds, - [FromQuery] string? albumArtistIds, - [FromQuery] string? contributingArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds, [FromQuery] string? albums, - [FromQuery] string? albumIds, - [FromQuery] string? ids, - [FromQuery] string? videoTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes, [FromQuery] string? minOfficialRating, [FromQuery] bool? isLocked, [FromQuery] bool? isPlaceHolder, @@ -188,12 +188,12 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, - [FromQuery] string? studioIds, - [FromQuery] string? genreIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { - var includeItemTypes = "Trailer"; + var includeItemTypes = new[] { "Trailer" }; return _itemsController .GetItems( diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index e10f1fe912..5141aebca6 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Devices; @@ -96,7 +97,7 @@ namespace Jellyfin.Api.Controllers [ProducesAudioFile] public async Task<ActionResult> GetUniversalAudioStream( [FromRoute, Required] Guid itemId, - [FromQuery] string? container, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] container, [FromQuery] string? mediaSourceId, [FromQuery] string? deviceId, [FromQuery] Guid? userId, @@ -258,7 +259,7 @@ namespace Jellyfin.Api.Controllers } private DeviceProfile GetDeviceProfile( - string? container, + string[] containers, string? transcodingContainer, string? audioCodec, string? transcodingProtocol, @@ -270,7 +271,6 @@ namespace Jellyfin.Api.Controllers { var deviceProfile = new DeviceProfile(); - var containers = RequestHelpers.Split(container, ',', true); int len = containers.Length; var directPlayProfiles = new DirectPlayProfile[len]; for (int i = 0; i < len; i++) @@ -327,7 +327,7 @@ namespace Jellyfin.Api.Controllers if (conditions.Count > 0) { // codec profile - codecProfiles.Add(new CodecProfile { Type = CodecType.Audio, Container = container, Conditions = conditions.ToArray() }); + codecProfiles.Add(new CodecProfile { Type = CodecType.Audio, Container = string.Join(',', containers), Conditions = conditions.ToArray() }); } deviceProfile.CodecProfiles = codecProfiles.ToArray(); diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index cfd8511297..a7fb4f116c 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -269,7 +269,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid userId, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, @@ -296,7 +296,7 @@ namespace Jellyfin.Api.Controllers new LatestItemsQuery { GroupItems = groupItems, - IncludeItemTypes = RequestHelpers.Split(includeItemTypes, ',', true), + IncludeItemTypes = includeItemTypes, IsPlayed = isPlayed, Limit = limit, ParentId = parentId ?? Guid.Empty, diff --git a/Jellyfin.Api/Controllers/UserViewsController.cs b/Jellyfin.Api/Controllers/UserViewsController.cs index d575bfc3b8..60fd1df013 100644 --- a/Jellyfin.Api/Controllers/UserViewsController.cs +++ b/Jellyfin.Api/Controllers/UserViewsController.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.UserViewDtos; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -67,7 +68,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryResult<BaseItemDto>> GetUserViews( [FromRoute, Required] Guid userId, [FromQuery] bool? includeExternalContent, - [FromQuery] string? presetViews, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] presetViews, [FromQuery] bool includeHidden = false) { var query = new UserViewQuery @@ -81,9 +82,9 @@ namespace Jellyfin.Api.Controllers query.IncludeExternalContent = includeExternalContent.Value; } - if (!string.IsNullOrWhiteSpace(presetViews)) + if (presetViews.Length != 0) { - query.PresetViews = RequestHelpers.Split(presetViews, ',', true); + query.PresetViews = presetViews; } var app = _authContext.GetAuthorizationInfo(Request).Client ?? string.Empty; diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 4de7aac71d..dd5e70a50a 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -10,6 +10,7 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; @@ -203,9 +204,9 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - public async Task<ActionResult> MergeVersions([FromQuery, Required] string itemIds) + public async Task<ActionResult> MergeVersions([FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds) { - var items = RequestHelpers.Split(itemIds, ',', true) + var items = itemIds .Select(i => _libraryManager.GetItemById(i)) .OfType<Video>() .OrderBy(i => i.Id) diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 1b38e399d6..9c3ecb4cee 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -73,9 +73,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery] string? sortBy, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -103,19 +103,15 @@ namespace Jellyfin.Api.Controllers IList<BaseItem> items; - var excludeItemTypesArr = RequestHelpers.Split(excludeItemTypes, ',', true); - var includeItemTypesArr = RequestHelpers.Split(includeItemTypes, ',', true); - var mediaTypesArr = RequestHelpers.Split(mediaTypes, ',', true); - var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypesArr, - IncludeItemTypes = includeItemTypesArr, - MediaTypes = mediaTypesArr, + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, + MediaTypes = mediaTypes, DtoOptions = dtoOptions }; - bool Filter(BaseItem i) => FilterItem(i, excludeItemTypesArr, includeItemTypesArr, mediaTypesArr); + bool Filter(BaseItem i) => FilterItem(i, excludeItemTypes, includeItemTypes, mediaTypes); if (parentItem.IsFolder) { diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index f06f038ab5..efce11f8a7 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -122,49 +122,6 @@ namespace Jellyfin.Api.Helpers return session; } - /// <summary> - /// Get Guid array from string. - /// </summary> - /// <param name="value">String value.</param> - /// <returns>Guid array.</returns> - internal static Guid[] GetGuids(string? value) - { - if (value == null) - { - return Array.Empty<Guid>(); - } - - return Split(value, ',', true) - .Select(i => new Guid(i)) - .ToArray(); - } - - /// <summary> - /// Gets the item fields. - /// </summary> - /// <param name="fields">The fields string.</param> - /// <returns>IEnumerable{ItemFields}.</returns> - internal static ItemFields[] GetItemFields(string? fields) - { - if (string.IsNullOrEmpty(fields)) - { - return Array.Empty<ItemFields>(); - } - - return Split(fields, ',', true) - .Select(v => - { - if (Enum.TryParse(v, true, out ItemFields value)) - { - return (ItemFields?)value; - } - - return null; - }).Where(i => i.HasValue) - .Select(i => i!.Value) - .ToArray(); - } - internal static QueryResult<BaseItemDto> CreateQueryResult( QueryResult<(BaseItem, ItemCounts)> result, DtoOptions dtoOptions, diff --git a/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs new file mode 100644 index 0000000000..a42e0e4da8 --- /dev/null +++ b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.ModelBinders +{ + /// <summary> + /// Comma delimited array model binder. + /// Returns an empty array of specified type if there is no query parameter. + /// </summary> + public class PipeDelimitedArrayModelBinder : IModelBinder + { + private readonly ILogger<PipeDelimitedArrayModelBinder> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="PipeDelimitedArrayModelBinder"/> class. + /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger{PipeDelimitedArrayModelBinder}"/> interface.</param> + public PipeDelimitedArrayModelBinder(ILogger<PipeDelimitedArrayModelBinder> logger) + { + _logger = logger; + } + + /// <inheritdoc/> + public Task BindModelAsync(ModelBindingContext bindingContext) + { + var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0]; + var converter = TypeDescriptor.GetConverter(elementType); + + if (valueProviderResult.Length > 1) + { + var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter); + bindingContext.Result = ModelBindingResult.Success(typedValues); + } + else + { + var value = valueProviderResult.FirstValue; + + if (value != null) + { + var splitValues = value.Split('|', StringSplitOptions.RemoveEmptyEntries); + var typedValues = GetParsedResult(splitValues, elementType, converter); + bindingContext.Result = ModelBindingResult.Success(typedValues); + } + else + { + var emptyResult = Array.CreateInstance(elementType, 0); + bindingContext.Result = ModelBindingResult.Success(emptyResult); + } + } + + return Task.CompletedTask; + } + + private Array GetParsedResult(IReadOnlyList<string> values, Type elementType, TypeConverter converter) + { + var parsedValues = new object?[values.Count]; + var convertedCount = 0; + for (var i = 0; i < values.Count; i++) + { + try + { + parsedValues[i] = converter.ConvertFromString(values[i].Trim()); + convertedCount++; + } + catch (FormatException e) + { + _logger.LogWarning(e, "Error converting value."); + } + } + + var typedValues = Array.CreateInstance(elementType, convertedCount); + var typedValueIndex = 0; + for (var i = 0; i < parsedValues.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; + } + } +} diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index 5ca4408d18..a47ae926c1 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -16,7 +16,8 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// <summary> /// Gets or sets the channels to return guide information for. /// </summary> - public string? ChannelIds { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList<Guid> ChannelIds { get; set; } = Array.Empty<Guid>(); /// <summary> /// Gets or sets optional. Filter by user id. @@ -115,12 +116,14 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// <summary> /// Gets or sets the genres to return guide information for. /// </summary> - public string? Genres { get; set; } + [JsonConverter(typeof(JsonPipeDelimitedArrayConverterFactory))] + public IReadOnlyList<string> Genres { get; set; } = Array.Empty<string>(); /// <summary> /// Gets or sets the genre ids to return guide information for. /// </summary> - public string? GenreIds { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList<Guid> GenreIds { get; set; } = Array.Empty<Guid>(); /// <summary> /// Gets or sets include image information in output. diff --git a/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs index 0d67c86f71..d0d6889fc8 100644 --- a/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs +++ b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs @@ -1,4 +1,7 @@ using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; namespace Jellyfin.Api.Models.PlaylistDtos { @@ -15,7 +18,8 @@ namespace Jellyfin.Api.Models.PlaylistDtos /// <summary> /// Gets or sets item ids to add to the playlist. /// </summary> - public string? Ids { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList<Guid> Ids { get; set; } = Array.Empty<Guid>(); /// <summary> /// Gets or sets the user id. diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs new file mode 100644 index 0000000000..0eb6916a5a --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -0,0 +1,74 @@ +using System; +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Convert Pipe delimited string to array of type. + /// </summary> + /// <typeparam name="T">Type to convert to.</typeparam> + public class JsonPipeDelimitedArrayConverter<T> : JsonConverter<T[]> + { + private readonly TypeConverter _typeConverter; + + /// <summary> + /// Initializes a new instance of the <see cref="JsonPipeDelimitedArrayConverter{T}"/> class. + /// </summary> + public JsonPipeDelimitedArrayConverter() + { + _typeConverter = TypeDescriptor.GetConverter(typeof(T)); + } + + /// <inheritdoc /> + public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var stringEntries = reader.GetString()?.Split('|', StringSplitOptions.RemoveEmptyEntries); + if (stringEntries == null || stringEntries.Length == 0) + { + return Array.Empty<T>(); + } + + var parsedValues = new object[stringEntries.Length]; + var convertedCount = 0; + for (var i = 0; i < stringEntries.Length; i++) + { + try + { + parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim()); + convertedCount++; + } + catch (FormatException) + { + // TODO log when upgraded to .Net5 + // _logger.LogWarning(e, "Error converting value."); + } + } + + var typedValues = new T[convertedCount]; + var typedValueIndex = 0; + for (var i = 0; i < stringEntries.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; + } + + return JsonSerializer.Deserialize<T[]>(ref reader, options); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value, options); + } + } +} diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs new file mode 100644 index 0000000000..5e77223ef2 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Json Pipe delimited array converter factory. + /// </summary> + /// <remarks> + /// This must be applied as an attribute, adding to the JsonConverter list causes stack overflow. + /// </remarks> + public class JsonPipeDelimitedArrayConverterFactory : JsonConverterFactory + { + /// <inheritdoc /> + public override bool CanConvert(Type typeToConvert) + { + return true; + } + + /// <inheritdoc /> + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0]; + return (JsonConverter)Activator.CreateInstance(typeof(JsonPipeDelimitedArrayConverter<>).MakeGenericType(structType)); + } + } +} diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index b67a549835..bb9e0b8c02 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -20,7 +20,7 @@ <ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="5.0.0" /> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.8" /> </ItemGroup> diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index a76c8a376b..ead4392f39 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1067,12 +1067,12 @@ namespace MediaBrowser.Controller.Entities return false; } - if (request.Genres.Length > 0) + if (request.Genres.Count > 0) { return false; } - if (request.GenreIds.Length > 0) + if (request.GenreIds.Count > 0) { return false; } @@ -1177,7 +1177,7 @@ namespace MediaBrowser.Controller.Entities return false; } - if (request.GenreIds.Length > 0) + if (request.GenreIds.Count > 0) { return false; } diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 904752a229..270217356f 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Controller.Entities public string[] ExcludeInheritedTags { get; set; } - public string[] Genres { get; set; } + public IReadOnlyList<string> Genres { get; set; } public bool? IsSpecialSeason { get; set; } @@ -116,7 +116,7 @@ namespace MediaBrowser.Controller.Entities public Guid[] StudioIds { get; set; } - public Guid[] GenreIds { get; set; } + public IReadOnlyList<Guid> GenreIds { get; set; } public ImageType[] ImageTypes { get; set; } @@ -162,7 +162,7 @@ namespace MediaBrowser.Controller.Entities public double? MinCommunityRating { get; set; } - public Guid[] ChannelIds { get; set; } + public IReadOnlyList<Guid> ChannelIds { get; set; } public int? ParentIndexNumber { get; set; } diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index a262fee15d..4e33a6bbde 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -791,7 +791,7 @@ namespace MediaBrowser.Controller.Entities } // Apply genre filter - if (query.Genres.Length > 0 && !query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase))) + if (query.Genres.Count > 0 && !query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase))) { return false; } @@ -822,7 +822,7 @@ namespace MediaBrowser.Controller.Entities } // Apply genre filter - if (query.GenreIds.Length > 0 && !query.GenreIds.Any(id => + if (query.GenreIds.Count > 0 && !query.GenreIds.Any(id => { var genreItem = libraryManager.GetItemById(id); return genreItem != null && item.Genres.Contains(genreItem.Name, StringComparer.OrdinalIgnoreCase); diff --git a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs index fbf2c52131..f6c5920709 100644 --- a/MediaBrowser.Controller/Playlists/IPlaylistManager.cs +++ b/MediaBrowser.Controller/Playlists/IPlaylistManager.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.Playlists /// <param name="itemIds">The item ids.</param> /// <param name="userId">The user identifier.</param> /// <returns>Task.</returns> - Task AddToPlaylistAsync(Guid playlistId, ICollection<Guid> itemIds, Guid userId); + Task AddToPlaylistAsync(Guid playlistId, IReadOnlyCollection<Guid> itemIds, Guid userId); /// <summary> /// Removes from playlist. diff --git a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs index ef435b21ec..e8ee494034 100644 --- a/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs +++ b/MediaBrowser.Model/Playlists/PlaylistCreationRequest.cs @@ -2,6 +2,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; namespace MediaBrowser.Model.Playlists { @@ -9,15 +10,10 @@ namespace MediaBrowser.Model.Playlists { public string Name { get; set; } - public Guid[] ItemIdList { get; set; } + public IReadOnlyList<Guid> ItemIdList { get; set; } = Array.Empty<Guid>(); public string MediaType { get; set; } public Guid UserId { get; set; } - - public PlaylistCreationRequest() - { - ItemIdList = Array.Empty<Guid>(); - } } } diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs new file mode 100644 index 0000000000..938d19a154 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/ModelBinders/PipeDelimitedArrayModelBinderTests.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading.Tasks; +using Jellyfin.Api.ModelBinders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Primitives; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.ModelBinders +{ + public sealed class PipeDelimitedArrayModelBinderTests + { + [Fact] + public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedStringArrayQuery() + { + var queryParamName = "test"; + IReadOnlyList<string> queryParamValues = new[] { "lol", "xd" }; + var queryParamString = "lol|xd"; + var queryParamType = typeof(string[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<string>?)bindingContextMock.Object?.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_CorrectlyBindsValidDelimitedIntArrayQuery() + { + var queryParamName = "test"; + IReadOnlyList<int> queryParamValues = new[] { 42, 0 }; + var queryParamString = "42|0"; + var queryParamType = typeof(int[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<int>?)bindingContextMock.Object.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedEnumArrayQuery() + { + var queryParamName = "test"; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; + var queryParamString = "How|Much"; + var queryParamType = typeof(TestType[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_CorrectlyBindsValidPipeDelimitedEnumArrayQueryWithDoublePipes() + { + var queryParamName = "test"; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; + var queryParamString = "How||Much"; + var queryParamType = typeof(TestType[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_CorrectlyBindsValidEnumArrayQuery() + { + var queryParamName = "test"; + IReadOnlyList<TestType> queryParamValues = new[] { TestType.How, TestType.Much }; + var queryParamString1 = "How"; + var queryParamString2 = "Much"; + var queryParamType = typeof(TestType[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> + { + { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) }, + }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_CorrectlyBindsEmptyEnumArrayQuery() + { + var queryParamName = "test"; + IReadOnlyList<TestType> queryParamValues = Array.Empty<TestType>(); + var queryParamType = typeof(TestType[]); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> + { + { queryParamName, new StringValues(value: null) }, + }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Equal((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model, queryParamValues); + } + + [Fact] + public async Task BindModelAsync_EnumArrayQuery_BindValidOnly() + { + var queryParamName = "test"; + var queryParamString = "🔥|😢"; + var queryParamType = typeof(IReadOnlyList<TestType>); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { queryParamName, new StringValues(queryParamString) } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Empty((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model); + } + + [Fact] + public async Task BindModelAsync_EnumArrayQuery_BindValidOnly_2() + { + var queryParamName = "test"; + var queryParamString1 = "How"; + var queryParamString2 = "😱"; + var queryParamType = typeof(IReadOnlyList<TestType>); + + var modelBinder = new PipeDelimitedArrayModelBinder(new NullLogger<PipeDelimitedArrayModelBinder>()); + + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> + { + { queryParamName, new StringValues(new[] { queryParamString1, queryParamString2 }) }, + }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(queryParamName); + bindingContextMock.Setup(b => b.ModelType).Returns(queryParamType); + bindingContextMock.SetupProperty(b => b.Result); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + Assert.True(bindingContextMock.Object.Result.IsModelSet); + Assert.Single((IReadOnlyList<TestType>?)bindingContextMock.Object.Result.Model); + } + } +} From 2a0578ce1a711c712beee2bdf04610bf9c7742d6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 16 Nov 2020 20:37:43 -0700 Subject: [PATCH 0385/1930] Add missing manual splits --- Jellyfin.Api/Controllers/ArtistsController.cs | 12 +++--- .../Controllers/ChannelsController.cs | 8 +--- Jellyfin.Api/Controllers/FilterController.cs | 41 ++++++++++--------- Jellyfin.Api/Controllers/ItemsController.cs | 30 +++++++------- 4 files changed, 45 insertions(+), 46 deletions(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 0123bb8fa3..f684c649af 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -105,7 +105,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? person, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, - [FromQuery] string? studios, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, @@ -170,9 +170,9 @@ namespace Jellyfin.Api.Controllers } // Studios - if (!string.IsNullOrEmpty(studios)) + if (studios.Length != 0) { - query.StudioIds = studios.Split('|').Select(i => + query.StudioIds = studios.Select(i => { try { @@ -309,7 +309,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? person, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, - [FromQuery] string? studios, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, [FromQuery] Guid? userId, [FromQuery] string? nameStartsWithOrGreater, @@ -374,9 +374,9 @@ namespace Jellyfin.Api.Controllers } // Studios - if (!string.IsNullOrEmpty(studios)) + if (studios.Length != 0) { - query.StudioIds = studios.Split('|').Select(i => + query.StudioIds = studios.Select(i => { try { diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index ec9d7cdce1..c4dc44cc36 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -198,7 +198,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? channelIds) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] channelIds) { var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -208,11 +208,7 @@ namespace Jellyfin.Api.Controllers { Limit = limit, StartIndex = startIndex, - ChannelIds = (channelIds ?? string.Empty) - .Split(',') - .Where(i => !string.IsNullOrWhiteSpace(i)) - .Select(i => new Guid(i)) - .ToArray(), + ChannelIds = channelIds, DtoOptions = new DtoOptions { Fields = fields } }; diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 008bb58d16..c97a1ed146 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using Jellyfin.Api.Constants; +using Jellyfin.Api.ModelBinders; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; @@ -50,8 +51,8 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryFiltersLegacy> GetQueryFiltersLegacy( [FromQuery] Guid? userId, [FromQuery] string? parentId, - [FromQuery] string? includeItemTypes, - [FromQuery] string? mediaTypes) + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes) { var parentItem = string.IsNullOrEmpty(parentId) ? null @@ -61,10 +62,11 @@ namespace Jellyfin.Api.Controllers ? _userManager.GetUserById(userId.Value) : null; - if (string.Equals(includeItemTypes, nameof(BoxSet), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(Playlist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(Trailer), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, "Program", StringComparison.OrdinalIgnoreCase)) + if (includeItemTypes.Length == 1 + && (string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) { parentItem = null; } @@ -78,8 +80,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery { User = user, - MediaTypes = (mediaTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), - IncludeItemTypes = (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), + MediaTypes = mediaTypes, + IncludeItemTypes = includeItemTypes, Recursive = true, EnableTotalRecordCount = false, DtoOptions = new DtoOptions @@ -139,7 +141,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<QueryFilters> GetQueryFilters( [FromQuery] Guid? userId, [FromQuery] string? parentId, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isAiring, [FromQuery] bool? isMovie, [FromQuery] bool? isSports, @@ -156,10 +158,11 @@ namespace Jellyfin.Api.Controllers ? _userManager.GetUserById(userId.Value) : null; - if (string.Equals(includeItemTypes, nameof(BoxSet), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(Playlist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(Trailer), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, "Program", StringComparison.OrdinalIgnoreCase)) + if (includeItemTypes.Length == 1 + && (string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) { parentItem = null; } @@ -167,8 +170,7 @@ namespace Jellyfin.Api.Controllers var filters = new QueryFilters(); var genreQuery = new InternalItemsQuery(user) { - IncludeItemTypes = - (includeItemTypes ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), + IncludeItemTypes = includeItemTypes, DtoOptions = new DtoOptions { Fields = Array.Empty<ItemFields>(), @@ -192,10 +194,11 @@ namespace Jellyfin.Api.Controllers genreQuery.Parent = parentItem; } - if (string.Equals(includeItemTypes, nameof(MusicAlbum), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(MusicVideo), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(MusicArtist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes, nameof(Audio), StringComparison.OrdinalIgnoreCase)) + if (includeItemTypes.Length == 1 + && (string.Equals(includeItemTypes[0], nameof(MusicAlbum), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(MusicVideo), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(MusicArtist), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Audio), StringComparison.OrdinalIgnoreCase))) { filters.Genres = _libraryManager.GetMusicGenres(genreQuery).Items.Select(i => new NameGuidPair { diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index cff06aafe7..5d2277ed47 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -159,7 +159,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasParentalRating, [FromQuery] bool? isHd, [FromQuery] bool? is4K, - [FromQuery] string? locationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] locationTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, @@ -199,13 +199,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? person, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, - [FromQuery] string? studios, - [FromQuery] string? artists, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds, - [FromQuery] string? albums, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes, @@ -219,7 +219,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, [FromQuery] bool? is3D, - [FromQuery] string? seriesStatus, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, @@ -401,9 +401,9 @@ namespace Jellyfin.Api.Controllers } // Filter by Series Status - if (!string.IsNullOrEmpty(seriesStatus)) + if(seriesStatus.Length != 0) { - query.SeriesStatuses = seriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray(); + query.SeriesStatuses = seriesStatus; } // ExcludeLocationTypes @@ -412,9 +412,9 @@ namespace Jellyfin.Api.Controllers query.IsVirtualItem = false; } - if (!string.IsNullOrEmpty(locationTypes)) + if (locationTypes.Length != 0) { - var requestedLocationTypes = locationTypes.Split(','); + var requestedLocationTypes = locationTypes; if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4) { query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual.ToString()); @@ -434,9 +434,9 @@ namespace Jellyfin.Api.Controllers } // Artists - if (!string.IsNullOrEmpty(artists)) + if (artists.Length != 0) { - query.ArtistIds = artists.Split('|').Select(i => + query.ArtistIds = artists.Select(i => { try { @@ -461,18 +461,18 @@ namespace Jellyfin.Api.Controllers } // Albums - if (!string.IsNullOrEmpty(albums)) + if (albums.Length != 0) { - query.AlbumIds = albums.Split('|').SelectMany(i => + query.AlbumIds = albums.SelectMany(i => { return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = i, Limit = 1 }); }).ToArray(); } // Studios - if (!string.IsNullOrEmpty(studios)) + if (studios.Length != 0) { - query.StudioIds = studios.Split('|').Select(i => + query.StudioIds = studios.Select(i => { try { From 3b68ce1183c89cf79b38895d3401b7005674f79c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 16 Nov 2020 20:45:09 -0700 Subject: [PATCH 0386/1930] Fix build --- Jellyfin.Api/Controllers/ItemsController.cs | 6 +++--- Jellyfin.Api/Controllers/TrailersController.cs | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 5d2277ed47..43282b6851 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -159,7 +159,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasParentalRating, [FromQuery] bool? isHd, [FromQuery] bool? is4K, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] locationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, @@ -401,7 +401,7 @@ namespace Jellyfin.Api.Controllers } // Filter by Series Status - if(seriesStatus.Length != 0) + if (seriesStatus.Length != 0) { query.SeriesStatuses = seriesStatus; } @@ -417,7 +417,7 @@ namespace Jellyfin.Api.Controllers var requestedLocationTypes = locationTypes; if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4) { - query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual.ToString()); + query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual); } } diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index f09a6a91aa..8d08d5c697 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -125,7 +125,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasParentalRating, [FromQuery] bool? isHd, [FromQuery] bool? is4K, - [FromQuery] string? locationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, @@ -164,13 +164,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? person, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, - [FromQuery] string? studios, - [FromQuery] string? artists, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] studios, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] artists, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds, - [FromQuery] string? albums, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] albums, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes, @@ -184,7 +184,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, [FromQuery] bool? is3D, - [FromQuery] string? seriesStatus, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, From c770b9e0c68661b5e8f4ef8289a6ef089799d6ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= <oddstr13@openshell.no> Date: Tue, 17 Nov 2020 05:27:14 +0100 Subject: [PATCH 0387/1930] Use .NET 5.0 in the Nuget pipeline --- .ci/azure-pipelines-package.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 0dc604a794..d478516b83 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -188,6 +188,12 @@ jobs: vmImage: 'ubuntu-latest' steps: + - task: UseDotNet@2 + displayName: 'Use .NET 5.0 sdk' + inputs: + packageType: 'sdk' + version: '5.0.x' + - task: DotNetCoreCLI@2 displayName: 'Build Stable Nuget packages' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') From bb46f24bb3301869fcefa5dd7892d0e303181050 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= <lukas@kucharczyk.xyz> Date: Tue, 17 Nov 2020 09:43:46 +0000 Subject: [PATCH 0388/1930] Translated using Weblate (Czech) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/cs/ --- Emby.Server.Implementations/Localization/Core/cs.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index fb31b01ff8..7752671837 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Knihovna", "TasksMaintenanceCategory": "Údržba", "TaskCleanActivityLogDescription": "Smazat záznamy o aktivitě, které jsou starší než zadaná doba.", - "TaskCleanActivityLog": "Smazat záznam aktivity" + "TaskCleanActivityLog": "Smazat záznam aktivity", + "Undefined": "Nedefinované", + "Forced": "Vynucené", + "Default": "Výchozí" } From 7cbcce06382e8314ac778095dcfe9212ab083358 Mon Sep 17 00:00:00 2001 From: Sverre <sverre@sverrecraft.com> Date: Tue, 17 Nov 2020 09:48:52 +0000 Subject: [PATCH 0389/1930] =?UTF-8?q?Translated=20using=20Weblate=20(Norwe?= =?UTF-8?q?gian=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Transl?= =?UTF-8?q?ate-URL:=20https://translate.jellyfin.org/projects/jellyfin/jel?= =?UTF-8?q?lyfin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Emby.Server.Implementations/Localization/Core/nb.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index 245c3cd636..3b016fe62a 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -113,5 +113,9 @@ "TaskRefreshPeople": "Oppfrisk personer", "TaskCleanLogsDescription": "Sletter loggfiler som er eldre enn {0} dager gamle.", "TaskCleanLogs": "Tøm loggmappe", - "TaskRefreshLibraryDescription": "Skanner mediebibliotekene dine for nye filer og oppdaterer metadata." + "TaskRefreshLibraryDescription": "Skanner mediebibliotekene dine for nye filer og oppdaterer metadata.", + "TaskCleanActivityLog": "Tøm aktivitetslogg", + "Undefined": "Udefinert", + "Forced": "Tvungen", + "Default": "Standard" } From fc3d6278be89b695aa79dc61d7f1226d4d6e441b Mon Sep 17 00:00:00 2001 From: Thomas Schwery <thomas@inf3.ch> Date: Tue, 17 Nov 2020 10:16:24 +0000 Subject: [PATCH 0390/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index cc9243f37b..3d5d69f36a 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Bibliothèque", "TasksMaintenanceCategory": "Maintenance", "TaskCleanActivityLogDescription": "Supprime les entrées du journal d'activité antérieures à l'âge configuré.", - "TaskCleanActivityLog": "Nettoyer le journal d'activité" + "TaskCleanActivityLog": "Nettoyer le journal d'activité", + "Undefined": "Non défini", + "Forced": "Forcé", + "Default": "Par défaut" } From d481c35cad8f4ed7444744f051620c5b3ed9fd2c Mon Sep 17 00:00:00 2001 From: Stepan <ste.martinek+git@gmail.com> Date: Tue, 17 Nov 2020 13:06:56 +0100 Subject: [PATCH 0391/1930] Merge fix --- Emby.Naming/Video/VideoFileInfo.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 7d7411a563..eb2353440a 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,3 +1,4 @@ +#nullable enable using MediaBrowser.Model.Entities; namespace Emby.Naming.Video @@ -21,7 +22,7 @@ namespace Emby.Naming.Video /// <param name="isStub">Is Stub.</param> /// <param name="stubType">Stub type.</param> /// <param name="isDirectory">Is directory.</param> - public VideoFileInfo(string name, string? path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default) + public VideoFileInfo(string name, string path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default) { Path = path; Container = container; @@ -40,7 +41,7 @@ namespace Emby.Naming.Video /// Gets or sets the path. /// </summary> /// <value>The path.</value> - public string? Path { get; set; } + public string Path { get; set; } /// <summary> /// Gets or sets the container. From a6ad36b57a78984d4a76fac2f760524a7692511b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Tue, 17 Nov 2020 14:20:18 +0100 Subject: [PATCH 0392/1930] Don't scale images extracted by ffmpeg --- .../Encoder/MediaEncoder.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 5a3a9185d7..d804e64431 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -520,29 +520,29 @@ namespace MediaBrowser.MediaEncoding.Encoder var tempExtractPath = Path.Combine(_configurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg"); Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath)); - // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. + // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar - var vf = "scale=600:trunc(600/dar/2)*2"; + var vf = String.Empty; if (threedFormat.HasValue) { switch (threedFormat.Value) { case Video3DFormat.HalfSideBySide: - vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. + vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. break; case Video3DFormat.FullSideBySide: - vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600. + vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + // fsbs crop width in half,set the display aspect,crop out any black bars we may have made break; case Video3DFormat.HalfTopAndBottom: - vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600 + vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made break; case Video3DFormat.FullTopAndBottom: - vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600 + vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made break; default: break; From d7cdaeea7dfc7dd556765a0fb224d8428bc38c0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Tue, 17 Nov 2020 14:26:05 +0100 Subject: [PATCH 0393/1930] Use all system cores when threads are set to auto or bigger than the amount of system's cores --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 5846a603a2..3a9f57c55b 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2344,7 +2344,7 @@ namespace MediaBrowser.Controller.MediaEncoding // Automatic if (threads <= 0 || threads >= Environment.ProcessorCount) { - return 0; + return Environment.ProcessorCount; } return threads; From 5fa4cce4cce2bcc6ac2a2cca884af5e659c836f0 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 06:57:25 -0700 Subject: [PATCH 0394/1930] Use ALL the decompression methods. --- MediaBrowser.Common/Net/DefaultHttpClientHandler.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs b/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs index e189d6e706..f1c5f24772 100644 --- a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs +++ b/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs @@ -13,8 +13,7 @@ namespace MediaBrowser.Common.Net /// </summary> public DefaultHttpClientHandler() { - // TODO change to DecompressionMethods.All with .NET5 - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; + AutomaticDecompression = DecompressionMethods.All; } } } From 08279e91badebf34e34735b8f512ba585fb336d6 Mon Sep 17 00:00:00 2001 From: Cody Robibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 07:08:22 -0700 Subject: [PATCH 0395/1930] Update MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs --- MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index e99c48a704..2c5abe933f 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -404,9 +404,6 @@ namespace MediaBrowser.Controller.MediaEncoding { // Don't exceed what the encoder supports // Seeing issues of attempting to encode to 88200 - // return Math.Min(44100, BaseRequest.AudioSampleRate.Value); - - // I don't see any reason why limiting the sample rate to a maximum of 44100 ! return BaseRequest.AudioSampleRate.Value; } From 04a712ab1d56a29a31e2c4991c16d338348762f4 Mon Sep 17 00:00:00 2001 From: martinek-stepan <68327580+martinek-stepan@users.noreply.github.com> Date: Tue, 17 Nov 2020 15:11:32 +0100 Subject: [PATCH 0396/1930] Update Emby.Naming/Video/VideoFileInfo.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Naming/Video/VideoFileInfo.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index eb2353440a..1457db7378 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,4 +1,3 @@ -#nullable enable using MediaBrowser.Model.Entities; namespace Emby.Naming.Video From 94cae4f1455995a0a35df8d1b7c64760387e5b64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Tue, 17 Nov 2020 14:46:23 +0100 Subject: [PATCH 0397/1930] Specify threads to ffmpeg properly --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 12 +++++++++--- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 14 ++++++++------ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 3e5457dbd4..4726211d27 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -9,6 +9,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; @@ -25,6 +26,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly IServerApplicationPaths _appPaths; private readonly IJsonSerializer _json; private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>(); + private readonly IServerConfigurationManager _serverConfigurationManager; private bool _hasExited; private Stream _logFileStream; @@ -35,12 +37,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV ILogger logger, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, - IJsonSerializer json) + IJsonSerializer json, + IServerConfigurationManager serverConfigurationManager) { _logger = logger; _mediaEncoder = mediaEncoder; _appPaths = appPaths; _json = json; + _serverConfigurationManager = serverConfigurationManager; } private static bool CopySubtitles => false; @@ -179,15 +183,17 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var outputParam = string.Empty; + var threads = EncodingHelper.GetNumberOfThreads(null, _serverConfigurationManager.GetEncodingOptions(), null); var commandLineArgs = string.Format( CultureInfo.InvariantCulture, - "-i \"{0}\" {2} -map_metadata -1 -threads 0 {3}{4}{5} -y \"{1}\"", + "-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"", inputTempFile, targetFile, videoArgs, GetAudioArgs(mediaSource), subtitleArgs, - outputParam); + outputParam, + threads); return inputModifier + " " + commandLineArgs; } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index d804e64431..2b4712b2dc 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -64,6 +64,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private string _ffmpegPath = string.Empty; private string _ffprobePath; + private int threads; public MediaEncoder( ILogger<MediaEncoder> logger, @@ -129,6 +130,7 @@ namespace MediaBrowser.MediaEncoding.Encoder SetAvailableDecoders(validator.GetDecoders()); SetAvailableEncoders(validator.GetEncoders()); SetAvailableHwaccels(validator.GetHwaccels()); + threads = EncodingHelper.GetNumberOfThreads(null, _configurationManager.GetEncodingOptions(), null); } _logger.LogInformation("FFmpeg: {EncoderLocation}: {FfmpegPath}", EncoderLocation, _ffmpegPath ?? string.Empty); @@ -377,9 +379,9 @@ namespace MediaBrowser.MediaEncoding.Encoder CancellationToken cancellationToken) { var args = extractChapters - ? "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_chapters -show_format" - : "{0} -i {1} -threads 0 -v warning -print_format json -show_streams -show_format"; - args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath).Trim(); + ? "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_chapters -show_format" + : "{0} -i {1} -threads {2} -v warning -print_format json -show_streams -show_format"; + args = string.Format(CultureInfo.InvariantCulture, args, probeSizeArgument, inputPath, threads).Trim(); var process = new Process { @@ -555,8 +557,8 @@ namespace MediaBrowser.MediaEncoding.Encoder // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty; - var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) : - string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg); + var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {5} -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail, threads) : + string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); @@ -693,7 +695,7 @@ namespace MediaBrowser.MediaEncoding.Encoder Directory.CreateDirectory(targetDirectory); var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg"); - var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf); + var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); From 7bf647bb942fb5adfc1d96fc324d549af5f30651 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 09:38:50 -0700 Subject: [PATCH 0398/1930] Remove precondition checks --- Jellyfin.Api/Controllers/ItemsController.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 43282b6851..6d30a3d425 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -412,13 +412,9 @@ namespace Jellyfin.Api.Controllers query.IsVirtualItem = false; } - if (locationTypes.Length != 0) + if (locationTypes.Length > 0 && locationTypes.Length < 4) { - var requestedLocationTypes = locationTypes; - if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4) - { - query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual); - } + query.IsVirtualItem = locationTypes.Contains(LocationType.Virtual); } // Min official rating From 5b62f70bc03afe0d1bce702d71635fe57562dd0c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 09:57:08 -0700 Subject: [PATCH 0399/1930] Update exception handle comment --- .../Json/Converters/JsonCommaDelimitedArrayConverter.cs | 3 ++- .../Json/Converters/JsonPipeDelimitedArrayConverter.cs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index 06a29a0dbe..a259cb7bcb 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -43,7 +43,8 @@ namespace MediaBrowser.Common.Json.Converters } catch (FormatException) { - // TODO log when upgraded to .Net5 + // TODO log when upgraded to .Net6 + // https://github.com/dotnet/runtime/issues/42975 // _logger.LogWarning(e, "Error converting value."); } } diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs index 0eb6916a5a..75fbcea1f0 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -43,7 +43,8 @@ namespace MediaBrowser.Common.Json.Converters } catch (FormatException) { - // TODO log when upgraded to .Net5 + // TODO log when upgraded to .Net6 + // https://github.com/dotnet/runtime/issues/42975 // _logger.LogWarning(e, "Error converting value."); } } From 4b1c9dc9eaa120a30a7820257a83dd5aa3ecd9f4 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Tue, 17 Nov 2020 19:43:00 +0100 Subject: [PATCH 0400/1930] Pass cancellation where possible --- Emby.Dlna/PlayTo/SsdpHttpClient.cs | 4 ++-- Emby.Server.Implementations/ApplicationHost.cs | 2 +- .../Data/SqliteExtensions.cs | 14 -------------- .../LiveTv/EmbyTV/DirectRecorder.cs | 7 ++++--- .../LiveTv/Listings/SchedulesDirect.cs | 18 +++++++++--------- .../LiveTv/Listings/XmlTvListingsProvider.cs | 2 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 6 +++--- .../LiveTv/TunerHosts/M3uParser.cs | 2 +- .../LiveTv/TunerHosts/SharedHttpStream.cs | 2 +- .../Updates/InstallationManager.cs | 7 ++++--- .../Helpers/FileStreamResponseHelpers.cs | 6 ++++-- .../Subtitles/SubtitleEncoder.cs | 2 +- .../Manager/ItemImageProvider.cs | 4 ++-- .../Manager/ProviderManager.cs | 2 +- .../Plugins/AudioDb/AlbumProvider.cs | 2 +- .../Plugins/AudioDb/ArtistProvider.cs | 2 +- .../Plugins/MusicBrainz/ArtistProvider.cs | 6 +++--- .../MusicBrainz/MusicBrainzAlbumProvider.cs | 10 +++++----- .../Plugins/Omdb/OmdbItemProvider.cs | 2 +- .../Plugins/Omdb/OmdbProvider.cs | 4 ++-- 20 files changed, 47 insertions(+), 57 deletions(-) diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index c8c36fc972..f4d7937907 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -45,7 +45,7 @@ namespace Emby.Dlna.PlayTo header, cancellationToken) .ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var reader = new StreamReader(stream, Encoding.UTF8); return XDocument.Parse( await reader.ReadToEndAsync().ConfigureAwait(false), @@ -94,7 +94,7 @@ namespace Emby.Dlna.PlayTo options.Headers.UserAgent.ParseAdd(USERAGENT); options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var reader = new StreamReader(stream, Encoding.UTF8); return XDocument.Parse( await reader.ReadToEndAsync().ConfigureAwait(false), diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ad3c196189..17b99c858f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1378,7 +1378,7 @@ namespace Emby.Server.Implementations using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var result = await System.Text.Json.JsonSerializer.DeserializeAsync<string>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase); diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index 70a6df977f..1af301ceb0 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -107,20 +107,6 @@ namespace Emby.Server.Implementations.Data return null; } - public static void Attach(SQLiteDatabaseConnection db, string path, string alias) - { - var commandText = string.Format( - CultureInfo.InvariantCulture, - "attach @path as {0};", - alias); - - using (var statement = db.PrepareStatement(commandText)) - { - statement.TryBind("@path", path); - statement.MoveNext(); - } - } - public static bool IsDBNull(this IReadOnlyList<IResultSetValue> result, int index) { return result[index].SQLiteType == SQLiteType.Null; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 44560d1e21..341194f239 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -77,11 +77,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _logger.LogInformation("Copying recording stream to file {0}", targetFile); // The media source if infinite so we need to handle stopping ourselves - var durationToken = new CancellationTokenSource(duration); - cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + using var durationToken = new CancellationTokenSource(duration); + using var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token); + cancellationToken = linkedCancellationToken.Token; await _streamHelper.CopyUntilCancelled( - await response.Content.ReadAsStreamAsync().ConfigureAwait(false), + await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), output, IODefaults.CopyToBufferSize, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 43128c60d7..91f7c79315 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -112,7 +112,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings options.Content = new StringContent(requestString, Encoding.UTF8, MediaTypeNames.Application.Json); options.Headers.TryAddWithoutValidation("token", token); using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false); - await using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(responseStream).ConfigureAwait(false); _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings programRequestOptions.Content = new StringContent("[\"" + string.Join("\", \"", programsID) + "\"]", Encoding.UTF8, MediaTypeNames.Application.Json); using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false); - await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); @@ -480,9 +480,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false); - await using var response = await innerResponse2.Content.ReadAsStreamAsync().ConfigureAwait(false); - return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>( - response).ConfigureAwait(false); + await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(response).ConfigureAwait(false); } catch (Exception ex) { @@ -509,7 +508,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false); - await using var response = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(response).ConfigureAwait(false); @@ -542,6 +541,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>(); private DateTime _lastErrorResponse; + private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken) { var username = info.Username; @@ -651,7 +651,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).ConfigureAwait(false); if (root.message == "OK") { @@ -705,7 +705,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false); - await using var stream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var response = httpResponse.Content; var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(stream).ConfigureAwait(false); @@ -780,7 +780,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings var list = new List<ChannelInfo>(); using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false); - await using var stream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(stream).ConfigureAwait(false); _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); _logger.LogInformation("Mapping Stations to Channel"); diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 2d6f453bd4..76c8757370 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings Directory.CreateDirectory(Path.GetDirectoryName(cacheFile)); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(path, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await using (var fileStream = new FileStream(cacheFile, FileMode.CreateNew)) { await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 9fdbad63c2..c0a4d12285 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -72,7 +72,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var lineup = await JsonSerializer.DeserializeAsync<List<Channels>>(stream, cancellationToken: cancellationToken) .ConfigureAwait(false) ?? new List<Channels>(); @@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/discover.json", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, cancellationToken: cancellationToken) .ConfigureAwait(false); @@ -175,7 +175,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/tuners.html", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var sr = new StreamReader(stream, System.Text.Encoding.UTF8); var tuners = new List<LiveTvTunerInfo>(); while (!sr.EndOfStream) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 7c13d45e95..6ea1e1dd77 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts .SendAsync(requestMessage, cancellationToken) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); - return await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); } return File.OpenRead(info.Url); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 2e1b895096..2de447ad9a 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -135,7 +135,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts { Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using var message = response; - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read); await StreamHelper.CopyToAsync( stream, diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 6b6b8c4fe5..851e7bd68b 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.Updates { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(manifest, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); try { @@ -241,7 +241,8 @@ namespace Emby.Server.Implementations.Updates _currentInstallations.Add(tuple); } - var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token).Token; + using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, innerCancellationTokenSource.Token); + var linkedToken = linkedTokenSource.Token; await _eventManager.PublishAsync(new PluginInstallingEventArgs(package)).ConfigureAwait(false); @@ -333,7 +334,7 @@ namespace Emby.Server.Implementations.Updates using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(package.SourceUrl, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); // CA5351: Do Not Use Broken Cryptographic Algorithms #pragma warning disable CA5351 diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index 20c94cddad..cfa2c1229a 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -24,12 +24,14 @@ namespace Jellyfin.Api.Helpers /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param> /// <param name="httpClient">The <see cref="HttpClient"/> making the remote request.</param> /// <param name="httpContext">The current http context.</param> + /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param> /// <returns>A <see cref="Task{ActionResult}"/> containing the API response.</returns> public static async Task<ActionResult> GetStaticRemoteStreamResult( StreamState state, bool isHeadRequest, HttpClient httpClient, - HttpContext httpContext) + HttpContext httpContext, + CancellationToken cancellationToken = default) { if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent)) { @@ -47,7 +49,7 @@ namespace Jellyfin.Api.Helpers return new FileContentResult(Array.Empty<byte>(), contentType); } - return new FileStreamResult(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), contentType); + return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), contentType); } /// <summary> diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 8b3c6b2e63..b61b8a0e04 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -760,7 +760,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(new Uri(path), cancellationToken) .ConfigureAwait(false); - return await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); } case MediaProtocol.File: diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index 39748171af..ffc6889fa2 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -469,7 +469,7 @@ namespace MediaBrowser.Providers.Manager try { using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await _providerManager.SaveImage( item, @@ -586,7 +586,7 @@ namespace MediaBrowser.Providers.Manager } } - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await _providerManager.SaveImage( item, stream, diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 7a1b7bb2c7..58ca88a5be 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -181,7 +181,7 @@ namespace MediaBrowser.Providers.Manager throw new HttpRequestException("Invalid image received.", null, HttpStatusCode.NotFound); } - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await SaveImage( item, stream, diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index e6d89e6880..6536b303fe 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -175,7 +175,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb Directory.CreateDirectory(Path.GetDirectoryName(path)); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 72dad8a25a..85c92fa7b9 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -156,7 +156,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs index f27da7ce61..dc755b600b 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Providers.Music var url = "/ws/2/artist/?query=arid:{0}" + musicBrainzId.ToString(CultureInfo.InvariantCulture); using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); return GetResultsFromResponse(stream); } else @@ -49,7 +49,7 @@ namespace MediaBrowser.Providers.Music var url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch)); using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false)) - await using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) + await using (var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) { var results = GetResultsFromResponse(stream).ToList(); @@ -65,7 +65,7 @@ namespace MediaBrowser.Providers.Music url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch)); using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); return GetResultsFromResponse(stream); } } diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs index 31f0123dcf..93178d64a8 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs @@ -125,7 +125,7 @@ namespace MediaBrowser.Providers.Music if (!string.IsNullOrWhiteSpace(url)) { using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); return GetResultsFromResponse(stream); } @@ -284,7 +284,7 @@ namespace MediaBrowser.Providers.Music artistId); using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var oReader = new StreamReader(stream, Encoding.UTF8); var settings = new XmlReaderSettings { @@ -307,7 +307,7 @@ namespace MediaBrowser.Providers.Music WebUtility.UrlEncode(artistName)); using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var oReader = new StreamReader(stream, Encoding.UTF8); var settings = new XmlReaderSettings() { @@ -622,7 +622,7 @@ namespace MediaBrowser.Providers.Music var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture); using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var oReader = new StreamReader(stream, Encoding.UTF8); var settings = new XmlReaderSettings { @@ -649,7 +649,7 @@ namespace MediaBrowser.Providers.Music var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture); using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var oReader = new StreamReader(stream, Encoding.UTF8); var settings = new XmlReaderSettings { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 705359d2c7..43d8af75f0 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -133,7 +133,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var url = OmdbProvider.GetOmdbUrl(urlQuery); using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var resultList = new List<SearchResult>(); if (isSearch) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 9eed6172dd..6af52b591c 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -298,7 +298,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb imdbParam)); using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(stream).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); _jsonSerializer.SerializeToFile(rootObject, path); @@ -336,7 +336,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb seasonId)); using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<SeasonRootObject>(stream).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); _jsonSerializer.SerializeToFile(rootObject, path); From f6c6ee20085b16ca24079b102306b49f27d70751 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 13:44:51 -0700 Subject: [PATCH 0401/1930] Fix Environment authorization policy --- Jellyfin.Api/Controllers/EnvironmentController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/EnvironmentController.cs b/Jellyfin.Api/Controllers/EnvironmentController.cs index 6dd5362547..b0b4b5af51 100644 --- a/Jellyfin.Api/Controllers/EnvironmentController.cs +++ b/Jellyfin.Api/Controllers/EnvironmentController.cs @@ -17,7 +17,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Environment Controller. /// </summary> - [Authorize(Policy = Policies.RequiresElevation)] + [Authorize(Policy = Policies.FirstTimeSetupOrElevated)] public class EnvironmentController : BaseJellyfinApiController { private const char UncSeparator = '\\'; From b91afdb56fb9295c81f40665db5084958c630ed8 Mon Sep 17 00:00:00 2001 From: Moritz <moritz.leick@googlemail.com> Date: Tue, 17 Nov 2020 19:47:16 +0000 Subject: [PATCH 0402/1930] Translated using Weblate (German) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/de/ --- Emby.Server.Implementations/Localization/Core/de.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json index c81de8218f..6ab22b8a4b 100644 --- a/Emby.Server.Implementations/Localization/Core/de.json +++ b/Emby.Server.Implementations/Localization/Core/de.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Bibliothek", "TasksMaintenanceCategory": "Wartung", "TaskCleanActivityLogDescription": "Löscht Aktivitätsprotokolleinträge, die älter als das konfigurierte Alter sind.", - "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen" + "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen", + "Undefined": "Undefiniert", + "Forced": "Erzwungen", + "Default": "Standard" } From 316b18e8f20963ff15c1e5e76aef09870aa601b7 Mon Sep 17 00:00:00 2001 From: danielxb-ar <danielxb@gmail.com> Date: Tue, 17 Nov 2020 12:39:57 +0000 Subject: [PATCH 0403/1930] Translated using Weblate (Spanish (Argentina)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es_AR/ --- Emby.Server.Implementations/Localization/Core/es-AR.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es-AR.json b/Emby.Server.Implementations/Localization/Core/es-AR.json index 390074cdd7..0d4a14be00 100644 --- a/Emby.Server.Implementations/Localization/Core/es-AR.json +++ b/Emby.Server.Implementations/Localization/Core/es-AR.json @@ -113,5 +113,10 @@ "TasksChannelsCategory": "Canales de internet", "TasksApplicationCategory": "Aplicación", "TasksLibraryCategory": "Biblioteca", - "TasksMaintenanceCategory": "Mantenimiento" + "TasksMaintenanceCategory": "Mantenimiento", + "TaskCleanActivityLogDescription": "Borrar log de actividades anteriores a la fecha establecida.", + "TaskCleanActivityLog": "Borrar log de actividades", + "Undefined": "Indefinido", + "Forced": "Forzado", + "Default": "Por Defecto" } From a8524be6be3ff7c527d31cbe3c4e0edc7ffa9d56 Mon Sep 17 00:00:00 2001 From: HDmaniac <HDmaniac@protonmail.com> Date: Tue, 17 Nov 2020 21:14:05 +0000 Subject: [PATCH 0404/1930] Translated using Weblate (Spanish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es/ --- Emby.Server.Implementations/Localization/Core/es.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json index d6af40c409..fe674cf366 100644 --- a/Emby.Server.Implementations/Localization/Core/es.json +++ b/Emby.Server.Implementations/Localization/Core/es.json @@ -115,5 +115,8 @@ "TaskDownloadMissingSubtitles": "Descargar los subtítulos que faltan", "TaskDownloadMissingSubtitlesDescription": "Busca en internet los subtítulos que falten en el contenido de tus bibliotecas, basándose en la configuración de los metadatos.", "TaskCleanActivityLogDescription": "Elimina todos los registros de actividad anteriores a la fecha configurada.", - "TaskCleanActivityLog": "Limpiar registro de actividad" + "TaskCleanActivityLog": "Limpiar registro de actividad", + "Undefined": "Indefinido", + "Forced": "Forzado", + "Default": "Predeterminado" } From 1831b6cbab0781a0d8f4bafc9e018179db0e19a5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 17 Nov 2020 16:39:47 -0700 Subject: [PATCH 0405/1930] Remove tvdb migration. --- Jellyfin.Server/Migrations/MigrationRunner.cs | 3 +- .../Routines/DownloadTheTvdbPlugin.cs | 63 ------------------- 2 files changed, 1 insertion(+), 65 deletions(-) delete mode 100644 Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index ad80604c58..aca1654084 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -24,8 +24,7 @@ namespace Jellyfin.Server.Migrations typeof(Routines.MigrateUserDb), typeof(Routines.ReaddDefaultPluginRepository), typeof(Routines.MigrateDisplayPreferencesDb), - typeof(Routines.RemoveDownloadImagesInAdvance), - typeof(Routines.DownloadTheTvdbPlugin) + typeof(Routines.RemoveDownloadImagesInAdvance) }; /// <summary> diff --git a/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs b/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs deleted file mode 100644 index 0dfb27bc98..0000000000 --- a/Jellyfin.Server/Migrations/Routines/DownloadTheTvdbPlugin.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Linq; -using MediaBrowser.Common.Updates; -using Microsoft.Extensions.Logging; - -namespace Jellyfin.Server.Migrations.Routines -{ - /// <summary> - /// Download TheTvdb plugin after update. - /// </summary> - public class DownloadTheTvdbPlugin : IMigrationRoutine - { - private readonly Guid _tvdbPluginId = new Guid("a677c0da-fac5-4cde-941a-7134223f14c8"); - private readonly IInstallationManager _installationManager; - private readonly ILogger<DownloadTheTvdbPlugin> _logger; - - /// <summary> - /// Initializes a new instance of the <see cref="DownloadTheTvdbPlugin"/> class. - /// </summary> - /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param> - /// <param name="logger">Instance of the <see cref="ILogger{DownloadTvdbPlugin}"/> interface.</param> - public DownloadTheTvdbPlugin(IInstallationManager installationManager, ILogger<DownloadTheTvdbPlugin> logger) - { - _installationManager = installationManager; - _logger = logger; - } - - /// <inheritdoc /> - public Guid Id => new Guid("42E45BB4-5D78-4EE2-8C45-9095216D4769"); - - /// <inheritdoc /> - public string Name => "DownloadTheTvdbPlugin"; - - /// <inheritdoc /> - public bool PerformOnNewInstall => false; - - /// <inheritdoc /> - public void Perform() - { - try - { - var packages = _installationManager.GetAvailablePackages().GetAwaiter().GetResult(); - var package = _installationManager.GetCompatibleVersions( - packages, - guid: _tvdbPluginId) - .FirstOrDefault(); - - if (package == null) - { - _logger.LogWarning("TheTVDB Plugin not found, skipping migration."); - return; - } - - _installationManager.InstallPackage(package).GetAwaiter().GetResult(); - _logger.LogInformation("TheTVDB Plugin installed, please restart Jellyfin."); - } - catch (Exception e) - { - _logger.LogWarning(e, "Unable to install TheTVDB Plugin."); - } - } - } -} \ No newline at end of file From 38c3b6fcd37d71d09c6afe26ad26c762850f9971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Wed, 18 Nov 2020 10:01:03 +0100 Subject: [PATCH 0406/1930] Fix build and thread detection logic --- .../LiveTv/EmbyTV/EmbyTV.cs | 2 +- .../LiveTv/EmbyTV/EncodedRecorder.cs | 1 + Jellyfin.Api/Controllers/DynamicHlsController.cs | 2 +- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 13 ++++++++----- .../Encoder/MediaEncoder.cs | 16 ++++++++-------- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index fcc2d1eeb6..0dc045ee6f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1635,7 +1635,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http)) { - return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer); + return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _config); } return new DirectRecorder(_logger, _httpClientFactory, _streamHelper); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 4726211d27..e6ee9819eb 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -8,6 +8,7 @@ using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 6e59da798c..bba5e972e8 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1329,7 +1329,7 @@ namespace Jellyfin.Api.Controllers { var videoCodec = _encodingHelper.GetVideoEncoder(state, encodingOptions); - var threads = _encodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); + var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); // GetNumberOfThreads is static if (state.BaseRequest.BreakOnNonKeyFrames) { diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 389dc8a088..065fa786ee 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -359,7 +359,7 @@ namespace Jellyfin.Api.Controllers private string GetCommandLineArguments(string outputPath, StreamState state) { var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); - var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); + var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); // GetNumberOfThreads is static var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 3a9f57c55b..60c44cfcfc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2329,20 +2329,23 @@ namespace MediaBrowser.Controller.MediaEncoding /// <summary> /// Gets the number of threads. /// </summary> - public int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec) + public static int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec) { - if (string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)) + if (outputVideoCodec != null && string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)) { // per docs: // -threads number of threads to use for encoding, can't be 0 [auto] with VP8 // (recommended value : number of real cores - 1) return Math.Max(Environment.ProcessorCount - 1, 1); } - - var threads = state.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount; + var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount; // Automatic - if (threads <= 0 || threads >= Environment.ProcessorCount) + if (threads <= 0) + { + return 0; + } + else if (threads >= Environment.ProcessorCount) { return Environment.ProcessorCount; } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 2b4712b2dc..5f60c09ae7 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -524,26 +524,26 @@ namespace MediaBrowser.MediaEncoding.Encoder // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar - var vf = String.Empty; + var vf = string.Empty; if (threedFormat.HasValue) { switch (threedFormat.Value) { case Video3DFormat.HalfSideBySide: - vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + vf = "-vf crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. break; case Video3DFormat.FullSideBySide: - vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + vf = "-vf crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; // fsbs crop width in half,set the display aspect,crop out any black bars we may have made break; case Video3DFormat.HalfTopAndBottom: - vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + vf = "-vf crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made break; case Video3DFormat.FullTopAndBottom: - vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; + vf = "-vf crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made break; default: @@ -557,8 +557,8 @@ namespace MediaBrowser.MediaEncoding.Encoder // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty; - var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {5} -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail, threads) : - string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); + var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {5} -v quiet -vframes 1 {2}{4} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail, threads) : + string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); @@ -695,7 +695,7 @@ namespace MediaBrowser.MediaEncoding.Encoder Directory.CreateDirectory(targetDirectory); var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg"); - var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf, threads); + var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet {2} -f image2 \"{1}\"", inputArgument, outputPath, vf, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); From 9c20701cf62a7a39235b0b4d4471297770432670 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Wed, 18 Nov 2020 13:28:35 +0100 Subject: [PATCH 0407/1930] Correct typos --- Emby.Server.Implementations/SyncPlay/GroupController.cs | 3 +-- Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 4efc671ffa..31df8404b4 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -57,9 +57,8 @@ namespace Emby.Server.Implementations.SyncPlay new Dictionary<string, GroupMember>(StringComparer.OrdinalIgnoreCase); /// <summary> - /// Internal group state. + /// The internal group state. /// </summary> - /// <value>The group's state.</value> private IGroupState _state; /// <summary> diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 4df8e3ba77..73bcced8ad 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -54,12 +54,12 @@ namespace Emby.Server.Implementations.SyncPlay new Dictionary<Guid, IGroupController>(); /// <summary> - /// Lock used for accesing the list of groups. + /// Lock used for accessing the list of groups. /// </summary> private readonly object _groupsLock = new object(); /// <summary> - /// Lock used for accesing the session-to-group map. + /// Lock used for accessing the session-to-group map. /// </summary> private readonly object _mapsLock = new object(); From e51ddd326c51be8c2bba4b1ac65131cbe65b9f3a Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 18 Nov 2020 13:23:45 +0000 Subject: [PATCH 0408/1930] Fixes spelling. --- Emby.Dlna/Common/Argument.cs | 2 +- Emby.Dlna/ContentDirectory/ControlHandler.cs | 2 +- Emby.Dlna/DlnaManager.cs | 4 +- Emby.Dlna/PlayTo/Device.cs | 4 +- Emby.Naming/Subtitles/SubtitleParser.cs | 2 +- Emby.Naming/Video/VideoListResolver.cs | 2 +- .../Library/MediaStreamSelector.cs | 2 +- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- .../LiveTv/TunerHosts/M3uParser.cs | 2 +- .../ScheduledTasks/TaskManager.cs | 4 +- .../SyncPlay/SyncPlayManager.cs | 2 +- Jellyfin.Api/Controllers/AudioController.cs | 6 +-- .../Controllers/DynamicHlsController.cs | 22 ++++---- Jellyfin.Api/Controllers/ItemsController.cs | 50 +++++++++---------- Jellyfin.Api/Controllers/LiveTvController.cs | 4 +- .../Controllers/TrailersController.cs | 42 ++++++++-------- Jellyfin.Api/Controllers/TvShowsController.cs | 6 +-- .../Controllers/UserLibraryController.cs | 4 +- .../Controllers/VideoHlsController.cs | 4 +- Jellyfin.Api/Controllers/VideosController.cs | 4 +- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 4 +- 21 files changed, 87 insertions(+), 87 deletions(-) diff --git a/Emby.Dlna/Common/Argument.cs b/Emby.Dlna/Common/Argument.cs index 430a3b47d5..e4e9c55e0d 100644 --- a/Emby.Dlna/Common/Argument.cs +++ b/Emby.Dlna/Common/Argument.cs @@ -1,7 +1,7 @@ namespace Emby.Dlna.Common { /// <summary> - /// DLNA Query parameter type, used when quering DLNA devices via SOAP. + /// DLNA Query parameter type, used when querying DLNA devices via SOAP. /// </summary> public class Argument { diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 9f35c19594..b93651746b 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1674,7 +1674,7 @@ namespace Emby.Dlna.ContentDirectory } /// <summary> - /// Retreives the ServerItem id. + /// Retrieves the ServerItem id. /// </summary> /// <param name="id">The id<see cref="string"/>.</param> /// <returns>The <see cref="ServerItem"/>.</returns> diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 069400833e..fedd20b68a 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -484,10 +484,10 @@ namespace Emby.Dlna /// <summary> /// Recreates the object using serialization, to ensure it's not a subclass. - /// If it's a subclass it may not serlialize properly to xml (different root element tag name). + /// If it's a subclass it may not serialize properly to xml (different root element tag name). /// </summary> /// <param name="profile">The device profile.</param> - /// <returns>The reserialized device profile.</returns> + /// <returns>The re-serialized device profile.</returns> private DeviceProfile ReserializeProfile(DeviceProfile profile) { if (profile.GetType() == typeof(DeviceProfile)) diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index c97acdb026..58a7ea1374 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -480,7 +480,7 @@ namespace Emby.Dlna.PlayTo return; } - // If we're not playing anything make sure we don't get data more often than neccessry to keep the Session alive + // If we're not playing anything make sure we don't get data more often than necessary to keep the Session alive if (transportState.Value == TransportState.Stopped) { RestartTimerInactive(); @@ -821,7 +821,7 @@ namespace Emby.Dlna.PlayTo { } - // first try to add a root node with a dlna namesapce + // first try to add a root node with a dlna namesake try { return XElement.Parse("<data xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">" + xml + "</data>") diff --git a/Emby.Naming/Subtitles/SubtitleParser.cs b/Emby.Naming/Subtitles/SubtitleParser.cs index e872452519..a19340ef69 100644 --- a/Emby.Naming/Subtitles/SubtitleParser.cs +++ b/Emby.Naming/Subtitles/SubtitleParser.cs @@ -60,7 +60,7 @@ namespace Emby.Naming.Subtitles private string[] GetFlags(string path) { - // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _. + // Note: the tags need be surrounded be either a space ( ), hyphen -, dot . or underscore _. var file = Path.GetFileName(path); diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 19cc491cfb..5f83355c8f 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -30,7 +30,7 @@ namespace Emby.Naming.Video /// </summary> /// <param name="files">List of related video files.</param> /// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param> - /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files togeather when related.</returns> + /// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns> public IEnumerable<VideoInfo> Resolve(List<FileSystemMetadata> files, bool supportMultiVersion = true) { var videoResolver = new VideoResolver(_options); diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs index 179e0ed986..28fa062396 100644 --- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs +++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs @@ -101,7 +101,7 @@ namespace Emby.Server.Implementations.Library private static IEnumerable<MediaStream> GetSortedStreams(IEnumerable<MediaStream> streams, MediaStreamType type, string[] languagePreferences) { - // Give some preferance to external text subs for better performance + // Give some preference to external text subs for better performance return streams.Where(i => i.Type == type) .OrderBy(i => { diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 91f7c79315..5d17ba1de9 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -261,7 +261,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings Id = newID, StartDate = startAt, EndDate = endAt, - Name = details.titles[0].title120 ?? "Unkown", + Name = details.titles[0].title120 ?? "Unknown", OfficialRating = null, CommunityRating = null, EpisodeTitle = episodeTitle, diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 6ea1e1dd77..1d6c26c130 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -197,7 +197,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (string.IsNullOrWhiteSpace(numberString)) { // Using this as a fallback now as this leads to Problems with channels like "5 USA" - // where 5 isnt ment to be the channel number + // where 5 isn't ment to be the channel number // Check for channel number with the format from SatIp // #EXTINF:0,84. VOX Schweiz // #EXTINF:0,84.0 - VOX Schweiz diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index 6f81bf49bb..cfbf03ddc0 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var type = scheduledTask.ScheduledTask.GetType(); - _logger.LogInformation("Queueing task {0}", type.Name); + _logger.LogInformation("Queuing task {0}", type.Name); lock (_taskQueue) { @@ -176,7 +176,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var type = task.ScheduledTask.GetType(); - _logger.LogInformation("Queueing task {0}", type.Name); + _logger.LogInformation("Queuing task {0}", type.Name); lock (_taskQueue) { diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 966ed5024e..7c4e003112 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.SyncPlay new Dictionary<Guid, ISyncPlayController>(); /// <summary> - /// Lock used for accesing any group. + /// Lock used for accessing any group. /// </summary> private readonly object _groupsLock = new object(); diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs index d4c6e4af94..ae8c05d858 100644 --- a/Jellyfin.Api/Controllers/AudioController.cs +++ b/Jellyfin.Api/Controllers/AudioController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; @@ -42,7 +42,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -71,7 +71,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 6e59da798c..7c5c56660b 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -120,7 +120,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -149,7 +149,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> @@ -285,7 +285,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -315,7 +315,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> @@ -452,7 +452,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -481,7 +481,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> @@ -615,7 +615,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -645,7 +645,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> @@ -812,7 +812,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> @@ -953,7 +953,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -983,7 +983,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index d8d371ebc3..15d7bd0b8c 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; @@ -73,8 +73,8 @@ namespace Jellyfin.Api.Controllers /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param> /// <param name="isHd">Optional filter by items that are HD or not.</param> /// <param name="is4K">Optional filter by items that are 4K or not.</param> - /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.</param> - /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimeted.</param> + /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param> + /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param> /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param> /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param> /// <param name="minCommunityRating">Optional filter by minimum community rating.</param> @@ -87,42 +87,42 @@ namespace Jellyfin.Api.Controllers /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param> /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param> /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param> - /// <param name="excludeItemIds">Optional. If specified, results will be filtered by exxcluding item ids. This allows multiple, comma delimeted.</param> + /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param> /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> /// <param name="limit">Optional. The maximum number of records to return.</param> /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param> /// <param name="searchTerm">Optional. Filter based on a search term.</param> /// <param name="sortOrder">Sort Order - Ascending,Descending.</param> /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> - /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param> - /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param> - /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> + /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param> + /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param> + /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param> /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param> /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param> - /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> + /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> /// <param name="isPlayed">Optional filter by items that are played, or not.</param> - /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimeted.</param> - /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.</param> - /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.</param> - /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.</param> + /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param> + /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param> + /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param> + /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param> /// <param name="enableUserData">Optional, include user data.</param> /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param> /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param> /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param> - /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.</param> - /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimeted.</param> - /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimeted.</param> + /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param> + /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param> + /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param> /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param> /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param> /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param> - /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimeted.</param> - /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimeted.</param> + /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param> + /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param> /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param> - /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.</param> + /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param> /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param> /// <param name="isLocked">Optional filter by items that are locked.</param> /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param> @@ -133,12 +133,12 @@ namespace Jellyfin.Api.Controllers /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param> /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param> /// <param name="is3D">Optional filter by items that are 3D, or not.</param> - /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimeted.</param> + /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param> /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param> /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param> /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param> - /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimeted.</param> - /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimeted.</param> + /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param> + /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param> /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param> /// <param name="enableImages">Optional, include image information in output.</param> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns> @@ -513,13 +513,13 @@ namespace Jellyfin.Api.Controllers /// <param name="limit">The item limit.</param> /// <param name="searchTerm">The search term.</param> /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param> /// <param name="enableUserData">Optional. Include user data.</param> /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param> /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> - /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param> - /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimeted.</param> + /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param> + /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param> /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param> /// <param name="enableImages">Optional. Include image information in output.</param> /// <response code="200">Items returned.</response> diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 29c0f1df4d..f81f9088a2 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; @@ -1155,7 +1155,7 @@ namespace Jellyfin.Api.Controllers /// <param name="newDevicesOnly">Only discover new tuners.</param> /// <response code="200">Tuners returned.</response> /// <returns>An <see cref="OkResult"/> containing the tuners.</returns> - [HttpGet("Tuners/Discvover")] + [HttpGet("Tuners/Discover")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<TunerHostInfo>>> DiscoverTuners([FromQuery] bool newDevicesOnly = false) diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index d78adcbcdc..12a14a72c9 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Jellyfin.Api.Constants; using Jellyfin.Api.ModelBinders; using MediaBrowser.Model.Dto; @@ -42,8 +42,8 @@ namespace Jellyfin.Api.Controllers /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param> /// <param name="isHd">Optional filter by items that are HD or not.</param> /// <param name="is4K">Optional filter by items that are 4K or not.</param> - /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimeted.</param> - /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimeted.</param> + /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param> + /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param> /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param> /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param> /// <param name="minCommunityRating">Optional filter by minimum community rating.</param> @@ -56,41 +56,41 @@ namespace Jellyfin.Api.Controllers /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param> /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param> /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param> - /// <param name="excludeItemIds">Optional. If specified, results will be filtered by exxcluding item ids. This allows multiple, comma delimeted.</param> + /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param> /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param> /// <param name="limit">Optional. The maximum number of records to return.</param> /// <param name="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param> /// <param name="searchTerm">Optional. Filter based on a search term.</param> /// <param name="sortOrder">Sort Order - Ascending,Descending.</param> /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> - /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param> - /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimeted. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param> + /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param> + /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param> /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param> /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param> /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param> - /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> + /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> /// <param name="isPlayed">Optional filter by items that are played, or not.</param> - /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimeted.</param> - /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimeted.</param> - /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimeted.</param> - /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimeted.</param> + /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param> + /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param> + /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param> + /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param> /// <param name="enableUserData">Optional, include user data.</param> /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param> /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param> /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param> - /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimeted.</param> - /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimeted.</param> - /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimeted.</param> + /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param> + /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param> + /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param> /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param> /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param> /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param> - /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimeted.</param> - /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimeted.</param> + /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param> + /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param> /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param> - /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimeted.</param> + /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param> /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param> /// <param name="isLocked">Optional filter by items that are locked.</param> /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param> @@ -101,12 +101,12 @@ namespace Jellyfin.Api.Controllers /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param> /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param> /// <param name="is3D">Optional filter by items that are 3D, or not.</param> - /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimeted.</param> + /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param> /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param> /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param> /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param> - /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimeted.</param> - /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimeted.</param> + /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param> + /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param> /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param> /// <param name="enableImages">Optional, include image information in output.</param> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the trailers.</returns> diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 6fd154836b..57b056f50b 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -176,7 +176,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="seriesId">The series id.</param> /// <param name="userId">The user id.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> /// <param name="season">Optional filter by season number.</param> /// <param name="seasonId">Optional. Filter by season id.</param> /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param> @@ -188,7 +188,7 @@ namespace Jellyfin.Api.Controllers /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param> /// <param name="enableImageTypes">Optional. The image types to include in the output.</param> /// <param name="enableUserData">Optional. Include user data.</param> - /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimeted. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> + /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param> /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the episodes on success or a <see cref="NotFoundResult"/> if the series was not found.</returns> [HttpGet("{seriesId}/Episodes")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -303,7 +303,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="seriesId">The series id.</param> /// <param name="userId">The user id.</param> - /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> + /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines, TrailerUrls.</param> /// <param name="isSpecialSeason">Optional. Filter by special season.</param> /// <param name="isMissing">Optional. Filter by items that are missing episodes or not.</param> /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param> diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index cfd8511297..2a6547bbb1 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; @@ -253,7 +253,7 @@ namespace Jellyfin.Api.Controllers /// <param name="userId">User id.</param> /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param> /// <param name="fields">Optional. Specify additional fields of information to return in the output.</param> - /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.</param> + /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param> /// <param name="isPlayed">Filter by items that are played, or not.</param> /// <param name="enableImages">Optional. include image information in output.</param> /// <param name="imageTypeLimit">Optional. the max number of images to return, per image type.</param> diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 389dc8a088..d0f26b1beb 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; @@ -145,7 +145,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 4de7aac71d..07b114bb77 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -283,7 +283,7 @@ namespace Jellyfin.Api.Controllers /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param> /// <param name="playSessionId">The play session id.</param> /// <param name="segmentContainer">The segment container.</param> - /// <param name="segmentLength">The segment lenght.</param> + /// <param name="segmentLength">The segment length.</param> /// <param name="minSegments">The minimum number of segments.</param> /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param> /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param> @@ -312,7 +312,7 @@ namespace Jellyfin.Api.Controllers /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param> /// <param name="requireAvc">Optional. Whether to require avc.</param> /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param> - /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamporphic stream.</param> + /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param> /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param> /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param> /// <param name="liveStreamId">The live stream id.</param> diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 168dc27a83..26a03105d7 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -582,7 +582,7 @@ namespace Jellyfin.Api.Helpers // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback _ = new JobLogger(_logger).StartStreamingLog(state, process.StandardError.BaseStream, logStream); - // Wait for the file to exist before proceeeding + // Wait for the file to exist before proceeding var ffmpegTargetFile = state.WaitForPath ?? outputPath; _logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile); while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited) From 9a323f6df08927b5db06ba634f430523a236265f Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 18 Nov 2020 13:46:14 +0000 Subject: [PATCH 0409/1930] More spelling corrections. --- Jellyfin.Data/Entities/Libraries/CollectionItem.cs | 4 ++-- Jellyfin.Data/Entities/Libraries/ItemMetadata.cs | 2 +- .../Users/DefaultAuthenticationProvider.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 4 ++-- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- MediaBrowser.Controller/Entities/Folder.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 6 +++--- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- MediaBrowser.Model/Dlna/ResolutionNormalizer.cs | 2 +- MediaBrowser.Providers/Manager/ProviderUtils.cs | 4 ++-- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 10 +++++----- MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs | 2 +- MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs | 10 +++++----- RSSDP/DisposableManagedObjectBase.cs | 6 +++--- RSSDP/HttpParserBase.cs | 2 +- RSSDP/ISsdpDeviceLocator.cs | 4 ++-- RSSDP/SsdpDevicePublisher.cs | 4 ++-- RSSDP/SsdpRootDevice.cs | 4 ++-- 18 files changed, 36 insertions(+), 36 deletions(-) diff --git a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs index 4467c9bbdc..f9539964d0 100644 --- a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs @@ -73,7 +73,7 @@ namespace Jellyfin.Data.Entities.Libraries /// Gets or sets the next item in the collection. /// </summary> /// <remarks> - /// TODO check if this properly updated dependant and has the proper principal relationship. + /// TODO check if this properly updated Dependant and has the proper principal relationship. /// </remarks> public virtual CollectionItem Next { get; set; } @@ -81,7 +81,7 @@ namespace Jellyfin.Data.Entities.Libraries /// Gets or sets the previous item in the collection. /// </summary> /// <remarks> - /// TODO check if this properly updated dependant and has the proper principal relationship. + /// TODO check if this properly updated Dependant and has the proper principal relationship. /// </remarks> public virtual CollectionItem Previous { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs index 1d2dc0f669..d74330c051 100644 --- a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs @@ -141,7 +141,7 @@ namespace Jellyfin.Data.Entities.Libraries public virtual ICollection<PersonRole> PersonRoles { get; protected set; } /// <summary> - /// Gets or sets a collection containing the generes for this item. + /// Gets or sets a collection containing the genres for this item. /// </summary> public virtual ICollection<Genre> Genres { get; protected set; } diff --git a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs index f79e433a67..662b4bf651 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs @@ -53,7 +53,7 @@ namespace Jellyfin.Server.Implementations.Users bool success = false; - // As long as jellyfin supports passwordless users, we need this little block here to accommodate + // As long as jellyfin supports password-less users, we need this little block here to accommodate if (!HasPassword(resolvedUser) && string.IsNullOrEmpty(password)) { return Task.FromResult(new ProviderAuthenticationResult diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index a0330afeff..12966a474f 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -58,7 +58,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses. /// </summary> - /// <returns>The list of ipaddresses.</returns> + /// <returns>The list of ip addresses.</returns> IPAddress[] GetLocalIpAddresses(); /// <summary> @@ -73,7 +73,7 @@ namespace MediaBrowser.Common.Net /// Returns true if address is in the LAN list in the config file. /// </summary> /// <param name="address">The address to check.</param> - /// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param> + /// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] around and return true if it matches the address give in address.</param> /// <param name="excludeRFC">If true, returns false if address is in the 127.x.x.x or 169.128.x.x range.</param> /// <returns><c>false</c>if the address isn't in the LAN list, <c>true</c> if the address has been defined as a LAN address.</returns> bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 1d44a55114..8d77730041 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -2611,7 +2611,7 @@ namespace MediaBrowser.Controller.Entities { if (!AllowsMultipleImages(type)) { - throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots"); + throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots"); } var info1 = GetImageInfo(type, index1); diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index a76c8a376b..1e3825c6e3 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -212,7 +212,7 @@ namespace MediaBrowser.Controller.Entities /// <summary> /// Loads our children. Validation will occur externally. - /// We want this sychronous. + /// We want this synchronous. /// </summary> protected virtual List<BaseItem> LoadChildren() { diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 5846a603a2..a4a5cecdc5 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -63,7 +63,7 @@ namespace MediaBrowser.Controller.MediaEncoding { // Only use alternative encoders for video files. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully - // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this. + // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this. if (state.VideoType == VideoType.VideoFile) { var hwType = encodingOptions.HardwareAccelerationType; @@ -247,7 +247,7 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } - // Seeing reported failures here, not sure yet if this is related to specfying input format + // Seeing reported failures here, not sure yet if this is related to specifying input format if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase)) { return null; @@ -2752,7 +2752,7 @@ namespace MediaBrowser.Controller.MediaEncoding var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile; // Only use alternative encoders for video files. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully - // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this. + // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this. if (videoType != VideoType.VideoFile) { return null; diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 5a3a9185d7..e060253ee7 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -542,7 +542,7 @@ namespace MediaBrowser.MediaEncoding.Encoder break; case Video3DFormat.FullTopAndBottom: vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600 + // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to 600 break; default: break; diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index a4305c8104..2f8614386a 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -29,7 +29,7 @@ namespace MediaBrowser.Model.Dlna int? maxWidth, int? maxHeight) { - // If the bitrate isn't changing, then don't downlscale the resolution + // If the bitrate isn't changing, then don't downscale the resolution if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value) { if (maxWidth.HasValue || maxHeight.HasValue) diff --git a/MediaBrowser.Providers/Manager/ProviderUtils.cs b/MediaBrowser.Providers/Manager/ProviderUtils.cs index 70a5a6ac13..5621d2b86c 100644 --- a/MediaBrowser.Providers/Manager/ProviderUtils.cs +++ b/MediaBrowser.Providers/Manager/ProviderUtils.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Providers.Manager { if (replaceData || string.IsNullOrEmpty(target.Name)) { - // Safeguard against incoming data having an emtpy name + // Safeguard against incoming data having an empty name if (!string.IsNullOrWhiteSpace(source.Name)) { target.Name = source.Name; @@ -48,7 +48,7 @@ namespace MediaBrowser.Providers.Manager if (replaceData || string.IsNullOrEmpty(target.OriginalTitle)) { - // Safeguard against incoming data having an emtpy name + // Safeguard against incoming data having an empty name if (!string.IsNullOrWhiteSpace(source.OriginalTitle)) { target.OriginalTitle = source.OriginalTitle; diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 6af52b591c..332479ff8a 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var result = await GetRootObject(imdbId, cancellationToken).ConfigureAwait(false); - // Only take the name and rating if the user's language is set to english, since Omdb has no localization + // Only take the name and rating if the user's language is set to English, since Omdb has no localization if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport) { item.Name = result.Title; @@ -151,7 +151,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb return false; } - // Only take the name and rating if the user's language is set to english, since Omdb has no localization + // Only take the name and rating if the user's language is set to English, since Omdb has no localization if (string.Equals(language, "en", StringComparison.OrdinalIgnoreCase) || _configurationManager.Configuration.EnableNewOmdbSupport) { item.Name = result.Title; @@ -385,7 +385,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport; // Grab series genres because IMDb data is better than TVDB. Leave movies alone - // But only do it if english is the preferred language because this data will not be localized + // But only do it if English is the preferred language because this data will not be localized if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre)) { item.Genres = Array.Empty<string>(); @@ -401,7 +401,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb if (isConfiguredForEnglish) { - // Omdb is currently english only, so for other languages skip this and let secondary providers fill it in + // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in item.Overview = result.Plot; } @@ -455,7 +455,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { var lang = item.GetPreferredMetadataLanguage(); - // The data isn't localized and so can only be used for english users + // The data isn't localized and so can only be used for English users return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase); } diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index b754a07953..0e8a5baab6 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -98,7 +98,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb if (preferredLanguage.Length == 5) // like en-US { - // Currenty, TMDB supports 2-letter language codes only + // Currently, TMDB supports 2-letter language codes only // They are planning to change this in the future, thus we're // supplying both codes if we're having a 5-letter code. languages.Add(preferredLanguage.Substring(0, 2)); diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index 9cc0344c1c..bce4cf0093 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -134,7 +134,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - // int.TryParse is local aware, so it can be probamatic, force us culture + // int.TryParse is local aware, so it can be problematic, force us culture if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval)) { item.AirsBeforeEpisodeNumber = rval; @@ -150,7 +150,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - // int.TryParse is local aware, so it can be probamatic, force us culture + // int.TryParse is local aware, so it can be problematic, force us culture if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval)) { item.AirsAfterSeasonNumber = rval; @@ -166,7 +166,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - // int.TryParse is local aware, so it can be probamatic, force us culture + // int.TryParse is local aware, so it can be problematic, force us culture if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval)) { item.AirsBeforeSeasonNumber = rval; @@ -182,7 +182,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - // int.TryParse is local aware, so it can be probamatic, force us culture + // int.TryParse is local aware, so it can be problematic, force us culture if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval)) { item.AirsBeforeSeasonNumber = rval; @@ -198,7 +198,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - // int.TryParse is local aware, so it can be probamatic, force us culture + // int.TryParse is local aware, so it can be problematic, force us culture if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var rval)) { item.AirsBeforeEpisodeNumber = rval; diff --git a/RSSDP/DisposableManagedObjectBase.cs b/RSSDP/DisposableManagedObjectBase.cs index 745ec359c9..7d6a471f95 100644 --- a/RSSDP/DisposableManagedObjectBase.cs +++ b/RSSDP/DisposableManagedObjectBase.cs @@ -5,7 +5,7 @@ using System.Text; namespace Rssdp.Infrastructure { /// <summary> - /// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property. + /// Correctly implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceties not on the interface such as an <see cref="IsDisposed"/> property. /// </summary> public abstract class DisposableManagedObjectBase : IDisposable { @@ -61,10 +61,10 @@ namespace Rssdp.Infrastructure /// Disposes this object instance and all internally managed resources. /// </summary> /// <remarks> - /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para> + /// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behavior of derived classes.</para> /// </remarks> /// <seealso cref="IsDisposed"/> - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "We do exactly as asked, but CA doesn't seem to like us also setting the IsDisposed property. Too bad, it's a good idea and shouldn't cause an exception or anything likely to interfer with the dispose process.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "We do exactly as asked, but CA doesn't seem to like us also setting the IsDisposed property. Too bad, it's a good idea and shouldn't cause an exception or anything likely to interfere with the dispose process.")] public void Dispose() { IsDisposed = true; diff --git a/RSSDP/HttpParserBase.cs b/RSSDP/HttpParserBase.cs index 11202940e1..c56249523d 100644 --- a/RSSDP/HttpParserBase.cs +++ b/RSSDP/HttpParserBase.cs @@ -105,7 +105,7 @@ namespace Rssdp.Infrastructure var headerName = line.Substring(0, headerKeySeparatorIndex).Trim(); var headerValue = line.Substring(headerKeySeparatorIndex + 1).Trim(); - // Not sure how to determine where request headers and and content headers begin, + // Not sure how to determine where request headers and content headers begin, // at least not without a known set of headers (general headers first the content headers) // which seems like a bad way of doing it. So we'll assume if it's a known content header put it there // else use request headers. diff --git a/RSSDP/ISsdpDeviceLocator.cs b/RSSDP/ISsdpDeviceLocator.cs index 4130556434..4df166cd26 100644 --- a/RSSDP/ISsdpDeviceLocator.cs +++ b/RSSDP/ISsdpDeviceLocator.cs @@ -52,7 +52,7 @@ namespace Rssdp.Infrastructure } /// <summary> - /// Aynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results. + /// Asynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results. /// </summary> /// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(); @@ -83,7 +83,7 @@ namespace Rssdp.Infrastructure /// </param> /// <param name="searchWaitTime">The amount of time to wait for network responses to the search request. Longer values will likely return more devices, but increase search time. A value between 1 and 5 is recommended by the UPnP 1.1 specification. Specify TimeSpan.Zero to return only devices already in the cache.</param> /// <remarks> - /// <para>By design RSSDP does not support 'publishing services' as it is intended for use with non-standard UPnP devices that don't publish UPnP style services. However, it is still possible to use RSSDP to search for devices implemetning these services if you know the service type.</para> + /// <para>By design RSSDP does not support 'publishing services' as it is intended for use with non-standard UPnP devices that don't publish UPnP style services. However, it is still possible to use RSSDP to search for devices implementing these services if you know the service type.</para> /// </remarks> /// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns> System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(string searchTarget, TimeSpan searchWaitTime); diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 1a8577d8da..90925b9e0a 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -102,7 +102,7 @@ namespace Rssdp.Infrastructure /// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception> /// <exception cref="InvalidOperationException">Thrown if the <paramref name="device"/> contains property values that are not acceptable to the UPnP 1.0 specification.</exception> - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable suppresses compiler warning, but task is not really needed.")] public void AddDevice(SsdpRootDevice device) { if (device == null) @@ -180,7 +180,7 @@ namespace Rssdp.Infrastructure /// </summary> /// <remarks> /// <para>Enabling this option will cause devices to show up in Microsoft Windows Explorer's network screens (if discovery is enabled etc.). Windows Explorer appears to search only for pnp:rootdeivce and not upnp:rootdevice.</para> - /// <para>If false, the system will only use upnp:rootdevice for notifiation broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para> + /// <para>If false, the system will only use upnp:rootdevice for notification broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para> /// </remarks> public bool SupportPnpRootDevice { diff --git a/RSSDP/SsdpRootDevice.cs b/RSSDP/SsdpRootDevice.cs index 8937ec331f..4084b31ca6 100644 --- a/RSSDP/SsdpRootDevice.cs +++ b/RSSDP/SsdpRootDevice.cs @@ -25,7 +25,7 @@ namespace Rssdp /// Specifies how long clients can cache this device's details for. Optional but defaults to <see cref="TimeSpan.Zero"/> which means no-caching. Recommended value is half an hour. /// </summary> /// <remarks> - /// <para>Specifiy <see cref="TimeSpan.Zero"/> to indicate no caching allowed.</para> + /// <para>Specify <see cref="TimeSpan.Zero"/> to indicate no caching allowed.</para> /// <para>Also used to specify how often to rebroadcast alive notifications.</para> /// <para>The UPnP/SSDP specifications indicate this should not be less than 1800 seconds (half an hour), but this is not enforced by this library.</para> /// </remarks> @@ -50,7 +50,7 @@ namespace Rssdp public IPAddress SubnetMask { get; set; } /// <summary> - /// The base URL to use for all relative url's provided in other propertise (and those of child devices). Optional. + /// The base URL to use for all relative url's provided in other properties (and those of child devices). Optional. /// </summary> /// <remarks> /// <para>Defines the base URL. Used to construct fully-qualified URLs. All relative URLs that appear elsewhere in the description are combined with this base URL. If URLBase is empty or not given, the base URL is the URL from which the device description was retrieved (which is the preferred implementation; use of URLBase is no longer recommended). Specified by UPnP vendor. Single URL.</para> From 7a26f64c7badb05bc4e35cb678df6b7ffb9bc540 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 18 Nov 2020 13:48:31 +0000 Subject: [PATCH 0410/1930] Update Device.cs --- Emby.Dlna/PlayTo/Device.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 58a7ea1374..f8ff03076a 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -775,7 +775,7 @@ namespace Emby.Dlna.PlayTo if (track == null) { - // If track is null, some vendors do this, use GetMediaInfo instead + // If track is null, some vendors do this, use GetMediaInfo instead. return (true, null); } @@ -812,7 +812,7 @@ namespace Emby.Dlna.PlayTo private XElement ParseResponse(string xml) { - // Handle different variations sent back by devices + // Handle different variations sent back by devices. try { return XElement.Parse(xml); @@ -821,7 +821,7 @@ namespace Emby.Dlna.PlayTo { } - // first try to add a root node with a dlna namesake + // first try to add a root node with a dlna namespace. try { return XElement.Parse("<data xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">" + xml + "</data>") From 4c394eec90922b58ae5feecb4ed2713c24945f43 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 18 Nov 2020 14:08:44 +0000 Subject: [PATCH 0411/1930] Update Jellyfin.Api/Controllers/LiveTvController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/LiveTvController.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index f81f9088a2..41eb4f0303 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1155,6 +1155,7 @@ namespace Jellyfin.Api.Controllers /// <param name="newDevicesOnly">Only discover new tuners.</param> /// <response code="200">Tuners returned.</response> /// <returns>An <see cref="OkResult"/> containing the tuners.</returns> + [HttpGet("Tuners/Discvover", Name = "DiscvoverTuners")] [HttpGet("Tuners/Discover")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] From fbcf3b750dd4a9d07e80a5455a315518ceb9aa3b Mon Sep 17 00:00:00 2001 From: Nyanmisaka <799610810@qq.com> Date: Wed, 18 Nov 2020 13:28:26 +0000 Subject: [PATCH 0412/1930] Translated using Weblate (Chinese (Simplified)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hans/ --- Emby.Server.Implementations/Localization/Core/zh-CN.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index 3ae0fe5e77..12803456e3 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -115,5 +115,8 @@ "TasksApplicationCategory": "应用程序", "TasksMaintenanceCategory": "维护", "TaskCleanActivityLog": "清理程序日志", - "TaskCleanActivityLogDescription": "删除早于设置时间的活动日志条目。" + "TaskCleanActivityLogDescription": "删除早于设置时间的活动日志条目。", + "Undefined": "未定义", + "Forced": "强制的", + "Default": "默认" } From d608ab8042c03d6b84fd4d17c1ad9fb5f0e18192 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 18 Nov 2020 09:29:18 -0700 Subject: [PATCH 0413/1930] Fix null reference when saving plugin configuration --- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index e21d8c7d1b..e271bc03e1 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -276,7 +276,7 @@ namespace MediaBrowser.Common.Plugins SaveConfiguration(); - ConfigurationChanged.Invoke(this, configuration); + ConfigurationChanged?.Invoke(this, configuration); } /// <inheritdoc /> From c2d2c571e7958eea1052a31dd78897d75d58fcdd Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 18 Nov 2020 18:20:31 -0700 Subject: [PATCH 0414/1930] Set default request accept headers --- Jellyfin.Server/Startup.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 62ffe174cd..5a9a1690c0 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -66,10 +66,14 @@ namespace Jellyfin.Server var productHeader = new ProductInfoHeaderValue( _serverApplicationHost.Name.Replace(' ', '-'), _serverApplicationHost.ApplicationVersionString); + var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json); + var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*"); services .AddHttpClient(NamedClient.Default, c => { c.DefaultRequestHeaders.UserAgent.Add(productHeader); + c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader); + c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); @@ -77,6 +81,8 @@ namespace Jellyfin.Server { c.DefaultRequestHeaders.UserAgent.Add(productHeader); c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"({_serverApplicationHost.ApplicationUserAgentAddress})")); + c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader); + c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); From 3ffdcfdb802079ee9ad3e76527b4519f3fe4458a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 09:03:03 +0000 Subject: [PATCH 0415/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index a6130a8e7a..d9debeee35 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -271,6 +271,19 @@ namespace MediaBrowser.Common.Plugins XmlSerializer.SerializeToFile(config, ConfigurationFilePath); } } + + /// <summary> + /// Saves the current configuration to the file system. + /// </summary> + public virtual void SaveConfiguration() + { + lock (_configurationSaveLock) + { + _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); + + XmlSerializer.SerializeToFile(Configuration, ConfigurationFilePath); + } + } /// <inheritdoc /> public virtual void UpdateConfiguration(BasePluginConfiguration configuration) From 18855a7884ee5f33b124347425886cc974b424e8 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 13:34:09 +0000 Subject: [PATCH 0416/1930] Initialial upload --- .../Plugins/PluginManifest.cs | 5 + .../Updates/InstallationManager.cs | 98 ++++++++++++++++--- Jellyfin.Api/Controllers/PackageController.cs | 2 +- .../Routines/ReaddDefaultPluginRepository.cs | 6 +- .../Updates/IInstallationManager.cs | 7 +- MediaBrowser.Model/Updates/PackageInfo.cs | 12 +-- MediaBrowser.Model/Updates/RepositoryInfo.cs | 6 ++ MediaBrowser.Model/Updates/VersionInfo.cs | 30 +++++- 8 files changed, 134 insertions(+), 32 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManifest.cs b/Emby.Server.Implementations/Plugins/PluginManifest.cs index 33762791bc..63cad82716 100644 --- a/Emby.Server.Implementations/Plugins/PluginManifest.cs +++ b/Emby.Server.Implementations/Plugins/PluginManifest.cs @@ -56,5 +56,10 @@ namespace Emby.Server.Implementations.Plugins /// Gets or sets the Version number of the plugin. /// </summary> public string Version { get; set; } + + /// <summary> + /// Gets or sets the Repository where the plugin originated. + /// </summary> + public string Repository { get; set; } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 851e7bd68b..e23e0790b9 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -93,17 +93,29 @@ namespace Emby.Server.Implementations.Updates public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal; /// <inheritdoc /> - public async Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default) + public async Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, CancellationToken cancellationToken = default) { try { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetAsync(manifest, cancellationToken).ConfigureAwait(false); + .GetAsync(new Uri(manifest), cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); try { - return await _jsonSerializer.DeserializeFromStreamAsync<IReadOnlyList<PackageInfo>>(stream).ConfigureAwait(false); + var package = await _jsonSerializer.DeserializeFromStreamAsync<IList<PackageInfo>>(stream).ConfigureAwait(false); + + // Store the repository and repository url with each version, as they may be spread apart. + foreach (var entry in package) + { + foreach (var ver in entry.versions) + { + ver.repositoryName = manifestName; + ver.repositoryUrl = manifest; + } + } + + return package; } catch (SerializationException ex) { @@ -123,17 +135,69 @@ namespace Emby.Server.Implementations.Updates } } + private static void MergeSort(IList<VersionInfo> source, IList<VersionInfo> dest) + { + int sLength = source.Count - 1; + int dLength = dest.Count; + int s = 0, d = 0; + var sourceVersion = source[0].VersionNumber; + var destVersion = dest[0].VersionNumber; + + while (d < dLength) + { + if (sourceVersion.CompareTo(destVersion) >= 0) + { + if (s < sLength) + { + sourceVersion = source[++s].VersionNumber; + } + else + { + // Append all of destination to the end of source. + while (d < dLength) + { + source.Add(dest[d++]); + } + + break; + } + } + else + { + source.Insert(s++, dest[d++]); + if (d >= dLength) + { + break; + } + + sLength++; + destVersion = dest[d].VersionNumber; + } + } + } + /// <inheritdoc /> public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default) { var result = new List<PackageInfo>(); foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories) { - foreach (var package in await GetPackages(repository.Url, cancellationToken).ConfigureAwait(true)) + if (repository.Enabled) { - package.repositoryName = repository.Name; - package.repositoryUrl = repository.Url; - result.Add(package); + // Where repositories have the same content, the details of the first is taken. + foreach (var package in await GetPackages(repository.Name, repository.Url, cancellationToken).ConfigureAwait(true)) + { + var existing = FilterPackages(result, package.name, Guid.Parse(package.guid)).FirstOrDefault(); + if (existing != null) + { + // Assumption is both lists are ordered, so slot these into the correct place. + MergeSort(existing.versions, package.versions); + } + else + { + result.Add(package); + } + } } } @@ -144,7 +208,8 @@ namespace Emby.Server.Implementations.Updates public IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, string name = null, - Guid guid = default) + Guid guid = default, + Version specificVersion = null) { if (name != null) { @@ -156,6 +221,11 @@ namespace Emby.Server.Implementations.Updates availablePackages = availablePackages.Where(x => Guid.Parse(x.guid) == guid); } + if (specificVersion != null) + { + availablePackages = availablePackages.Where(x => x.versions.Where(y => y.VersionNumber.Equals(specificVersion)).Any()); + } + return availablePackages; } @@ -167,7 +237,7 @@ namespace Emby.Server.Implementations.Updates Version minVersion = null, Version specificVersion = null) { - var package = FilterPackages(availablePackages, name, guid).FirstOrDefault(); + var package = FilterPackages(availablePackages, name, guid, specificVersion).FirstOrDefault(); // Package not found in repository if (package == null) @@ -181,21 +251,21 @@ namespace Emby.Server.Implementations.Updates if (specificVersion != null) { - availableVersions = availableVersions.Where(x => new Version(x.version) == specificVersion); + availableVersions = availableVersions.Where(x => x.VersionNumber.Equals(specificVersion)); } else if (minVersion != null) { - availableVersions = availableVersions.Where(x => new Version(x.version) >= minVersion); + availableVersions = availableVersions.Where(x => x.VersionNumber >= minVersion); } - foreach (var v in availableVersions.OrderByDescending(x => x.version)) + foreach (var v in availableVersions.OrderByDescending(x => x.VersionNumber)) { yield return new InstallationInfo { Changelog = v.changelog, Guid = new Guid(package.guid), Name = package.name, - Version = new Version(v.version), + Version = v.VersionNumber, SourceUrl = v.sourceUrl, Checksum = v.checksum }; @@ -322,7 +392,7 @@ namespace Emby.Server.Implementations.Updates private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken) { - var extension = Path.GetExtension(package.SourceUrl); + var extension = Path.GetExtension(package.SourceUrl.ToString()); if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase)) { _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl); diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 1f797d6bc3..83b3597665 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -99,7 +99,7 @@ namespace Jellyfin.Api.Controllers var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); if (!string.IsNullOrEmpty(repositoryUrl)) { - packages = packages.Where(p => p.repositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase)) + packages = packages.Where(p => p.versions.Where(q => q.repositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase)).Any()) .ToList(); } diff --git a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs index b281b5cc09..db605c54ec 100644 --- a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs +++ b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs @@ -1,4 +1,4 @@ -using System; +using System; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Updates; @@ -14,7 +14,7 @@ namespace Jellyfin.Server.Migrations.Routines private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo { Name = "Jellyfin Stable", - Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" + Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json", }; /// <summary> @@ -46,4 +46,4 @@ namespace Jellyfin.Server.Migrations.Routines } } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 6aa16fea74..585b1ee19e 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -19,10 +19,11 @@ namespace MediaBrowser.Common.Updates /// <summary> /// Parses a plugin manifest at the supplied URL. /// </summary> + /// <param name="manifestName">Name of the repository.</param> /// <param name="manifest">The URL to query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task{IReadOnlyList{PackageInfo}}.</returns> - Task<IReadOnlyList<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default); + Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, CancellationToken cancellationToken = default); /// <summary> /// Gets all available packages. @@ -37,11 +38,13 @@ namespace MediaBrowser.Common.Updates /// <param name="availablePackages">The available packages.</param> /// <param name="name">The name of the plugin.</param> /// <param name="guid">The id of the plugin.</param> + /// <param name="specificVersion">The version of the plugin.</param> /// <returns>All plugins matching the requirements.</returns> IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, string name = null, - Guid guid = default); + Guid guid = default, + Version specificVersion = null); /// <summary> /// Returns all compatible versions ordered from newest to oldest. diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 98b151d551..5e93043639 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -50,17 +50,7 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the versions. /// </summary> /// <value>The versions.</value> - public IReadOnlyList<VersionInfo> versions { get; set; } - - /// <summary> - /// Gets or sets the repository name. - /// </summary> - public string repositoryName { get; set; } - - /// <summary> - /// Gets or sets the repository url. - /// </summary> - public string repositoryUrl { get; set; } + public IList<VersionInfo> versions { get; set; } /// <summary> /// Initializes a new instance of the <see cref="PackageInfo"/> class. diff --git a/MediaBrowser.Model/Updates/RepositoryInfo.cs b/MediaBrowser.Model/Updates/RepositoryInfo.cs index bd42e77f0f..705d3b33cc 100644 --- a/MediaBrowser.Model/Updates/RepositoryInfo.cs +++ b/MediaBrowser.Model/Updates/RepositoryInfo.cs @@ -16,5 +16,11 @@ namespace MediaBrowser.Model.Updates /// </summary> /// <value>The URL.</value> public string? Url { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the repository is enabled. + /// </summary> + /// <value><c>true</c> if enabled.</value> + public bool Enabled { get; set; } = true; } } diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs index a4aa0e75f3..844170999a 100644 --- a/MediaBrowser.Model/Updates/VersionInfo.cs +++ b/MediaBrowser.Model/Updates/VersionInfo.cs @@ -9,11 +9,29 @@ namespace MediaBrowser.Model.Updates /// </summary> public class VersionInfo { + private Version _version; + /// <summary> /// Gets or sets the version. /// </summary> /// <value>The version.</value> - public string version { get; set; } + public string version + { + get + { + return _version == null ? string.Empty : _version.ToString(); + } + + set + { + _version = Version.Parse(value); + } + } + + /// <summary> + /// Gets the version as a <see cref="Version"/>. + /// </summary> + public Version VersionNumber => _version; /// <summary> /// Gets or sets the changelog for this version. @@ -44,5 +62,15 @@ namespace MediaBrowser.Model.Updates /// </summary> /// <value>The timestamp.</value> public string timestamp { get; set; } + + /// <summary> + /// Gets or sets the repository name. + /// </summary> + public string repositoryName { get; set; } + + /// <summary> + /// Gets or sets the repository url. + /// </summary> + public string repositoryUrl { get; set; } } } From 4e07d9d5618d4f093cc102fb1f43f40c95c1aa47 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Thu, 19 Nov 2020 08:49:21 -0500 Subject: [PATCH 0417/1930] Update FFmpeg log --- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 36 ++++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 168dc27a83..11682d88b1 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -145,7 +145,7 @@ namespace Jellyfin.Api.Helpers lock (_activeTranscodingJobs) { // This is really only needed for HLS. - // Progressive streams can stop on their own reliably + // Progressive streams can stop on their own reliably. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList(); } @@ -241,7 +241,7 @@ namespace Jellyfin.Api.Helpers lock (_activeTranscodingJobs) { // This is really only needed for HLS. - // Progressive streams can stop on their own reliably + // Progressive streams can stop on their own reliably. jobs.AddRange(_activeTranscodingJobs.Where(killJob)); } @@ -304,10 +304,10 @@ namespace Jellyfin.Api.Helpers process!.StandardInput.WriteLine("q"); - // Need to wait because killing is asynchronous + // Need to wait because killing is asynchronous. if (!process.WaitForExit(5000)) { - _logger.LogInformation("Killing ffmpeg process for {Path}", job.Path); + _logger.LogInformation("Killing FFmpeg process for {Path}", job.Path); process.Kill(); } } @@ -470,11 +470,11 @@ namespace Jellyfin.Api.Helpers } /// <summary> - /// Starts the FFMPEG. + /// Starts FFmpeg. /// </summary> /// <param name="state">The state.</param> /// <param name="outputPath">The output path.</param> - /// <param name="commandLineArguments">The command line arguments for ffmpeg.</param> + /// <param name="commandLineArguments">The command line arguments for FFmpeg.</param> /// <param name="request">The <see cref="HttpRequest"/>.</param> /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param> /// <param name="cancellationTokenSource">The cancellation token source.</param> @@ -501,13 +501,13 @@ namespace Jellyfin.Api.Helpers { this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state); - throw new ArgumentException("User does not have access to video transcoding"); + throw new ArgumentException("User does not have access to video transcoding."); } } if (string.IsNullOrEmpty(_mediaEncoder.EncoderPath)) { - throw new ArgumentException("FFMPEG path not set."); + throw new ArgumentException("FFmpeg path not set."); } var process = new Process @@ -544,18 +544,18 @@ namespace Jellyfin.Api.Helpers var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; _logger.LogInformation(commandLineLogMessage); - var logFilePrefix = "ffmpeg-transcode"; + var logFilePrefix = "FFmpeg.Transcode-"; if (state.VideoRequest != null && EncodingHelper.IsCopyCodec(state.OutputVideoCodec)) { logFilePrefix = EncodingHelper.IsCopyCodec(state.OutputAudioCodec) - ? "ffmpeg-remux" - : "ffmpeg-directstream"; + ? "FFmpeg.Remux-" + : "FFmpeg.DirectStream-"; } - var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt"); + var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("YYYY-MM-dd_HH-mm-ss") + "_" + state.Request.MediaSourceId + ".log"); - // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. + // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); @@ -569,17 +569,17 @@ namespace Jellyfin.Api.Helpers } catch (Exception ex) { - _logger.LogError(ex, "Error starting ffmpeg"); + _logger.LogError(ex, "Error starting FFmpeg"); this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state); throw; } - _logger.LogDebug("Launched ffmpeg process"); + _logger.LogDebug("Launched FFmpeg process"); state.TranscodingJob = transcodingJob; - // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback + // Important - don't await the log task or we won't be able to kill FFmpeg when the user stops playback _ = new JobLogger(_logger).StartStreamingLog(state, process.StandardError.BaseStream, logStream); // Wait for the file to exist before proceeeding @@ -748,11 +748,11 @@ namespace Jellyfin.Api.Helpers if (process.ExitCode == 0) { - _logger.LogInformation("FFMpeg exited with code 0"); + _logger.LogInformation("FFmpeg exited with code 0"); } else { - _logger.LogError("FFMpeg exited with code {0}", process.ExitCode); + _logger.LogError("FFmpeg exited with code {0}", process.ExitCode); } process.Dispose(); From e6e72953209a9f0e383eed71282269a8aa2cc0cb Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Thu, 19 Nov 2020 08:58:16 -0500 Subject: [PATCH 0418/1930] oops --- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 11682d88b1..da898d3d98 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,7 +553,7 @@ namespace Jellyfin.Api.Helpers : "FFmpeg.DirectStream-"; } - var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("YYYY-MM-dd_HH-mm-ss") + "_" + state.Request.MediaSourceId + ".log"); + var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + state.Request.MediaSourceId + ".log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); From 1df58fbaa0b002a75c3b0d9f21b51461a2d9cd69 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 14:12:33 +0000 Subject: [PATCH 0419/1930] updated --- Emby.Server.Implementations/Updates/InstallationManager.cs | 4 ++-- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index e23e0790b9..7a071c071a 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -392,7 +392,7 @@ namespace Emby.Server.Implementations.Updates private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken) { - var extension = Path.GetExtension(package.SourceUrl.ToString()); + var extension = Path.GetExtension(package.SourceUrl); if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase)) { _logger.LogError("Only zip packages are supported. {SourceUrl} is not a zip archive.", package.SourceUrl); @@ -403,7 +403,7 @@ namespace Emby.Server.Implementations.Updates string targetDir = Path.Combine(_appPaths.PluginsPath, package.Name); using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetAsync(package.SourceUrl, cancellationToken).ConfigureAwait(false); + .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); // CA5351: Do Not Use Broken Cryptographic Algorithms diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 0f8ceba291..98f1bc2d23 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; From c53b4f55472e517744d4db8a4ce5e9cff31514bb Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 19 Nov 2020 07:35:34 -0700 Subject: [PATCH 0420/1930] Add xml and quality --- Jellyfin.Server/Startup.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 5a9a1690c0..c1a8b75c68 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -66,13 +66,15 @@ namespace Jellyfin.Server var productHeader = new ProductInfoHeaderValue( _serverApplicationHost.Name.Replace(' ', '-'), _serverApplicationHost.ApplicationVersionString); - var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json); - var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*"); + var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0); + var acceptXmlHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Xml, 0.9); + var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*", 0.8); services .AddHttpClient(NamedClient.Default, c => { c.DefaultRequestHeaders.UserAgent.Add(productHeader); c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader); + c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader); c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); From 5790db05ba9c28d3aba83bf437d29820f3d02be8 Mon Sep 17 00:00:00 2001 From: Patrick Barron <barronpm@gmail.com> Date: Thu, 19 Nov 2020 09:38:54 -0500 Subject: [PATCH 0421/1930] Clean up DeviceManager and don't store capabilities on disk --- .../Devices/DeviceManager.cs | 71 +++---------------- .../Session/SessionManager.cs | 24 +------ 2 files changed, 12 insertions(+), 83 deletions(-) diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index f98c694c46..da5047d244 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -1,61 +1,38 @@ #pragma warning disable CS1591 using System; +using System.Collections.Concurrent; using System.Collections.Generic; -using System.Globalization; -using System.IO; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Data.Events; -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Security; using MediaBrowser.Model.Devices; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Session; -using Microsoft.Extensions.Caching.Memory; namespace Emby.Server.Implementations.Devices { public class DeviceManager : IDeviceManager { - private readonly IMemoryCache _memoryCache; - private readonly IJsonSerializer _json; private readonly IUserManager _userManager; - private readonly IServerConfigurationManager _config; private readonly IAuthenticationRepository _authRepo; - private readonly object _capabilitiesSyncLock = new object(); + private readonly ConcurrentDictionary<string, ClientCapabilities> _capabilitiesMap = new (); - public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated; - - public DeviceManager( - IAuthenticationRepository authRepo, - IJsonSerializer json, - IUserManager userManager, - IServerConfigurationManager config, - IMemoryCache memoryCache) + public DeviceManager(IAuthenticationRepository authRepo, IUserManager userManager) { - _json = json; _userManager = userManager; - _config = config; - _memoryCache = memoryCache; _authRepo = authRepo; } + public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated; + public void SaveCapabilities(string deviceId, ClientCapabilities capabilities) { - var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json"); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - - lock (_capabilitiesSyncLock) - { - _memoryCache.Set(deviceId, capabilities); - _json.SerializeToFile(capabilities, path); - } + _capabilitiesMap[deviceId] = capabilities; } public void UpdateDeviceOptions(string deviceId, DeviceOptions options) @@ -72,32 +49,12 @@ namespace Emby.Server.Implementations.Devices public ClientCapabilities GetCapabilities(string id) { - if (_memoryCache.TryGetValue(id, out ClientCapabilities result)) - { - return result; - } - - lock (_capabilitiesSyncLock) - { - var path = Path.Combine(GetDevicePath(id), "capabilities.json"); - try - { - return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities(); - } - catch - { - } - } - - return new ClientCapabilities(); + return _capabilitiesMap.TryGetValue(id, out ClientCapabilities result) + ? result + : new ClientCapabilities(); } public DeviceInfo GetDevice(string id) - { - return GetDevice(id, true); - } - - private DeviceInfo GetDevice(string id, bool includeCapabilities) { var session = _authRepo.Get(new AuthenticationInfoQuery { @@ -154,16 +111,6 @@ namespace Emby.Server.Implementations.Devices }; } - private string GetDevicesPath() - { - return Path.Combine(_config.ApplicationPaths.DataPath, "devices"); - } - - private string GetDevicePath(string id) - { - return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture)); - } - public bool CanAccessDevice(User user, string deviceId) { if (user == null) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 607b322f2e..afddfa856b 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -58,8 +58,7 @@ namespace Emby.Server.Implementations.Session /// <summary> /// The active connections. /// </summary> - private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections = - new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections = new (StringComparer.OrdinalIgnoreCase); private Timer _idleTimer; @@ -196,7 +195,7 @@ namespace Emby.Server.Implementations.Session { if (!string.IsNullOrEmpty(info.DeviceId)) { - var capabilities = GetSavedCapabilities(info.DeviceId); + var capabilities = _deviceManager.GetCapabilities(info.DeviceId); if (capabilities != null) { @@ -1677,27 +1676,10 @@ namespace Emby.Server.Implementations.Session SessionInfo = session }); - try - { - SaveCapabilities(session.DeviceId, capabilities); - } - catch (Exception ex) - { - _logger.LogError("Error saving device capabilities", ex); - } + _deviceManager.SaveCapabilities(session.DeviceId, capabilities); } } - private ClientCapabilities GetSavedCapabilities(string deviceId) - { - return _deviceManager.GetCapabilities(deviceId); - } - - private void SaveCapabilities(string deviceId, ClientCapabilities capabilities) - { - _deviceManager.SaveCapabilities(deviceId, capabilities); - } - /// <summary> /// Converts a BaseItem to a BaseItemInfo. /// </summary> From 31980e6f87543314d041d9ef4cc38356f752fb70 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 14:40:06 +0000 Subject: [PATCH 0422/1930] Fixed issue with plugins being deleted. --- Emby.Server.Implementations/ApplicationHost.cs | 5 +++-- Emby.Server.Implementations/Plugins/PluginManifest.cs | 5 ----- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 17b99c858f..cba9afb986 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -999,7 +999,7 @@ namespace Emby.Server.Implementations var versions = new List<LocalPlugin>(); if (!Directory.Exists(path)) { - // Plugin path doesn't exist, don't try to enumerate subfolders. + // Plugin path doesn't exist, don't try to enumerate sub-folders. return Enumerable.Empty<LocalPlugin>(); } @@ -1070,7 +1070,6 @@ namespace Emby.Server.Implementations if (!string.IsNullOrEmpty(lastName) && cleanup) { // Attempt a cleanup of old folders. - versions.RemoveAt(x); try { Logger.LogDebug("Deleting {Path}", versions[x].Path); @@ -1080,6 +1079,8 @@ namespace Emby.Server.Implementations { Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path); } + + versions.RemoveAt(x); } } diff --git a/Emby.Server.Implementations/Plugins/PluginManifest.cs b/Emby.Server.Implementations/Plugins/PluginManifest.cs index 63cad82716..33762791bc 100644 --- a/Emby.Server.Implementations/Plugins/PluginManifest.cs +++ b/Emby.Server.Implementations/Plugins/PluginManifest.cs @@ -56,10 +56,5 @@ namespace Emby.Server.Implementations.Plugins /// Gets or sets the Version number of the plugin. /// </summary> public string Version { get; set; } - - /// <summary> - /// Gets or sets the Repository where the plugin originated. - /// </summary> - public string Repository { get; set; } } } From 51dab0958d11e142f582da9c46a8679335b99dda Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 19 Nov 2020 22:46:02 +0800 Subject: [PATCH 0423/1930] changes per suggestions --- .../Controllers/DynamicHlsController.cs | 91 ++----- .../Controllers/VideoHlsController.cs | 90 ++----- Jellyfin.Api/Helpers/HlsHelpers.cs | 20 +- .../MediaEncoding/EncodingHelper.cs | 227 ++++++++++++------ 4 files changed, 193 insertions(+), 235 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 28357091bb..90c2a6b58b 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -43,7 +43,7 @@ namespace Jellyfin.Api.Controllers public class DynamicHlsController : BaseJellyfinApiController { private const string DefaultEncoderPreset = "veryfast"; - private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private const TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; private readonly ILibraryManager _libraryManager; private readonly IUserManager _userManager; @@ -1446,58 +1446,38 @@ namespace Jellyfin.Api.Controllers { if (EncodingHelper.IsCopyCodec(audioCodec)) { - var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); - var bitStreamArgs = string.Empty; - - // Apply aac_adtstoasc bitstream filter when media source is in mpegts. - if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) - && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) - || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) - { - bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; - } + var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container); return "-acodec copy -strict -2" + bitStreamArgs; } - var audioTranscodeParams = new List<string>(); + var audioTranscodeParams = string.Empty; - audioTranscodeParams.Add("-acodec " + audioCodec); + audioTranscodeParams += "-acodec " + audioCodec; if (state.OutputAudioBitrate.HasValue) { - audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture); } if (state.OutputAudioChannels.HasValue) { - audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture); } if (state.OutputAudioSampleRate.HasValue) { - audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture); } - audioTranscodeParams.Add("-vn"); - return string.Join(' ', audioTranscodeParams); + audioTranscodeParams += " -vn"; + return audioTranscodeParams; } if (EncodingHelper.IsCopyCodec(audioCodec)) { var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); - var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); - var bitStreamArgs = string.Empty; - - // Apply aac_adtstoasc bitstream filter when media source is in mpegts. - if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) - && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) - || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) - { - bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; - } + var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container); if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec)) { @@ -1528,7 +1508,7 @@ namespace Jellyfin.Api.Controllers args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture); } - args += " " + _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true); + args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true); return args; } @@ -1574,7 +1554,7 @@ namespace Jellyfin.Api.Controllers { if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { - string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.VideoStream); + string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream); if (!string.IsNullOrEmpty(bitStreamArgs)) { args += " " + bitStreamArgs; @@ -1587,51 +1567,10 @@ namespace Jellyfin.Api.Controllers } else { - var gopArg = string.Empty; - var keyFrameArg = string.Format( - CultureInfo.InvariantCulture, - " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"", - startNumber * state.SegmentLength, - state.SegmentLength); + args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); - var framerate = state.VideoStream?.RealFrameRate; - if (framerate.HasValue) - { - // This is to make sure keyframe interval is limited to our segment, - // as forcing keyframes is not enough. - // Example: we encoded half of desired length, then codec detected - // scene cut and inserted a keyframe; next forced keyframe would - // be created outside of segment, which breaks seeking. - // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe. - gopArg = string.Format( - CultureInfo.InvariantCulture, - " -g {0} -keyint_min {0} -sc_threshold 0", - Math.Ceiling(state.SegmentLength * framerate.Value)); - } - - args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); - - // Unable to force key frames using these encoders, set key frames by GOP. - if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase)) - { - args += " " + gopArg; - } - else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) - { - args += " " + keyFrameArg; - } - else - { - args += " " + keyFrameArg + gopArg; - } + // Set the key frame params for video encoding to match the hls segment time. + args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, false, startNumber); // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now. if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index b03402c1b0..bb80265436 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -367,7 +367,7 @@ namespace Jellyfin.Api.Controllers var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension); - var outputExtension = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer); + var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer); var outputTsArg = outputPrefix + "%d" + outputExtension; var segmentFormat = outputExtension.TrimStart('.'); @@ -441,57 +441,37 @@ namespace Jellyfin.Api.Controllers { if (EncodingHelper.IsCopyCodec(audioCodec)) { - var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); - var bitStreamArgs = string.Empty; - - // Apply aac_adtstoasc bitstream filter when media source is in mpegts. - if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) - && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) - || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) - { - bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; - } + var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container); return "-acodec copy -strict -2" + bitStreamArgs; } - var audioTranscodeParams = new List<string>(); + var audioTranscodeParams = string.Empty; - audioTranscodeParams.Add("-acodec " + audioCodec); + audioTranscodeParams += "-acodec " + audioCodec; if (state.OutputAudioBitrate.HasValue) { - audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ab " + state.OutputAudioBitrate.Value.ToString(CultureInfo.InvariantCulture); } if (state.OutputAudioChannels.HasValue) { - audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture); } if (state.OutputAudioSampleRate.HasValue) { - audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)); + audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture); } - audioTranscodeParams.Add("-vn"); - return string.Join(' ', audioTranscodeParams); + audioTranscodeParams += " -vn"; + return audioTranscodeParams; } if (EncodingHelper.IsCopyCodec(audioCodec)) { - var segmentFormat = HlsHelpers.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); - var bitStreamArgs = string.Empty; - - // Apply aac_adtstoasc bitstream filter when media source is in mpegts. - if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) - && (string.Equals(state.MediaSource.Container, "mpegts", StringComparison.OrdinalIgnoreCase) - || string.Equals(state.MediaSource.Container, "hls", StringComparison.OrdinalIgnoreCase))) - { - bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.AudioStream); - bitStreamArgs = !string.IsNullOrEmpty(bitStreamArgs) ? " " + bitStreamArgs : string.Empty; - } + var bitStreamArgs = EncodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.MediaSource.Container); return "-acodec copy -strict -2" + bitStreamArgs; } @@ -517,7 +497,7 @@ namespace Jellyfin.Api.Controllers args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture); } - args += " " + _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true); + args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions, true); return args; } @@ -563,7 +543,7 @@ namespace Jellyfin.Api.Controllers // If h264_mp4toannexb is ever added, do not use it for live tv. if (state.VideoStream != null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { - string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state.VideoStream); + string bitStreamArgs = EncodingHelper.GetBitStreamArgs(state.VideoStream); if (!string.IsNullOrEmpty(bitStreamArgs)) { args += " " + bitStreamArgs; @@ -574,50 +554,10 @@ namespace Jellyfin.Api.Controllers } else { - var gopArg = string.Empty; - var keyFrameArg = string.Format( - CultureInfo.InvariantCulture, - " -force_key_frames \"expr:gte(t,n_forced*{0})\"", - state.SegmentLength.ToString(CultureInfo.InvariantCulture)); + args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); - var framerate = state.VideoStream?.RealFrameRate; - if (framerate.HasValue) - { - // This is to make sure keyframe interval is limited to our segment, - // as forcing keyframes is not enough. - // Example: we encoded half of desired length, then codec detected - // scene cut and inserted a keyframe; next forced keyframe would - // be created outside of segment, which breaks seeking. - // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe. - gopArg = string.Format( - CultureInfo.InvariantCulture, - " -g {0} -keyint_min {0} -sc_threshold 0", - Math.Ceiling(state.SegmentLength * framerate.Value)); - } - - args += " " + _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, DefaultEncoderPreset); - - // Unable to force key frames using these encoders, set key frames by GOP. - if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase)) - { - args += " " + gopArg; - } - else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) - { - args += " " + keyFrameArg; - } - else - { - args += " " + keyFrameArg + gopArg; - } + // Set the key frame params for video encoding to match the hls segment time. + args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, true, null); // Currenly b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now. if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)) diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 1c874e4bdb..18e23fb5c8 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; +using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; using Microsoft.Extensions.Logging; @@ -76,21 +77,6 @@ namespace Jellyfin.Api.Helpers } } - /// <summary> - /// Gets the extension of segment container. - /// </summary> - /// <param name="segmentContainer">The name of the segment container.</param> - /// <returns>The string text of extension.</returns> - public static string GetSegmentFileExtension(string? segmentContainer) - { - if (!string.IsNullOrWhiteSpace(segmentContainer)) - { - return "." + segmentContainer; - } - - return ".ts"; - } - /// <summary> /// Gets the #EXT-X-MAP string. /// </summary> @@ -103,7 +89,7 @@ namespace Jellyfin.Api.Helpers var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath); var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension); - var outputExtension = GetSegmentFileExtension(state.Request.SegmentContainer); + var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer); // on Linux/Unix // #EXT-X-MAP:URI="prefix-1.mp4" @@ -137,7 +123,7 @@ namespace Jellyfin.Api.Helpers var text = reader.ReadToEnd(); - var segmentFormat = GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); + var segmentFormat = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) { var fmp4InitFileName = GetFmp4InitFileName(path, state, true); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index b181a6ee6d..a2e3318f3d 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -580,7 +580,7 @@ namespace MediaBrowser.Controller.MediaEncoding /// </summary> /// <param name="stream">The stream.</param> /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns> - public bool IsH264(MediaStream stream) + public static bool IsH264(MediaStream stream) { var codec = stream.Codec ?? string.Empty; @@ -588,7 +588,7 @@ namespace MediaBrowser.Controller.MediaEncoding || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1; } - public bool IsH265(MediaStream stream) + public static bool IsH265(MediaStream stream) { var codec = stream.Codec ?? string.Empty; @@ -596,14 +596,14 @@ namespace MediaBrowser.Controller.MediaEncoding || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1; } - public bool IsAAC(MediaStream stream) + public static bool IsAAC(MediaStream stream) { var codec = stream.Codec ?? string.Empty; return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1; } - public string GetBitStreamArgs(MediaStream stream) + public static string GetBitStreamArgs(MediaStream stream) { // TODO This is auto inserted into the mpegts mux so it might not be needed. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb @@ -626,6 +626,33 @@ namespace MediaBrowser.Controller.MediaEncoding } } + public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer) + { + var bitStreamArgs = string.Empty; + var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.'); + + // Apply aac_adtstoasc bitstream filter when media source is in mpegts. + if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase) + && (string.Equals(mediaSourceContainer, "mpegts", StringComparison.OrdinalIgnoreCase) + || string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase))) + { + bitStreamArgs = GetBitStreamArgs(state.AudioStream); + bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs; + } + + return bitStreamArgs; + } + + public static string GetSegmentFileExtension(string segmentContainer) + { + if (!string.IsNullOrWhiteSpace(segmentContainer)) + { + return "." + segmentContainer; + } + + return ".ts"; + } + public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec) { var bitrate = state.OutputVideoBitrate; @@ -799,6 +826,72 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } + public string GetHlsVideoKeyFrameArguments( + EncodingJobInfo state, + string codec, + int segmentLength, + bool isEventPlaylist, + int? startNumber) + { + var args = string.Empty; + var gopArg = string.Empty; + var keyFrameArg = string.Empty; + if (isEventPlaylist) + { + keyFrameArg = string.Format( + CultureInfo.InvariantCulture, + " -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"", + segmentLength); + } + else if (startNumber.HasValue) + { + keyFrameArg = string.Format( + CultureInfo.InvariantCulture, + " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"", + startNumber.Value * segmentLength, + segmentLength); + } + + var framerate = state.VideoStream?.RealFrameRate; + if (framerate.HasValue) + { + // This is to make sure keyframe interval is limited to our segment, + // as forcing keyframes is not enough. + // Example: we encoded half of desired length, then codec detected + // scene cut and inserted a keyframe; next forced keyframe would + // be created outside of segment, which breaks seeking. + // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe. + gopArg = string.Format( + CultureInfo.InvariantCulture, + " -g:v:0 {0} -keyint_min:v:0 {0} -sc_threshold:v:0 0", + Math.Ceiling(segmentLength * framerate.Value)); + } + + // Unable to force key frames using these encoders, set key frames by GOP. + if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + args += gopArg; + } + else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) + { + args += " " + keyFrameArg; + } + else + { + args += " " + keyFrameArg + gopArg; + } + + return args; + } + /// <summary> /// Gets the video bitrate to specify on the command line. /// </summary> @@ -806,6 +899,47 @@ namespace MediaBrowser.Controller.MediaEncoding { var param = string.Empty; + if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + param += " -pix_fmt yuv420p"; + } + + if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + { + var videoStream = state.VideoStream; + var isColorDepth10 = IsColorDepth10(state); + + if (isColorDepth10 + && _mediaEncoder.SupportsHwaccel("opencl") + && encodingOptions.EnableTonemapping + && !string.IsNullOrEmpty(videoStream.VideoRange) + && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) + { + param += " -pix_fmt nv12"; + } + else + { + param += " -pix_fmt yuv420p"; + } + } + + if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) + { + param += " -pix_fmt nv21"; + } + var isVc1 = state.VideoStream != null && string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase); var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase); @@ -814,11 +948,11 @@ namespace MediaBrowser.Controller.MediaEncoding { if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset)) { - param += "-preset " + encodingOptions.EncoderPreset; + param += " -preset " + encodingOptions.EncoderPreset; } else { - param += "-preset " + defaultPreset; + param += " -preset " + defaultPreset; } int encodeCrf = encodingOptions.H264Crf; @@ -849,11 +983,11 @@ namespace MediaBrowser.Controller.MediaEncoding if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase)) { - param += "-preset " + encodingOptions.EncoderPreset; + param += " -preset " + encodingOptions.EncoderPreset; } else { - param += "-preset 7"; + param += " -preset 7"; } param += " -look_ahead 0"; @@ -866,16 +1000,16 @@ namespace MediaBrowser.Controller.MediaEncoding { case "veryslow": - param += "-preset slow"; // lossless is only supported on maxwell and newer(2014+) + param += " -preset slow"; // lossless is only supported on maxwell and newer(2014+) break; case "slow": case "slower": - param += "-preset slow"; + param += " -preset slow"; break; case "medium": - param += "-preset medium"; + param += " -preset medium"; break; case "fast": @@ -883,11 +1017,11 @@ namespace MediaBrowser.Controller.MediaEncoding case "veryfast": case "superfast": case "ultrafast": - param += "-preset fast"; + param += " -preset fast"; break; default: - param += "-preset default"; + param += " -preset default"; break; } } @@ -899,11 +1033,11 @@ namespace MediaBrowser.Controller.MediaEncoding case "veryslow": case "slow": case "slower": - param += "-quality quality"; + param += " -quality quality"; break; case "medium": - param += "-quality balanced"; + param += " -quality balanced"; break; case "fast": @@ -911,11 +1045,11 @@ namespace MediaBrowser.Controller.MediaEncoding case "veryfast": case "superfast": case "ultrafast": - param += "-quality speed"; + param += " -quality speed"; break; default: - param += "-quality speed"; + param += " -quality speed"; break; } @@ -957,7 +1091,7 @@ namespace MediaBrowser.Controller.MediaEncoding profileScore = Math.Min(profileScore, 2); // http://www.webmproject.org/docs/encoder-parameters/ - param += string.Format(CultureInfo.InvariantCulture, "-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}", + param += string.Format(CultureInfo.InvariantCulture, " -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}", profileScore.ToString(_usCulture), crf, qmin, @@ -965,15 +1099,15 @@ namespace MediaBrowser.Controller.MediaEncoding } else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase)) { - param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2"; + param += " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2"; } else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv { - param += "-qmin 2"; + param += " -qmin 2"; } else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase)) { - param += "-mbd 2"; + param += " -mbd 2"; } param += GetVideoBitrateParam(state, videoEncoder); @@ -1035,7 +1169,7 @@ namespace MediaBrowser.Controller.MediaEncoding && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) { // not supported by h264_omx - param += " -profile:v " + profile; + param += " -profile:v:0 " + profile; } } @@ -1091,47 +1225,6 @@ namespace MediaBrowser.Controller.MediaEncoding param += " -x265-params:0 no-info=1"; } - if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) - && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) - { - param = "-pix_fmt yuv420p " + param; - } - - if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) - { - var videoStream = state.VideoStream; - var isColorDepth10 = IsColorDepth10(state); - - if (isColorDepth10 - && _mediaEncoder.SupportsHwaccel("opencl") - && encodingOptions.EnableTonemapping - && !string.IsNullOrEmpty(videoStream.VideoRange) - && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) - { - param = "-pix_fmt nv12 " + param; - } - else - { - param = "-pix_fmt yuv420p " + param; - } - } - - if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)) - { - param = "-pix_fmt nv21 " + param; - } - return param; } @@ -1521,7 +1614,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (filters.Count > 0) { - return "-af \"" + string.Join(",", filters) + "\""; + return " -af \"" + string.Join(",", filters) + "\""; } return string.Empty; @@ -3378,7 +3471,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps) { - args += " -copyts -avoid_negative_ts 0 -start_at_zero"; + args += " -copyts -avoid_negative_ts disabled -start_at_zero"; } if (!state.RunTimeTicks.HasValue) @@ -3426,7 +3519,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -copyts"; } - args += " -avoid_negative_ts 0"; + args += " -avoid_negative_ts disabled"; if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)) { @@ -3490,7 +3583,7 @@ namespace MediaBrowser.Controller.MediaEncoding args += " -ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture); } - args += " " + GetAudioFilterParam(state, encodingOptions, false); + args += GetAudioFilterParam(state, encodingOptions, false); return args; } From f8dd50fc1ae434be61f0ffb9519a40d5d6448df1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= <oddstr13@openshell.no> Date: Thu, 19 Nov 2020 15:41:58 +0100 Subject: [PATCH 0424/1930] Fix plugin old version cleanup --- Emby.Server.Implementations/ApplicationHost.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 17b99c858f..aa2ec158fa 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1070,7 +1070,6 @@ namespace Emby.Server.Implementations if (!string.IsNullOrEmpty(lastName) && cleanup) { // Attempt a cleanup of old folders. - versions.RemoveAt(x); try { Logger.LogDebug("Deleting {Path}", versions[x].Path); @@ -1080,6 +1079,8 @@ namespace Emby.Server.Implementations { Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path); } + + versions.RemoveAt(x); } } From 5ff08338d5a475d2975ecc6d4fe5222456368bd2 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Thu, 19 Nov 2020 15:02:36 +0000 Subject: [PATCH 0425/1930] Apply suggestions from code review Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- .../Controllers/VideoHlsController.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 6 ++--- .../Probing/ProbeResultNormalizer.cs | 23 +++++++------------ MediaBrowser.Model/Dlna/StreamBuilder.cs | 12 +++++----- 4 files changed, 18 insertions(+), 25 deletions(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index bb80265436..b151f85e2d 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -578,7 +578,7 @@ namespace Jellyfin.Api.Controllers args += _encodingHelper.GetOutputSizeParam(state, _encodingOptions, codec); } - if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)) + if (state.SubtitleStream == null || !state.SubtitleStream.IsExternal || state.SubtitleStream.IsTextSubtitleStream) { args += " -start_at_zero"; } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index a2e3318f3d..6e36adc169 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1194,7 +1194,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) { param += " -level " + level; } @@ -1205,7 +1205,7 @@ namespace MediaBrowser.Controller.MediaEncoding // NVENC cannot adjust the given level, just throw an error. } else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) - || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) + || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase)) { param += " -level " + level; } @@ -1931,7 +1931,7 @@ namespace MediaBrowser.Controller.MediaEncoding retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\""; } else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) + || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) { /* QSV in FFMpeg can now setup hardware overlay for transcodes. diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 387594ce63..3d3d1eb48f 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1025,12 +1025,10 @@ namespace MediaBrowser.MediaEncoding.Probing if (streamInfo != null && streamInfo.Tags != null) { var bps = GetDictionaryValue(streamInfo.Tags, "BPS-eng") ?? GetDictionaryValue(streamInfo.Tags, "BPS"); - if (!string.IsNullOrEmpty(bps)) + if (!string.IsNullOrEmpty(bps) + && int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps)) { - if (int.TryParse(bps, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBps)) - { - return parsedBps; - } + return parsedBps; } } @@ -1042,12 +1040,9 @@ namespace MediaBrowser.MediaEncoding.Probing if (streamInfo != null && streamInfo.Tags != null) { var duration = GetDictionaryValue(streamInfo.Tags, "DURATION-eng") ?? GetDictionaryValue(streamInfo.Tags, "DURATION"); - if (!string.IsNullOrEmpty(duration)) + if (!string.IsNullOrEmpty(duration) && TimeSpan.TryParse(duration, out var parsedDuration)) { - if (TimeSpan.TryParse(duration, out var parsedDuration)) - { - return parsedDuration.TotalSeconds; - } + return parsedDuration.TotalSeconds; } } @@ -1059,12 +1054,10 @@ namespace MediaBrowser.MediaEncoding.Probing if (streamInfo != null && streamInfo.Tags != null) { var numberOfBytes = GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES-eng") ?? GetDictionaryValue(streamInfo.Tags, "NUMBER_OF_BYTES"); - if (!string.IsNullOrEmpty(numberOfBytes)) + if (!string.IsNullOrEmpty(numberOfBytes) + && long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes)) { - if (long.TryParse(numberOfBytes, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedBytes)) - { - return parsedBytes; - } + return parsedBytes; } } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 76b137c490..2e51370057 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -928,12 +928,12 @@ namespace MediaBrowser.Model.Dlna defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels); } else if (targetAudioChannels.HasValue - && audioStream.Channels.HasValue - && audioStream.Channels.Value <= targetAudioChannels.Value - && !string.IsNullOrEmpty(audioStream.Codec) - && targetAudioCodecs != null - && targetAudioCodecs.Length > 0 - && !Array.Exists(targetAudioCodecs, elem => string.Equals(audioStream.Codec, elem, StringComparison.OrdinalIgnoreCase))) + && audioStream.Channels.HasValue + && audioStream.Channels.Value <= targetAudioChannels.Value + && !string.IsNullOrEmpty(audioStream.Codec) + && targetAudioCodecs != null + && targetAudioCodecs.Length > 0 + && !Array.Exists(targetAudioCodecs, elem => string.Equals(audioStream.Codec, elem, StringComparison.OrdinalIgnoreCase))) { // Shift the bitrate if we're transcoding to a different audio codec. defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, audioStream.Channels.Value); From 20d6999d8c844f15aa7f9a2336bf201e81efb5e9 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 19 Nov 2020 23:04:44 +0800 Subject: [PATCH 0426/1930] minor changes --- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index b151f85e2d..5e35822bc2 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -39,7 +39,7 @@ namespace Jellyfin.Api.Controllers public class VideoHlsController : BaseJellyfinApiController { private const string DefaultEncoderPreset = "superfast"; - private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private const TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; private readonly EncodingHelper _encodingHelper; private readonly IDlnaManager _dlnaManager; From 2deda0437d32016a0c73158840c9c04bc729b261 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= <ferferga.fer@gmail.com> Date: Wed, 18 Nov 2020 10:54:21 +0100 Subject: [PATCH 0427/1930] Review suggestions --- Jellyfin.Api/Controllers/DynamicHlsController.cs | 2 +- Jellyfin.Api/Controllers/VideoHlsController.cs | 2 +- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 8 +++++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index bba5e972e8..1c2e4474cb 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1329,7 +1329,7 @@ namespace Jellyfin.Api.Controllers { var videoCodec = _encodingHelper.GetVideoEncoder(state, encodingOptions); - var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); // GetNumberOfThreads is static + var threads = EncodingHelper.GetNumberOfThreads(state, encodingOptions, videoCodec); // GetNumberOfThreads is static. if (state.BaseRequest.BreakOnNonKeyFrames) { diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 065fa786ee..df9d35b13f 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -359,7 +359,7 @@ namespace Jellyfin.Api.Controllers private string GetCommandLineArguments(string outputPath, StreamState state) { var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions); - var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); // GetNumberOfThreads is static + var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); // GetNumberOfThreads is static. var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 60c44cfcfc..0fb8a92381 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2329,15 +2329,17 @@ namespace MediaBrowser.Controller.MediaEncoding /// <summary> /// Gets the number of threads. /// </summary> - public static int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec) +#nullable enable + public static int GetNumberOfThreads(EncodingJobInfo? state, EncodingOptions encodingOptions, string? outputVideoCodec) { - if (outputVideoCodec != null && string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)) { // per docs: // -threads number of threads to use for encoding, can't be 0 [auto] with VP8 // (recommended value : number of real cores - 1) return Math.Max(Environment.ProcessorCount - 1, 1); } + var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount; // Automatic @@ -2352,7 +2354,7 @@ namespace MediaBrowser.Controller.MediaEncoding return threads; } - +#nullable disable public void TryStreamCopy(EncodingJobInfo state) { if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream)) From 452ca4565ff245a3dec670fbe5b9881df76d9434 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 15:39:00 +0000 Subject: [PATCH 0428/1930] reversing other PR --- Emby.Server.Implementations/ApplicationHost.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index cba9afb986..17b99c858f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -999,7 +999,7 @@ namespace Emby.Server.Implementations var versions = new List<LocalPlugin>(); if (!Directory.Exists(path)) { - // Plugin path doesn't exist, don't try to enumerate sub-folders. + // Plugin path doesn't exist, don't try to enumerate subfolders. return Enumerable.Empty<LocalPlugin>(); } @@ -1070,6 +1070,7 @@ namespace Emby.Server.Implementations if (!string.IsNullOrEmpty(lastName) && cleanup) { // Attempt a cleanup of old folders. + versions.RemoveAt(x); try { Logger.LogDebug("Deleting {Path}", versions[x].Path); @@ -1079,8 +1080,6 @@ namespace Emby.Server.Implementations { Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path); } - - versions.RemoveAt(x); } } From 14fc7e6408aa35c7a87470f3cd2fc87971f7c442 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 15:40:20 +0000 Subject: [PATCH 0429/1930] revert changes. --- .../Migrations/Routines/ReaddDefaultPluginRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs index db605c54ec..394f14d63c 100644 --- a/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs +++ b/Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs @@ -14,7 +14,7 @@ namespace Jellyfin.Server.Migrations.Routines private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo { Name = "Jellyfin Stable", - Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json", + Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" }; /// <summary> From b02ceea91b592224dd4166d4a72c3dd412f463dc Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 19 Nov 2020 23:56:04 +0800 Subject: [PATCH 0430/1930] increase bitrate to 20Mbps for 1440p transcoding --- MediaBrowser.Model/Dlna/ResolutionNormalizer.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs index 39439f1fa3..ef2d2d8ca9 100644 --- a/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs +++ b/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs @@ -15,6 +15,7 @@ namespace MediaBrowser.Model.Dlna new ResolutionConfiguration(720, 950000), new ResolutionConfiguration(1280, 2500000), new ResolutionConfiguration(1920, 4000000), + new ResolutionConfiguration(2560, 20000000), new ResolutionConfiguration(3840, 35000000) }; From 28f8cb6ea54d330341afd7a0f3f96dc50dfb91ec Mon Sep 17 00:00:00 2001 From: Oatavandi <oatavandi@gmail.com> Date: Thu, 19 Nov 2020 15:26:36 +0000 Subject: [PATCH 0431/1930] Translated using Weblate (Tamil) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ta/ --- Emby.Server.Implementations/Localization/Core/ta.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index e8cd23d5d1..5fcdb1f748 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -114,5 +114,8 @@ "UserStoppedPlayingItemWithValues": "{0} {2} இல் {1} முடித்துவிட்டது", "UserStartedPlayingItemWithValues": "{0} {2}இல் {1} ஐ இயக்குகிறது", "TaskCleanActivityLogDescription": "உள்ளமைக்கப்பட்ட வயதை விட பழைய செயல்பாட்டு பதிவு உள்ளீடுகளை நீக்குகிறது.", - "TaskCleanActivityLog": "செயல்பாட்டு பதிவை அழி" + "TaskCleanActivityLog": "செயல்பாட்டு பதிவை அழி", + "Undefined": "வரையறுக்கப்படாத", + "Forced": "கட்டாயப்படுத்தப்பட்டது", + "Default": "இயல்புநிலை" } From e71ab2afb1fda7521c61f860654fd94e3bd5e3e8 Mon Sep 17 00:00:00 2001 From: hoanghuy309 <hoanghuy309@gmail.com> Date: Thu, 19 Nov 2020 15:00:19 +0000 Subject: [PATCH 0432/1930] Translated using Weblate (Vietnamese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/vi/ --- Emby.Server.Implementations/Localization/Core/vi.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index ba58e4bebf..0549995c8c 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -114,5 +114,8 @@ "Application": "Ứng Dụng", "AppDeviceValues": "Ứng Dụng: {0}, Thiết Bị: {1}", "TaskCleanActivityLogDescription": "Xóa các mục nhật ký hoạt động cũ hơn độ tuổi đã cài đặt.", - "TaskCleanActivityLog": "Xóa Nhật Ký Hoạt Động" + "TaskCleanActivityLog": "Xóa Nhật Ký Hoạt Động", + "Undefined": "Không Xác Định", + "Forced": "Bắt Buộc", + "Default": "Mặc Định" } From d8a3448a97c1cd77117cfb27c167297937701f0a Mon Sep 17 00:00:00 2001 From: JoJoBot420 <jojobot420@gmail.com> Date: Thu, 19 Nov 2020 16:46:37 +0000 Subject: [PATCH 0433/1930] Translated using Weblate (Hebrew) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/he/ --- Emby.Server.Implementations/Localization/Core/he.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/he.json b/Emby.Server.Implementations/Localization/Core/he.json index f906d6e117..981e8a06ed 100644 --- a/Emby.Server.Implementations/Localization/Core/he.json +++ b/Emby.Server.Implementations/Localization/Core/he.json @@ -113,5 +113,10 @@ "TaskRefreshChannels": "רענן ערוץ", "TaskCleanTranscodeDescription": "מחק קבצי transcode שנוצרו מלפני יותר מיום.", "TaskCleanTranscode": "נקה תקיית Transcode", - "TaskUpdatePluginsDescription": "הורד והתקן עדכונים עבור תוספים שמוגדרים לעדכון אוטומטי." + "TaskUpdatePluginsDescription": "הורד והתקן עדכונים עבור תוספים שמוגדרים לעדכון אוטומטי.", + "TaskCleanActivityLogDescription": "מחק רשומת פעילות הישנה יותר מהגיל המוגדר.", + "TaskCleanActivityLog": "נקה רשומת פעילות", + "Undefined": "לא מוגדר", + "Forced": "כפוי", + "Default": "ברירת מחדל" } From c4d892642693b531cc6ecd219c9ad55fe75f6ddf Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 17:55:31 +0000 Subject: [PATCH 0434/1930] Fixed notification --- .../Json/Converters/JsonVersionConverter.cs | 20 +++++++++++++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 1 + 2 files changed, 21 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs new file mode 100644 index 0000000000..37e6f64e34 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs @@ -0,0 +1,20 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a Version object or value to/from JSON. + /// </summary> + public class JsonVersionConverter : JsonConverter<Version> + { + /// <inheritdoc /> + public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new Version(reader.GetString()); + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString()); + } +} diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 6605ae9624..c5050a21db 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -40,6 +40,7 @@ namespace MediaBrowser.Common.Json }; options.Converters.Add(new JsonGuidConverter()); + options.Converters.Add(new JsonVersionConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new JsonNullableStructConverterFactory()); From 9c3e484c0e711ec72bd7d3cea068fe750627e43b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 18:14:38 +0000 Subject: [PATCH 0435/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index e030416cac..6de536a163 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -266,7 +266,7 @@ namespace MediaBrowser.Common.Plugins XmlSerializer.SerializeToFile(config, ConfigurationFilePath); } } - + /// <summary> /// Saves the current configuration to the file system. /// </summary> From 084d21cade4746a1841174793d52e9573aaec5f4 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 19 Nov 2020 18:27:30 +0000 Subject: [PATCH 0436/1930] Updated contributors. --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a97a4c7416..edc8b08646 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -7,6 +7,7 @@ - [anthonylavado](https://github.com/anthonylavado) - [Artiume](https://github.com/Artiume) - [AThomsen](https://github.com/AThomsen) + - [barongreenback](https://github.com/BaronGreenback) - [barronpm](https://github.com/barronpm) - [bilde2910](https://github.com/bilde2910) - [bfayers](https://github.com/bfayers) From 3423bdf53a450fdcbc1e7b873c33d8006979e852 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Thu, 19 Nov 2020 15:51:58 -0500 Subject: [PATCH 0437/1930] Update Jellyfin.Api/Helpers/TranscodingJobHelper.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index da898d3d98..1d95a0ef9e 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,7 +553,7 @@ namespace Jellyfin.Api.Helpers : "FFmpeg.DirectStream-"; } - var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + state.Request.MediaSourceId + ".log"); + var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + state.Request.MediaSourceId + "_" + Guid.NewGuid().ToString("N") + ".log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); From fe8531f74e1152086673026840e244d66054acd4 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 19 Nov 2020 16:15:20 -0700 Subject: [PATCH 0438/1930] Fix live tv hls playback --- .../Controllers/HlsSegmentController.cs | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 3b75e8d431..f6359f8e4a 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -132,13 +132,25 @@ namespace Jellyfin.Api.Controllers var normalizedPlaylistId = playlistId; - var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath) - .FirstOrDefault(i => - string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) - && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1) - ?? throw new ResourceNotFoundException($"Provided path ({transcodeFolderPath}) is not valid."); + var filePaths = _fileSystem.GetFilePaths(transcodeFolderPath); + // Add . to start of segment container for future use. + segmentContainer = segmentContainer.Insert(0, "."); + string? playlistPath = null; + foreach (var path in filePaths) + { + var pathExtension = Path.GetExtension(path); + if ((string.Equals(pathExtension, segmentContainer, StringComparison.OrdinalIgnoreCase) + || string.Equals(pathExtension, ".m3u8", StringComparison.OrdinalIgnoreCase)) + && path.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1) + { + playlistPath = path; + break; + } + } - return GetFileResult(file, playlistPath); + return playlistPath == null + ? NotFound("Hls segment not found.") + : GetFileResult(file, playlistPath); } private ActionResult GetFileResult(string path, string playlistPath) From d58e435409afc013ff6d31c2d99c9b32078bbe96 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 19 Nov 2020 16:16:23 -0700 Subject: [PATCH 0439/1930] Add response code documentation --- Jellyfin.Api/Controllers/HlsSegmentController.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index f6359f8e4a..ccdbbb2970 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -112,11 +112,13 @@ namespace Jellyfin.Api.Controllers /// <param name="segmentId">The segment id.</param> /// <param name="segmentContainer">The segment container.</param> /// <response code="200">Hls video segment returned.</response> + /// <response code="404">Hls segment not found.</response> /// <returns>A <see cref="FileStreamResult"/> containing the video segment.</returns> // Can't require authentication just yet due to seeing some requests come from Chrome without full query string // [Authenticated] [HttpGet("Videos/{itemId}/hls/{playlistId}/{segmentId}.{segmentContainer}")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesVideoFile] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")] public ActionResult GetHlsVideoSegmentLegacy( From a46b70b169ef612185df7a4463f929c2c2122958 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Thu, 19 Nov 2020 19:23:04 -0500 Subject: [PATCH 0440/1930] Truncate GUID to 8 char --- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 1d95a0ef9e..6d46eff404 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,7 +553,7 @@ namespace Jellyfin.Api.Helpers : "FFmpeg.DirectStream-"; } - var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + state.Request.MediaSourceId + "_" + Guid.NewGuid().ToString("N") + ".log"); + var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + state.Request.MediaSourceId + "_" + Guid.NewGuid().ToString("N").Substring(0, 8) + ".log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); From f557a730bb8e5b2a0906ae0c523d83e917f82c90 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 19 Nov 2020 17:33:51 -0700 Subject: [PATCH 0441/1930] Write DateTimes in ISO8601 format for backwards compatibility. --- .../JsonDateTimeIso8601Converter.cs | 24 +++++++++++++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 1 + 2 files changed, 25 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs b/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs new file mode 100644 index 0000000000..63b344a9d6 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Returns an ISO8601 formatted datetime. + /// </summary> + /// <remarks> + /// Used for legacy compatibility. + /// </remarks> + public class JsonDateTimeIso8601Converter : JsonConverter<DateTime> + { + /// <inheritdoc /> + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => reader.GetDateTime(); + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString("O", CultureInfo.InvariantCulture)); + } +} diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 6605ae9624..9a94664acc 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -42,6 +42,7 @@ namespace MediaBrowser.Common.Json options.Converters.Add(new JsonGuidConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new JsonNullableStructConverterFactory()); + options.Converters.Add(new JsonDateTimeIso8601Converter()); return options; } From 6a751251e7b9fa3ab42f8bdc4cfc79e434031321 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Thu, 19 Nov 2020 19:45:26 -0500 Subject: [PATCH 0442/1930] Update Jellyfin.Api/Helpers/TranscodingJobHelper.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 6d46eff404..889518879e 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,7 +553,9 @@ namespace Jellyfin.Api.Helpers : "FFmpeg.DirectStream-"; } - var logFilePath = Path.Combine(_serverConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture) + "_" + state.Request.MediaSourceId + "_" + Guid.NewGuid().ToString("N").Substring(0, 8) + ".log"); + var logFilePath = Path.Combine( + _serverConfigurationManager.ApplicationPaths.LogDirectoryPath, + $"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); From 90e4066b12e3b39124f9f4efcb20a0e51499a038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Woli=C5=84ski?= <cierdek@gmail.com> Date: Thu, 19 Nov 2020 23:19:32 +0000 Subject: [PATCH 0443/1930] Translated using Weblate (Polish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pl/ --- Emby.Server.Implementations/Localization/Core/pl.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pl.json b/Emby.Server.Implementations/Localization/Core/pl.json index 003e591b37..e3da96a85a 100644 --- a/Emby.Server.Implementations/Localization/Core/pl.json +++ b/Emby.Server.Implementations/Localization/Core/pl.json @@ -113,5 +113,10 @@ "TasksChannelsCategory": "Kanały internetowe", "TasksApplicationCategory": "Aplikacja", "TasksLibraryCategory": "Biblioteka", - "TasksMaintenanceCategory": "Konserwacja" + "TasksMaintenanceCategory": "Konserwacja", + "TaskCleanActivityLogDescription": "Usuwa wpisy dziennika aktywności starsze niż skonfigurowany wiek.", + "TaskCleanActivityLog": "Czyść dziennik aktywności", + "Undefined": "Nieustalony", + "Forced": "Wymuszony", + "Default": "Domyślne" } From ca33ace3e97a85c01848db072708a4e2cf0b251a Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Fri, 20 Nov 2020 09:56:08 +0800 Subject: [PATCH 0444/1930] rename --- .../Controllers/DynamicHlsController.cs | 22 +++++++++---------- .../Controllers/VideoHlsController.cs | 8 +++---- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 90c2a6b58b..856c470c21 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -43,7 +43,7 @@ namespace Jellyfin.Api.Controllers public class DynamicHlsController : BaseJellyfinApiController { private const string DefaultEncoderPreset = "veryfast"; - private const TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls; private readonly ILibraryManager _libraryManager; private readonly IUserManager _userManager; @@ -276,7 +276,7 @@ namespace Jellyfin.Api.Controllers EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming }; - return await _dynamicHlsHelper.GetMasterHlsPlaylist(_transcodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false); + return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false); } /// <summary> @@ -443,7 +443,7 @@ namespace Jellyfin.Api.Controllers EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming }; - return await _dynamicHlsHelper.GetMasterHlsPlaylist(_transcodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false); + return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateStreaming).ConfigureAwait(false); } /// <summary> @@ -1133,7 +1133,7 @@ namespace Jellyfin.Api.Controllers _dlnaManager, _deviceManager, _transcodingJobHelper, - _transcodingJobType, + TranscodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); @@ -1218,7 +1218,7 @@ namespace Jellyfin.Api.Controllers _dlnaManager, _deviceManager, _transcodingJobHelper, - _transcodingJobType, + TranscodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); @@ -1232,7 +1232,7 @@ namespace Jellyfin.Api.Controllers if (System.IO.File.Exists(segmentPath)) { - job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); + job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); } @@ -1246,7 +1246,7 @@ namespace Jellyfin.Api.Controllers { if (System.IO.File.Exists(segmentPath)) { - job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); + job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); transcodingLock.Release(); released = true; _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath); @@ -1300,7 +1300,7 @@ namespace Jellyfin.Api.Controllers playlistPath, GetCommandLineArguments(playlistPath, state, true, segmentId), Request, - _transcodingJobType, + TranscodingJobType, cancellationTokenSource).ConfigureAwait(false); } catch @@ -1313,7 +1313,7 @@ namespace Jellyfin.Api.Controllers } else { - job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); + job = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); if (job?.TranscodingThrottler != null) { await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false); @@ -1330,7 +1330,7 @@ namespace Jellyfin.Api.Controllers } _logger.LogDebug("returning {0} [general case]", segmentPath); - job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); + job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); } @@ -1750,7 +1750,7 @@ namespace Jellyfin.Api.Controllers private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension) { - var job = _transcodingJobHelper.GetTranscodingJob(playlist, _transcodingJobType); + var job = _transcodingJobHelper.GetTranscodingJob(playlist, TranscodingJobType); if (job == null || job.HasExited) { diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 5e35822bc2..13f6fd37c8 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -39,7 +39,7 @@ namespace Jellyfin.Api.Controllers public class VideoHlsController : BaseJellyfinApiController { private const string DefaultEncoderPreset = "superfast"; - private const TranscodingJobType _transcodingJobType = TranscodingJobType.Hls; + private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls; private readonly EncodingHelper _encodingHelper; private readonly IDlnaManager _dlnaManager; @@ -292,7 +292,7 @@ namespace Jellyfin.Api.Controllers _dlnaManager, _deviceManager, _transcodingJobHelper, - _transcodingJobType, + TranscodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); @@ -315,7 +315,7 @@ namespace Jellyfin.Api.Controllers playlistPath, GetCommandLineArguments(playlistPath, state), Request, - _transcodingJobType, + TranscodingJobType, cancellationTokenSource) .ConfigureAwait(false); job.IsLiveOutput = true; @@ -339,7 +339,7 @@ namespace Jellyfin.Api.Controllers } } - job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, _transcodingJobType); + job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); if (job != null) { From d6585e7ff2e14234201e3fe6a75a5af2170c7804 Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Thu, 19 Nov 2020 18:42:41 -0800 Subject: [PATCH 0445/1930] Upgrade System.Threading.Tasks.Dataflow --- MediaBrowser.Controller/MediaBrowser.Controller.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index b2bce02a29..e99483dcc9 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -16,8 +16,8 @@ <ItemGroup> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.9" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.9" /> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> - <PackageReference Include="System.Threading.Tasks.Dataflow" Version="4.11.1" /> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> + <PackageReference Include="System.Threading.Tasks.Dataflow" Version="5.0.0" /> </ItemGroup> <ItemGroup> From 44ff7a48436123e7290c576e2ca97c400e9f0ffa Mon Sep 17 00:00:00 2001 From: Claus Vium <cvium@users.noreply.github.com> Date: Fri, 20 Nov 2020 08:06:28 +0100 Subject: [PATCH 0446/1930] Apply suggestions from code review --- .../Controllers/VideoHlsController.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 32 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index f1d6a5d450..2ac16de6b9 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -394,7 +394,7 @@ namespace Jellyfin.Api.Controllers } else { - _logger.LogError("Invalid HLS segment container: " + segmentFormat); + _logger.LogError("Invalid HLS segment container: {SegmentFormat}", segmentFormat); } var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128 diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 388c5089c1..9a6f1231f1 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -878,9 +878,9 @@ namespace MediaBrowser.Controller.MediaEncoding args += gopArg; } else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) + || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)) { args += " " + keyFrameArg; } @@ -977,7 +977,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv) - || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv) + || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv) { string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" }; @@ -993,7 +993,7 @@ namespace MediaBrowser.Controller.MediaEncoding param += " -look_ahead 0"; } else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc) - || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc) + || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc) { // following preset will be deprecated in ffmpeg 4.4, use p1~p7 instead. switch (encodingOptions.EncoderPreset) @@ -1026,7 +1026,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf) - || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf) + || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf) { switch (encodingOptions.EncoderPreset) { @@ -1147,10 +1147,10 @@ namespace MediaBrowser.Controller.MediaEncoding // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)) - && profile != null - && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) + || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)) + && profile != null + && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) { profile = "baseline"; } @@ -1199,7 +1199,7 @@ namespace MediaBrowser.Controller.MediaEncoding param += " -level " + level; } else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) { // level option may cause NVENC to fail. // NVENC cannot adjust the given level, just throw an error. @@ -1920,8 +1920,8 @@ namespace MediaBrowser.Controller.MediaEncoding // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1 - && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase) - || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase))) + && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase))) { /* [base]: SW scaling video to OutputSize @@ -2017,9 +2017,9 @@ namespace MediaBrowser.Controller.MediaEncoding requestedMaxHeight); if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) - || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) + || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) && width.HasValue && height.HasValue) { From 47f3bb33f952ff9f8f8a8307bb3bd92636f156bc Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 09:03:11 +0000 Subject: [PATCH 0447/1930] Update BasePlugin.cs --- MediaBrowser.Common/Plugins/BasePlugin.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 6de536a163..084e91d500 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -272,12 +272,7 @@ namespace MediaBrowser.Common.Plugins /// </summary> public virtual void SaveConfiguration() { - lock (_configurationSaveLock) - { - _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); - - XmlSerializer.SerializeToFile(Configuration, ConfigurationFilePath); - } + SaveConfiguration(Configuration); } /// <inheritdoc /> From d63053461565545a0b6421a5fe98e02278ccb1d2 Mon Sep 17 00:00:00 2001 From: Decoy7 <mikemike19991@gmail.com> Date: Fri, 20 Nov 2020 12:39:08 +0000 Subject: [PATCH 0448/1930] Translated using Weblate (Greek) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/el/ --- Emby.Server.Implementations/Localization/Core/el.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/el.json b/Emby.Server.Implementations/Localization/Core/el.json index c45cc11cb8..dcf3311cd2 100644 --- a/Emby.Server.Implementations/Localization/Core/el.json +++ b/Emby.Server.Implementations/Localization/Core/el.json @@ -113,5 +113,10 @@ "TaskCleanTranscode": "Καθαρισμός Kαταλόγου Διακωδικοποιητή", "TaskUpdatePluginsDescription": "Κατεβάζει και εγκαθιστά ενημερώσεις για τις προσθήκες που έχουν ρυθμιστεί για αυτόματη ενημέρωση.", "TaskUpdatePlugins": "Ενημέρωση Προσθηκών", - "TaskRefreshPeopleDescription": "Ενημερώνει μεταδεδομένα για ηθοποιούς και σκηνοθέτες στην βιβλιοθήκη των πολυμέσων σας." + "TaskRefreshPeopleDescription": "Ενημερώνει μεταδεδομένα για ηθοποιούς και σκηνοθέτες στην βιβλιοθήκη των πολυμέσων σας.", + "TaskCleanActivityLogDescription": "Διαγράφει καταχωρήσεις απο το αρχείο καταγραφής δραστηριοτήτων παλαιότερες από την ηλικία που έχει διαμορφωθεί.", + "TaskCleanActivityLog": "Καθαρό Αρχείο Καταγραφής Δραστηριοτήτων", + "Undefined": "Απροσδιόριστο", + "Forced": "Εξαναγκασμένο", + "Default": "Προεπιλογή" } From 32b92641fbb068a89aeb47956e6ce0e98b1d3918 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 14:03:27 +0000 Subject: [PATCH 0449/1930] Get version info the manifest. --- .../ApplicationHost.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 5d47d1e401..74e472be69 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -181,6 +181,8 @@ namespace Emby.Server.Implementations private IPlugin[] _plugins; + private IEnumerable<LocalPlugin> _pluginsManifests; + /// <summary> /// Gets the plugins. /// </summary> @@ -772,6 +774,23 @@ namespace Emby.Server.Implementations foreach (var plugin in Plugins) { + if (plugin is IPluginAssembly assemblyPlugin) + { + // Ensure the version number matches the Plugin Manifest information. + foreach (var item in _pluginsManifests) + { + if (item.Path.Equals(plugin.AssemblyFilePath, StringComparison.OrdinalIgnoreCase)) + { + // Update version number to that of the manifest. + assemblyPlugin.SetAttributes( + plugin.AssemblyFilePath, + Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(plugin.AssemblyFilePath)), + item.Version); + break; + } + } + } + pluginBuilder.Append(plugin.Name) .Append(' ') .Append(plugin.Version) @@ -1093,7 +1112,8 @@ namespace Emby.Server.Implementations { if (Directory.Exists(ApplicationPaths.PluginsPath)) { - foreach (var plugin in GetLocalPlugins(ApplicationPaths.PluginsPath)) + _pluginsManifests = GetLocalPlugins(ApplicationPaths.PluginsPath); + foreach (var plugin in _pluginsManifests) { foreach (var file in plugin.DllFiles) { From 2f9e549c358f713df3650e3d99b13455153409a5 Mon Sep 17 00:00:00 2001 From: Csaba <csab0825@gmail.com> Date: Fri, 20 Nov 2020 14:09:37 +0000 Subject: [PATCH 0450/1930] Translated using Weblate (Hungarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hu/ --- Emby.Server.Implementations/Localization/Core/hu.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index 804dabe57a..e5707e78c9 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -115,5 +115,8 @@ "TaskRefreshChannels": "Csatornák frissítése", "TaskCleanTranscodeDescription": "Törli az egy napnál régebbi átkódolási fájlokat.", "TaskCleanActivityLogDescription": "A beállítottnál korábbi bejegyzések törlése a tevékenységnaplóból.", - "TaskCleanActivityLog": "Tevékenységnapló törlése" + "TaskCleanActivityLog": "Tevékenységnapló törlése", + "Undefined": "Meghatározatlan", + "Forced": "Kényszerített", + "Default": "Alapértelmezett" } From d6b0a939f73e30192d39f25bb745f1893606f7fb Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 14:14:00 +0000 Subject: [PATCH 0451/1930] fixed --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 74e472be69..073baf6c0f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -779,7 +779,7 @@ namespace Emby.Server.Implementations // Ensure the version number matches the Plugin Manifest information. foreach (var item in _pluginsManifests) { - if (item.Path.Equals(plugin.AssemblyFilePath, StringComparison.OrdinalIgnoreCase)) + if (Path.GetDirectoryName(plugin.AssemblyFilePath).Equals(item.Path, StringComparison.OrdinalIgnoreCase)) { // Update version number to that of the manifest. assemblyPlugin.SetAttributes( From 182a68f3dd14f0a1af2520b01ffdb3712d9dfe56 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 07:50:04 -0700 Subject: [PATCH 0452/1930] Set sdk version to 5.0 --- .ci/azure-pipelines-test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index 4ceda978a6..a47d890f28 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -30,11 +30,11 @@ jobs: # This is required for the SonarCloud analyzer - task: UseDotNet@2 - displayName: "Install .NET Core SDK 2.1" + displayName: "Install .NET SDK 5.0" condition: eq(variables['ImageName'], 'ubuntu-latest') inputs: packageType: sdk - version: '2.1.805' + version: '5.0' - task: UseDotNet@2 displayName: "Update DotNet" From f727f5dd72b4ce382b34f8fd4c1a6adcd6728cc3 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 07:52:10 -0700 Subject: [PATCH 0453/1930] Use sdk 5.x --- .ci/azure-pipelines-test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index a47d890f28..36152c82a4 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -30,11 +30,11 @@ jobs: # This is required for the SonarCloud analyzer - task: UseDotNet@2 - displayName: "Install .NET SDK 5.0" + displayName: "Install .NET SDK 5.x" condition: eq(variables['ImageName'], 'ubuntu-latest') inputs: packageType: sdk - version: '5.0' + version: '5.x' - task: UseDotNet@2 displayName: "Update DotNet" From bf66f57069e14de2954d4a1c799bb16232129821 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 08:12:38 -0700 Subject: [PATCH 0454/1930] Set DeleteTranscodeFileTask to trigger every 24h --- .../Tasks/DeleteTranscodeFileTask.cs | 62 ++++++++++++------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs index 26ef193542..b13fc7fc68 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteTranscodeFileTask.cs @@ -5,10 +5,10 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Globalization; namespace Emby.Server.Implementations.ScheduledTasks.Tasks { @@ -23,8 +23,12 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks private readonly ILocalizationManager _localization; /// <summary> - /// Initializes a new instance of the <see cref="DeleteTranscodeFileTask" /> class. + /// Initializes a new instance of the <see cref="DeleteTranscodeFileTask"/> class. /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger{DeleteTranscodeFileTask}"/> interface.</param> + /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> + /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param> + /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param> public DeleteTranscodeFileTask( ILogger<DeleteTranscodeFileTask> logger, IFileSystem fileSystem, @@ -37,11 +41,42 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks _localization = localization; } + /// <inheritdoc /> + public string Name => _localization.GetLocalizedString("TaskCleanTranscode"); + + /// <inheritdoc /> + public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription"); + + /// <inheritdoc /> + public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory"); + + /// <inheritdoc /> + public string Key => "DeleteTranscodeFiles"; + + /// <inheritdoc /> + public bool IsHidden => false; + + /// <inheritdoc /> + public bool IsEnabled => true; + + /// <inheritdoc /> + public bool IsLogged => true; + /// <summary> /// Creates the triggers that define when the task will run. /// </summary> /// <returns>IEnumerable{BaseTaskTrigger}.</returns> - public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() => new List<TaskTriggerInfo>(); + public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() + { + return new[] + { + new TaskTriggerInfo + { + Type = TaskTriggerInfo.TriggerInterval, + IntervalTicks = TimeSpan.FromHours(24).Ticks + } + }; + } /// <summary> /// Returns the task to be executed. @@ -131,26 +166,5 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks _logger.LogError(ex, "Error deleting file {path}", path); } } - - /// <inheritdoc /> - public string Name => _localization.GetLocalizedString("TaskCleanTranscode"); - - /// <inheritdoc /> - public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription"); - - /// <inheritdoc /> - public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory"); - - /// <inheritdoc /> - public string Key => "DeleteTranscodeFiles"; - - /// <inheritdoc /> - public bool IsHidden => false; - - /// <inheritdoc /> - public bool IsEnabled => true; - - /// <inheritdoc /> - public bool IsLogged => true; } } From b879fb615ebd5b922f3914021a4cdf892da12365 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 15:19:46 +0000 Subject: [PATCH 0455/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 073baf6c0f..2d9ef7e40d 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -181,7 +181,7 @@ namespace Emby.Server.Implementations private IPlugin[] _plugins; - private IEnumerable<LocalPlugin> _pluginsManifests; + private IReadOnlyList<LocalPlugin> _pluginsManifests; /// <summary> /// Gets the plugins. From 2f75f84b6f7d21e9337ee597f8367266a13a27a6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 10:22:40 -0700 Subject: [PATCH 0456/1930] Fix marking item as played --- .../Controllers/PlaystateController.cs | 3 +- .../ModelBinders/LegacyDateTimeModelBinder.cs | 49 +++++++++++++++++++ .../TypeConverters/DateTimeTypeConverter.cs | 44 ----------------- Jellyfin.Server/Startup.cs | 6 --- 4 files changed, 51 insertions(+), 51 deletions(-) create mode 100644 Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs delete mode 100644 Jellyfin.Api/TypeConverters/DateTimeTypeConverter.cs diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs index 5c15e9a0d7..6bdfe13317 100644 --- a/Jellyfin.Api/Controllers/PlaystateController.cs +++ b/Jellyfin.Api/Controllers/PlaystateController.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; @@ -74,7 +75,7 @@ namespace Jellyfin.Api.Controllers public ActionResult<UserItemDataDto> MarkPlayedItem( [FromRoute, Required] Guid userId, [FromRoute, Required] Guid itemId, - [FromQuery] DateTime? datePlayed) + [FromQuery, ModelBinder(typeof(LegacyDateTimeModelBinder))] DateTime? datePlayed) { var user = _userManager.GetUserById(userId); var session = RequestHelpers.GetSession(_sessionManager, _authContext, Request); diff --git a/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs b/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs new file mode 100644 index 0000000000..e1cb725f3e --- /dev/null +++ b/Jellyfin.Api/ModelBinders/LegacyDateTimeModelBinder.cs @@ -0,0 +1,49 @@ +using System; +using System.Globalization; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.ModelBinders +{ + /// <summary> + /// DateTime model binder. + /// </summary> + public class LegacyDateTimeModelBinder : IModelBinder + { + // Borrowed from the DateTimeModelBinderProvider + private const DateTimeStyles SupportedStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces; + private readonly DateTimeModelBinder _defaultModelBinder; + + /// <summary> + /// Initializes a new instance of the <see cref="LegacyDateTimeModelBinder"/> class. + /// </summary> + /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> + public LegacyDateTimeModelBinder(ILoggerFactory loggerFactory) + { + _defaultModelBinder = new DateTimeModelBinder(SupportedStyles, loggerFactory); + } + + /// <inheritdoc /> + public Task BindModelAsync(ModelBindingContext bindingContext) + { + var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + if (valueProviderResult.Values.Count == 1) + { + var dateTimeString = valueProviderResult.FirstValue; + // Mark Played Item. + if (DateTime.TryParseExact(dateTimeString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime)) + { + bindingContext.Result = ModelBindingResult.Success(dateTime); + } + else + { + return _defaultModelBinder.BindModelAsync(bindingContext); + } + } + + return Task.CompletedTask; + } + } +} diff --git a/Jellyfin.Api/TypeConverters/DateTimeTypeConverter.cs b/Jellyfin.Api/TypeConverters/DateTimeTypeConverter.cs deleted file mode 100644 index 315b473293..0000000000 --- a/Jellyfin.Api/TypeConverters/DateTimeTypeConverter.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.ComponentModel; -using System.Globalization; - -namespace Jellyfin.Api.TypeConverters -{ - /// <summary> - /// Custom datetime parser. - /// </summary> - public class DateTimeTypeConverter : TypeConverter - { - /// <inheritdoc /> - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); - } - - /// <inheritdoc /> - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - if (value is string dateString) - { - // Mark Played Item. - if (DateTime.TryParseExact(dateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime)) - { - return dateTime; - } - - // Get Activity Logs. - if (DateTime.TryParse(dateString, null, DateTimeStyles.RoundtripKind, out dateTime)) - { - return dateTime; - } - } - - return base.ConvertFrom(context, culture, value); - } - } -} diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 62ffe174cd..2a62339a63 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -1,8 +1,5 @@ -using System; -using System.ComponentModel; using System.Net.Http.Headers; using System.Net.Mime; -using Jellyfin.Api.TypeConverters; using Jellyfin.Server.Extensions; using Jellyfin.Server.Implementations; using Jellyfin.Server.Middleware; @@ -164,9 +161,6 @@ namespace Jellyfin.Server endpoints.MapHealthChecks("/health"); }); }); - - // Add type descriptor for legacy datetime parsing. - TypeDescriptor.AddAttributes(typeof(DateTime?), new TypeConverterAttribute(typeof(DateTimeTypeConverter))); } } } From b3d322f79fb81cc8c8dfabcfd4dc12ba58489eeb Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 10:50:11 -0700 Subject: [PATCH 0457/1930] Fix build after merge --- Jellyfin.Api/Controllers/ItemsController.cs | 48 ++++++++++----------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 7194bf2a93..b0979fbcf7 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -595,7 +595,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasParentalRating, [FromQuery] bool? isHd, [FromQuery] bool? is4K, - [FromQuery] string? locationTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes, [FromQuery] bool? isMissing, [FromQuery] bool? isUnaired, @@ -609,7 +609,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? hasImdbId, [FromQuery] bool? hasTmdbId, [FromQuery] bool? hasTvdbId, - [FromQuery] string? excludeItemIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] bool? recursive, @@ -617,34 +617,34 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? sortOrder, [FromQuery] string? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? excludeItemTypes, - [FromQuery] string? includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, - [FromQuery] string? mediaTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, [FromQuery] string? sortBy, [FromQuery] bool? isPlayed, - [FromQuery] string? genres, - [FromQuery] string? officialRatings, - [FromQuery] string? tags, - [FromQuery] string? years, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] string? person, - [FromQuery] string? personIds, - [FromQuery] string? personTypes, - [FromQuery] string? studios, - [FromQuery] string? artists, - [FromQuery] string? excludeArtistIds, - [FromQuery] string? artistIds, - [FromQuery] string? albumArtistIds, - [FromQuery] string? contributingArtistIds, - [FromQuery] string? albums, - [FromQuery] string? albumIds, - [FromQuery] string? ids, - [FromQuery] string? videoTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds, + [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes, [FromQuery] string? minOfficialRating, [FromQuery] bool? isLocked, [FromQuery] bool? isPlaceHolder, @@ -655,12 +655,12 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, [FromQuery] bool? is3D, - [FromQuery] string? seriesStatus, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus, [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, - [FromQuery] string? studioIds, - [FromQuery] string? genreIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { From f512d5167dd317b5be24b5deb7ec7059a3d588ac Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 11:27:37 -0700 Subject: [PATCH 0458/1930] Remove broken CleanDateTimes regex --- Emby.Naming/Common/NamingOptions.cs | 4 +--- .../Video/VideoResolverTests.cs | 12 +++++------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 316ed9f891..035d1b2280 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -132,9 +132,7 @@ namespace Emby.Naming.Common CleanDateTimes = new[] { @"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*", - @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*", - @"(.+\w)\W+\p{Ps}(19[0-9]{2}|20[0-9]{2})\p{Pe}", // Prefer year enclosed in parenthesis (){}[] - @"(.+\w)\W+(19[0-9]{2}|20[0-9]{2})(\W|$)", // Secondary year surrounded by non-word chars + @"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*" }; CleanStrings = new[] diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index 7d105b084e..b6447a7a64 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -147,13 +147,11 @@ namespace Jellyfin.Naming.Tests.Video }; yield return new object[] { - new VideoFileInfo() - { - Path = @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", - Container = "mp4", - Name = "Rain Man", - Year = 1988, - } + new VideoFileInfo( + path: @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", + container: "mp4", + name: "Rain Man", + year: 1988) }; } From b0be434ba66fb600244d8574ddc84e7d94b1342a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 20 Nov 2020 11:28:45 -0700 Subject: [PATCH 0459/1930] Revert unused change --- Emby.Naming/Video/CleanDateTimeParser.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Emby.Naming/Video/CleanDateTimeParser.cs b/Emby.Naming/Video/CleanDateTimeParser.cs index f2b538e6c7..0ee633dcc6 100644 --- a/Emby.Naming/Video/CleanDateTimeParser.cs +++ b/Emby.Naming/Video/CleanDateTimeParser.cs @@ -40,6 +40,7 @@ namespace Emby.Naming.Video var match = expression.Match(name); if (match.Success + && match.Groups.Count == 5 && match.Groups[1].Success && match.Groups[2].Success && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)) From 972ed3ccfe3b669ca3e3d53aa68b12ddabc9a613 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 18:56:36 +0000 Subject: [PATCH 0460/1930] fix. --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 2d9ef7e40d..d0dcdab757 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1112,7 +1112,7 @@ namespace Emby.Server.Implementations { if (Directory.Exists(ApplicationPaths.PluginsPath)) { - _pluginsManifests = GetLocalPlugins(ApplicationPaths.PluginsPath); + _pluginsManifests = GetLocalPlugins(ApplicationPaths.PluginsPath).ToList(); foreach (var plugin in _pluginsManifests) { foreach (var file in plugin.DllFiles) From eed1a40b1935e00e04f6b27c7d307bf110b83b31 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 20 Nov 2020 19:18:18 +0000 Subject: [PATCH 0461/1930] Fixed tests --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d0dcdab757..cf7751c369 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -774,7 +774,7 @@ namespace Emby.Server.Implementations foreach (var plugin in Plugins) { - if (plugin is IPluginAssembly assemblyPlugin) + if (_pluginsManifests != null && plugin is IPluginAssembly assemblyPlugin) { // Ensure the version number matches the Plugin Manifest information. foreach (var item in _pluginsManifests) From 9a9b2bfb2ea6a39d1a46f16355b42d930b307177 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 00:34:09 +0000 Subject: [PATCH 0462/1930] Updated to the latest --- .../Configuration/NetworkConfiguration.cs | 8 +- Jellyfin.Networking/Manager/NetworkManager.cs | 194 ++++++++++-------- MediaBrowser.Common/Net/IPHost.cs | 29 +-- MediaBrowser.Common/Net/IPNetAddress.cs | 8 +- MediaBrowser.Common/Net/IPObject.cs | 31 ++- 5 files changed, 149 insertions(+), 121 deletions(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index e710eb3c76..df420f48a2 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -99,8 +99,7 @@ namespace Jellyfin.Networking.Configuration public bool UPnPCreateHttpPortMap { get; set; } /// <summary> - /// Gets or sets the UDPPortRange - /// Gets or sets client udp port range. + /// Gets or sets the UDPPortRange. /// </summary> public string UDPPortRange { get; set; } = string.Empty; @@ -115,8 +114,8 @@ namespace Jellyfin.Networking.Configuration public bool EnableIPV4 { get; set; } = true; /// <summary> - /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. - /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. + /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect. /// </summary> public bool EnableSSDPTracing { get; set; } @@ -143,7 +142,6 @@ namespace Jellyfin.Networking.Configuration public bool IgnoreVirtualInterfaces { get; set; } = true; /// <summary> - /// Gets or sets the VirtualInterfaceNames /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>. /// </summary> public string VirtualInterfaceNames { get; set; } = "vEthernet*"; diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 00711f1620..515ae669a1 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -182,7 +182,7 @@ namespace Jellyfin.Networking.Manager public IReadOnlyCollection<PhysicalAddress> GetMacAddresses() { // Populated in construction - so always has values. - return _macAddresses.AsReadOnly(); + return _macAddresses; } /// <inheritdoc/> @@ -378,7 +378,7 @@ namespace Jellyfin.Networking.Manager } } - _logger.LogDebug("GetBindInterface: Source: {0}, External: {1}:", haveSource, isExternal); + _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal); // No preference given, so move on to bind addresses. if (MatchesBindInterface(source, isExternal, out string result)) @@ -408,20 +408,20 @@ namespace Jellyfin.Networking.Manager if (intf.Contains(source)) { result = FormatIP6String(intf.Address); - _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); return result; } } } result = FormatIP6String(interfaces.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); return result; } // There isn't any others, so we'll use the loopback. result = IsIP6Enabled ? "::" : "127.0.0.1"; - _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result); + _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); return result; } @@ -552,7 +552,7 @@ namespace Jellyfin.Networking.Manager { result = new Collection<IPObject>(); - _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) @@ -575,7 +575,7 @@ namespace Jellyfin.Networking.Manager /// Reloads all settings and re-initialises the instance. /// </summary> /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> - public void UpdateSettings(NetworkConfiguration configuration) + public void UpdateSettings(object configuration) { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); @@ -740,7 +740,7 @@ namespace Jellyfin.Networking.Manager // Null check required here for automated testing. if (IsInterface(token, out int index)) { - _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) @@ -780,7 +780,7 @@ namespace Jellyfin.Networking.Manager } else { - _logger.LogDebug("Invalid or unknown network {0}.", token); + _logger.LogDebug("Invalid or unknown network {Token}.", token); } } @@ -867,7 +867,7 @@ namespace Jellyfin.Networking.Manager var parts = entry.Split('='); if (parts.Length != 2) { - _logger.LogError("Unable to parse bind override. {0}", entry); + _logger.LogError("Unable to parse bind override: {Entry}", entry); } else { @@ -893,7 +893,7 @@ namespace Jellyfin.Networking.Manager } else { - _logger.LogError("Unable to parse bind ip address. {0}", parts[1]); + _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); } } } @@ -905,30 +905,35 @@ namespace Jellyfin.Networking.Manager /// </summary> private void InitialiseBind(NetworkConfiguration config) { - string[] lanAddresses = config.LocalNetworkAddresses; - - // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 - - if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) + lock (_intLock) { - lanAddresses = lanAddresses[0].Split(','); + string[] lanAddresses = config.LocalNetworkAddresses; + + // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 + + if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) + { + lanAddresses = lanAddresses[0].Split(','); + } + + // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334 + + // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. + if (config.IgnoreVirtualInterfaces) + { + var virtualInterfaceNames = config.VirtualInterfaceNames.Split(','); + var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; + Array.Copy(lanAddresses, newList, lanAddresses.Length); + Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); + lanAddresses = newList; + } + + // Read and parse bind addresses and exclusions, removing ones that don't exist. + _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); + _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); + _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); + _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } - - // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334 - - // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. - if (config.IgnoreVirtualInterfaces) - { - var newList = lanAddresses.ToList(); - newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList()); - lanAddresses = newList.ToArray(); - } - - // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); - _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } /// <summary> @@ -936,7 +941,10 @@ namespace Jellyfin.Networking.Manager /// </summary> private void InitialiseRemote(NetworkConfiguration config) { - RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); + lock (_intLock) + { + RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); + } } /// <summary> @@ -959,7 +967,8 @@ namespace Jellyfin.Networking.Manager // If no LAN addresses are specified - all private subnets are deemed to be the LAN _usingPrivateAddresses = _lanSubnets.Count == 0; - // NOTE: The order of the commands in this statement matters. + // NOTE: The order of the commands generating the collection in this statement matters. + // Altering the order will cause the collections to be created incorrectly. if (_usingPrivateAddresses) { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); @@ -1020,6 +1029,7 @@ namespace Jellyfin.Networking.Manager _interfaceNames.Clear(); _interfaceAddresses.Clear(); + _macAddresses.Clear(); try { @@ -1051,7 +1061,7 @@ namespace Jellyfin.Networking.Manager }; int tag = nw.Tag; - if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback()) + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) { // -ve Tags signify the interface has a gateway. nw.Tag *= -1; @@ -1072,7 +1082,7 @@ namespace Jellyfin.Networking.Manager }; int tag = nw.Tag; - if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback()) + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) { // -ve Tags signify the interface has a gateway. nw.Tag *= -1; @@ -1087,9 +1097,10 @@ namespace Jellyfin.Networking.Manager } } #pragma warning disable CA1031 // Do not catch general exception types - catch + catch (Exception ex) { // Ignore error, and attempt to continue. + _logger.LogError(ex, "Error encountered parsing interfaces."); } #pragma warning restore CA1031 // Do not catch general exception types } @@ -1100,8 +1111,7 @@ namespace Jellyfin.Networking.Manager // If for some reason we don't have an interface info, resolve our DNS name. if (_interfaceAddresses.Count == 0) { - _logger.LogWarning("No interfaces information available. Using loopback."); - + _logger.LogError("No interfaces information available. Resolving DNS name."); IPHost host = new IPHost(Dns.GetHostName()); foreach (var a in host.GetAddresses()) { @@ -1110,7 +1120,7 @@ namespace Jellyfin.Networking.Manager if (_interfaceAddresses.Count == 0) { - _logger.LogError("No interfaces information available. Resolving DNS name."); + _logger.LogWarning("No interfaces information available. Using loopback."); // Last ditch attempt - use loopback address. _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); if (IsIP6Enabled) @@ -1131,11 +1141,11 @@ namespace Jellyfin.Networking.Manager /// Attempts to match the source against a user defined bind interface. /// </summary> /// <param name="source">IP source address to use.</param> - /// <param name="isExternal">True if the source is in the external subnet.</param> + /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> /// <param name="bindPreference">The published server url that matches the source address.</param> /// <param name="port">The resultant port, if one exists.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> - private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port) { bindPreference = string.Empty; port = null; @@ -1144,12 +1154,12 @@ namespace Jellyfin.Networking.Manager foreach (var addr in _publishedServerUrls) { // Remaining. Match anything. - if (addr.Key.Equals(IPAddress.Broadcast)) + if (addr.Key.Address.Equals(IPAddress.Broadcast)) { bindPreference = addr.Value; break; } - else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal) + else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) { // External. bindPreference = addr.Value; @@ -1163,38 +1173,38 @@ namespace Jellyfin.Networking.Manager } } - if (!string.IsNullOrEmpty(bindPreference)) + if (string.IsNullOrEmpty(bindPreference)) { - // Has it got a port defined? - var parts = bindPreference.Split(':'); - if (parts.Length > 1) - { - if (int.TryParse(parts[1], out int p)) - { - bindPreference = parts[0]; - port = p; - } - } - - return true; + return false; } - return false; + // Has it got a port defined? + var parts = bindPreference.Split(':'); + if (parts.Length > 1) + { + if (int.TryParse(parts[1], out int p)) + { + bindPreference = parts[0]; + port = p; + } + } + + return true; } /// <summary> /// Attempts to match the source against a user defined bind interface. /// </summary> /// <param name="source">IP source address to use.</param> - /// <param name="isExternal">True if the source is in the external subnet.</param> + /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> /// <param name="result">The result, if a match is found.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> - private bool MatchesBindInterface(IPObject source, bool isExternal, out string result) + private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) { result = string.Empty; - var nc = _bindAddresses.Exclude(_bindExclusions); + var addresses = _bindAddresses.Exclude(_bindExclusions); - int count = nc.Count; + int count = addresses.Count; if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. @@ -1205,26 +1215,34 @@ namespace Jellyfin.Networking.Manager { // Check to see if any of the bind interfaces are in the same subnet. - Collection<IPObject> bindResult; IPAddress? defaultGateway = null; - IPAddress? bindAddress; + IPAddress? bindAddress = null; - if (isExternal) + if (isInExternalSubnet) { // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - bindResult = CreateCollection(nc - .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag)); - defaultGateway = bindResult.FirstOrDefault()?.Address; - bindAddress = bindResult - .Where(p => p.Contains(source)) - .OrderBy(p => p.Tag) - .FirstOrDefault()?.Address; + foreach (var addr in addresses.OrderBy(p => p.Tag)) + { + if (defaultGateway == null && !IsInLocalNetwork(addr)) + { + defaultGateway = addr.Address; + } + + if (bindAddress == null && addr.Contains(source)) + { + bindAddress = addr.Address; + } + + if (defaultGateway != null && bindAddress != null) + { + break; + } + } } else { // Look for the best internal address. - bindAddress = nc + bindAddress = addresses .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) .OrderBy(p => p.Tag) .FirstOrDefault()?.Address; @@ -1233,23 +1251,23 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = FormatIP6String(bindAddress); - _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result); return true; } - if (isExternal && defaultGateway != null) + if (isInExternalSubnet && defaultGateway != null) { result = FormatIP6String(defaultGateway); - _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); return true; } - result = FormatIP6String(nc.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", source, result); + result = FormatIP6String(addresses[0].Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); - if (isExternal) + if (isInExternalSubnet) { - _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source); + _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source); } return true; @@ -1268,12 +1286,12 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = CreateCollection(_interfaceAddresses + var extResult = _interfaceAddresses .Exclude(_bindExclusions) .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag)); + .OrderBy(p => p.Tag); - if (extResult.Count > 0) + if (extResult.Any()) { // Does the request originate in one of the interface subnets? // (For systems with multiple internal network cards, and multiple subnets) @@ -1282,19 +1300,19 @@ namespace Jellyfin.Networking.Manager if (!IsInLocalNetwork(intf) && intf.Contains(source)) { result = FormatIP6String(intf.Address); - _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); return true; } } result = FormatIP6String(extResult.First().Address); - _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", source, result); + _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); return true; } // Have to return something, so return an internal address - _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source); + _logger.LogWarning("{Source}: External request received, however, no WAN interface found.", source); return false; } } diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index f9e1568efc..4cede9ab16 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -1,5 +1,6 @@ #nullable enable using System; +using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Sockets; @@ -13,6 +14,11 @@ namespace MediaBrowser.Common.Net /// </summary> public class IPHost : IPObject { + /// <summary> + /// Gets or sets timeout value before resolve required, in minutes. + /// </summary> + public const int Timeout = 30; + /// <summary> /// Represents an IPHost that has no value. /// </summary> @@ -21,7 +27,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Time when last resolved in ticks. /// </summary> - private long _lastResolved; + private DateTime? _lastResolved = null; /// <summary> /// Gets the IP Addresses, attempting to resolve the name, if there are none. @@ -83,15 +89,9 @@ namespace MediaBrowser.Common.Net { // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length, // which is automatically determined by it's IP type. Anything else is meaningless. - throw new NotImplementedException("The prefix length on a host cannot be set."); } } - /// <summary> - /// Gets or sets timeout value before resolve required, in minutes. - /// </summary> - public byte Timeout { get; set; } = 30; - /// <summary> /// Gets a value indicating whether the address has a value. /// </summary> @@ -395,15 +395,15 @@ namespace MediaBrowser.Common.Net private bool ResolveHost() { // When was the last time we resolved? - if (_lastResolved == 0) + if (_lastResolved == null) { - _lastResolved = DateTime.UtcNow.Ticks; + _lastResolved = DateTime.UtcNow; } - // If we haven't resolved before, or out timer has run out... - if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.UtcNow.Ticks - _lastResolved).TotalMinutes > Timeout)) + // If we haven't resolved before, or our timer has run out... + if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved?.AddMinutes(Timeout))) { - _lastResolved = DateTime.UtcNow.Ticks; + _lastResolved = DateTime.UtcNow; ResolveHostInternal().GetAwaiter().GetResult(); Resolved = true; } @@ -433,9 +433,10 @@ namespace MediaBrowser.Common.Net IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false); _addresses = ip.AddressList; } - catch (SocketException) + catch (SocketException ex) { - // Ignore socket errors, as the result value will just be an empty array. + // Log and then ignore socket errors, as the result value will just be an empty array. + Debug.WriteLine("GetHostEntryAsync failed with {Message}.", ex.Message); } } } diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index 0d28c35cb8..a6f5fe4b37 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -18,17 +18,17 @@ namespace MediaBrowser.Common.Net /// <summary> /// IPv4 multicast address. /// </summary> - public static readonly IPAddress MulticastIPv4 = IPAddress.Parse("239.255.255.250"); + public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250"); /// <summary> /// IPv6 local link multicast address. /// </summary> - public static readonly IPAddress MulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); + public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); /// <summary> /// IPv6 site local multicast address. /// </summary> - public static readonly IPAddress MulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); + public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); /// <summary> /// IP4Loopback address host. @@ -235,7 +235,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns a textual representation of this object. /// </summary> - /// <param name="shortVersion">Set to true, if the subnet is to be included as part of the address.</param> + /// <param name="shortVersion">Set to true, if the subnet is to be excluded as part of the address.</param> /// <returns>String representation of this object.</returns> public string ToString(bool shortVersion) { diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index d18ac98933..69cd57f8ae 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -86,7 +86,9 @@ namespace MediaBrowser.Common.Net // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out. // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept. - byte[] addressBytes = address.GetAddressBytes(); + // GetAddressBytes + Span<byte> addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + address.TryWriteBytes(addressBytes, out _); int div = prefixLength / 8; int mod = prefixLength % 8; @@ -170,14 +172,16 @@ namespace MediaBrowser.Common.Net if (!address.Equals(IPAddress.None)) { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + if (address.AddressFamily == AddressFamily.InterNetwork) { - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - byte[] octet = address.GetAddressBytes(); + // GetAddressBytes + Span<byte> octet = stackalloc byte[4]; + address.TryWriteBytes(octet, out _); return (octet[0] == 10) || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918 @@ -186,7 +190,10 @@ namespace MediaBrowser.Common.Net } else { - byte[] octet = address.GetAddressBytes(); + // GetAddressBytes + Span<byte> octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link. @@ -223,7 +230,9 @@ namespace MediaBrowser.Common.Net return false; } - byte[] octet = address.GetAddressBytes(); + // GetAddressBytes + Span<byte> octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); uint word = (uint)(octet[0] << 8) + octet[1]; return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. @@ -261,7 +270,9 @@ namespace MediaBrowser.Common.Net byte cidrnet = 0; if (!mask.Equals(IPAddress.Any)) { - byte[] bytes = mask.GetAddressBytes(); + // GetAddressBytes + Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + mask.TryWriteBytes(bytes, out _); var zeroed = false; for (var i = 0; i < bytes.Length; i++) From c01042b35560ddc703917d8e588cfb00734dc36f Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 21 Nov 2020 12:28:32 +0100 Subject: [PATCH 0463/1930] Fix nullref --- Jellyfin.Api/Controllers/ImageController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 76e53b9a53..366f701632 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -928,7 +928,7 @@ namespace Jellyfin.Api.Controllers [FromRoute] int? imageIndex = null) { var user = _userManager.GetUserById(userId); - if (user == null) + if (user?.ProfileImage == null) { return NotFound(); } From 124bd4c2c03874f5b4de241e3d89ac95f6048b9a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 12:59:14 +0000 Subject: [PATCH 0464/1930] Networking: 1 - Network Manager (#4124) * NetworkManager * Config file with additional options. * Update Jellyfin.Networking/Manager/INetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/INetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Model/Configuration/ServerConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Model/Configuration/ServerConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Model/Configuration/ServerConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Split function. * Update Jellyfin.Networking/Manager/INetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * fixed iterations * Update Jellyfin.Networking.csproj * Update NetworkManager.cs * Updated to NetCollection 1.03. * Update ServerConfiguration.cs * Update StartupController.cs * Update INetworkManager.cs Removed public * Update INetworkManager.cs * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Updated comment * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update Jellyfin.Networking/Manager/INetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Remove mono code. Removed forced chromecast option * Inverted if * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Moved config into a separate container * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Changed sortedList to dictionary. * Update INetworkManager.cs Changed UpdateSettings param type * Update NetworkManager.cs * Update NetworkManager.cs * Update NetworkManager.cs * Update NetworkConfiguration.cs * Update INetworkManager.cs * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update MediaBrowser.Model/Configuration/ServerConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Model/Configuration/ServerConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Updated changes github didn't update. * Fixed compilation. * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Removed read locking. * Update NetworkManager.cs Changed configuration event to NamedConfigurationUpdated * updated comment * removed whitespace * Updated NetCollection to 1.0.6 Updated DXCopAnalyser to 3.3.1 * removed NetCollection * Update NetworkManager.cs * Update NetworkExtensions.cs * Update NetworkExtensions.cs Removed function. * Update NetworkExtensions.cs * Update NetworkManager.cs Changed ToString() to AsString() as native collection formats incorrectly. * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update NetworkExtensions.cs * Update Jellyfin.Networking/Configuration/NetworkConfiguration.cs Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> * Update Jellyfin.Networking/Configuration/NetworkConfiguration.cs Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> * Update Jellyfin.Networking/Configuration/NetworkConfiguration.cs Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> * updated * Replaced NetCollection with Collection<IPObject> * Update MediaBrowser.Common/Net/NetworkExtensions.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Model/Configuration/PathSubstitution.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/NetworkExtensions.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPHost.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * Update MediaBrowser.Common/Net/IPObject.cs Co-authored-by: Cody Robibero <cody@robibe.ro> * updated comments. * Updated comments / changes as suggested by @crobibero. * Split function as suggested * Fixed null ref. * Updated comment. * Updated cs to .net5 * Fixed issue with PublishedServerUrl * Fixes * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Restored locking * optimisation * Added comment * updates. * updated. * updates * updated. * Update IPHost.cs * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> * Update NetworkManager.cs * Removed whitespace. * Added debug logging * Added debug. * Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Bond-009 <bond.009@outlook.com> * Replaced GetAddressBytes Co-authored-by: Cody Robibero <cody@robibe.ro> Co-authored-by: Claus Vium <cvium@users.noreply.github.com> Co-authored-by: h1dden-da3m0n <33120068+h1dden-da3m0n@users.noreply.github.com> Co-authored-by: Bond-009 <bond.009@outlook.com> --- .../Networking/NetworkManager.cs | 30 +- Jellyfin.Api/Controllers/StartupController.cs | 6 +- .../Configuration/NetworkConfiguration.cs | 221 +++ .../NetworkConfigurationExtensions.cs | 21 + .../NetworkConfigurationFactory.cs | 27 + .../Jellyfin.Networking.csproj | 30 + .../Manager/INetworkManager.cs | 234 +++ Jellyfin.Networking/Manager/NetworkManager.cs | 1319 +++++++++++++++++ MediaBrowser.Common/Net/IPHost.cs | 445 ++++++ MediaBrowser.Common/Net/IPNetAddress.cs | 277 ++++ MediaBrowser.Common/Net/IPObject.cs | 406 +++++ MediaBrowser.Common/Net/NetworkExtensions.cs | 262 ++++ .../Configuration/PathSubstitution.cs | 20 + .../Configuration/ServerConfiguration.cs | 690 +++++---- MediaBrowser.sln | 34 +- 15 files changed, 3672 insertions(+), 350 deletions(-) create mode 100644 Jellyfin.Networking/Configuration/NetworkConfiguration.cs create mode 100644 Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs create mode 100644 Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs create mode 100644 Jellyfin.Networking/Jellyfin.Networking.csproj create mode 100644 Jellyfin.Networking/Manager/INetworkManager.cs create mode 100644 Jellyfin.Networking/Manager/NetworkManager.cs create mode 100644 MediaBrowser.Common/Net/IPHost.cs create mode 100644 MediaBrowser.Common/Net/IPNetAddress.cs create mode 100644 MediaBrowser.Common/Net/IPObject.cs create mode 100644 MediaBrowser.Common/Net/NetworkExtensions.cs create mode 100644 MediaBrowser.Model/Configuration/PathSubstitution.cs diff --git a/Emby.Server.Implementations/Networking/NetworkManager.cs b/Emby.Server.Implementations/Networking/NetworkManager.cs index 089ec30e6b..ff0a2a3617 100644 --- a/Emby.Server.Implementations/Networking/NetworkManager.cs +++ b/Emby.Server.Implementations/Networking/NetworkManager.cs @@ -18,13 +18,12 @@ namespace Emby.Server.Implementations.Networking public class NetworkManager : INetworkManager { private readonly ILogger<NetworkManager> _logger; - - private IPAddress[] _localIpAddresses; private readonly object _localIpAddressSyncLock = new object(); - private readonly object _subnetLookupLock = new object(); private readonly Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal); + private IPAddress[] _localIpAddresses; + private List<PhysicalAddress> _macAddresses; /// <summary> @@ -157,7 +156,9 @@ namespace Emby.Server.Implementations.Networking return false; } - byte[] octet = ipAddress.GetAddressBytes(); + // GetAddressBytes + Span<byte> octet = stackalloc byte[ipAddress.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + ipAddress.TryWriteBytes(octet, out _); if ((octet[0] == 10) || (octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918 @@ -260,7 +261,9 @@ namespace Emby.Server.Implementations.Networking /// <inheritdoc/> public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC) { - byte[] octet = address.GetAddressBytes(); + // GetAddressBytes + Span<byte> octet = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + address.TryWriteBytes(octet, out _); if ((octet[0] == 127) || // RFC1122 (octet[0] == 169 && octet[1] == 254)) // RFC3927 @@ -503,18 +506,25 @@ namespace Emby.Server.Implementations.Networking private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) { - byte[] ipAdressBytes = address.GetAddressBytes(); - byte[] subnetMaskBytes = subnetMask.GetAddressBytes(); + int size = address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16; - if (ipAdressBytes.Length != subnetMaskBytes.Length) + // GetAddressBytes + Span<byte> ipAddressBytes = stackalloc byte[size]; + address.TryWriteBytes(ipAddressBytes, out _); + + // GetAddressBytes + Span<byte> subnetMaskBytes = stackalloc byte[size]; + subnetMask.TryWriteBytes(subnetMaskBytes, out _); + + if (ipAddressBytes.Length != subnetMaskBytes.Length) { throw new ArgumentException("Lengths of IP address and subnet mask do not match."); } - byte[] broadcastAddress = new byte[ipAdressBytes.Length]; + byte[] broadcastAddress = new byte[ipAddressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { - broadcastAddress[i] = (byte)(ipAdressBytes[i] & subnetMaskBytes[i]); + broadcastAddress[i] = (byte)(ipAddressBytes[i] & subnetMaskBytes[i]); } return new IPAddress(broadcastAddress); diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs index 9c259cc198..e59c6e1ddf 100644 --- a/Jellyfin.Api/Controllers/StartupController.cs +++ b/Jellyfin.Api/Controllers/StartupController.cs @@ -72,9 +72,9 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult UpdateInitialConfiguration([FromBody, Required] StartupConfigurationDto startupConfiguration) { - _config.Configuration.UICulture = startupConfiguration.UICulture; - _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode; - _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage; + _config.Configuration.UICulture = startupConfiguration.UICulture ?? string.Empty; + _config.Configuration.MetadataCountryCode = startupConfiguration.MetadataCountryCode ?? string.Empty; + _config.Configuration.PreferredMetadataLanguage = startupConfiguration.PreferredMetadataLanguage ?? string.Empty; _config.SaveConfiguration(); return NoContent(); } diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs new file mode 100644 index 0000000000..df420f48a2 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -0,0 +1,221 @@ +#pragma warning disable CA1819 // Properties should not return arrays + +using System; +using MediaBrowser.Model.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// <summary> + /// Defines the <see cref="NetworkConfiguration" />. + /// </summary> + public class NetworkConfiguration + { + /// <summary> + /// The default value for <see cref="HttpServerPortNumber"/>. + /// </summary> + public const int DefaultHttpPort = 8096; + + /// <summary> + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. + /// </summary> + public const int DefaultHttpsPort = 8920; + + private string _baseUrl = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// </summary> + public bool RequireHttps { get; set; } + + /// <summary> + /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. + /// </summary> + public string BaseUrl + { + get => _baseUrl; + set + { + // Normalize the start of the string + if (string.IsNullOrWhiteSpace(value)) + { + // If baseUrl is empty, set an empty prefix string + _baseUrl = string.Empty; + return; + } + + if (value[0] != '/') + { + // If baseUrl was not configured with a leading slash, append one for consistency + value = "/" + value; + } + + // Normalize the end of the string + if (value[^1] == '/') + { + // If baseUrl was configured with a trailing slash, remove it for consistency + value = value.Remove(value.Length - 1); + } + + _baseUrl = value; + } + } + + /// <summary> + /// Gets or sets the public HTTPS port. + /// </summary> + /// <value>The public HTTPS port.</value> + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets the HTTP server port number. + /// </summary> + /// <value>The HTTP server port number.</value> + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets the HTTPS server port number. + /// </summary> + /// <value>The HTTPS server port number.</value> + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets a value indicating whether to use HTTPS. + /// </summary> + /// <remarks> + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for <see cref="ServerConfiguration.CertificatePath"/> and <see cref="ServerConfiguration.CertificatePassword"/>. + /// </remarks> + public bool EnableHttps { get; set; } + + /// <summary> + /// Gets or sets the public mapped port. + /// </summary> + /// <value>The public mapped port.</value> + public int PublicPort { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. + /// </summary> + public bool UPnPCreateHttpPortMap { get; set; } + + /// <summary> + /// Gets or sets the UDPPortRange. + /// </summary> + public string UDPPortRange { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// </summary> + public bool EnableIPV6 { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// </summary> + public bool EnableIPV4 { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect. + /// </summary> + public bool EnableSSDPTracing { get; set; } + + /// <summary> + /// Gets or sets the SSDPTracingFilter + /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// </summary> + public string SSDPTracingFilter { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the number of times SSDP UDP messages are sent. + /// </summary> + public int UDPSendCount { get; set; } = 2; + + /// <summary> + /// Gets or sets the delay between each groups of SSDP messages (in ms). + /// </summary> + public int UDPSendDelay { get; set; } = 100; + + /// <summary> + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding. + /// </summary> + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>. + /// </summary> + public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + + /// <summary> + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. + /// </summary> + public int GatewayMonitorPeriod { get; set; } = 60; + + /// <summary> + /// Gets a value indicating whether multi-socket binding is available. + /// </summary> + public bool EnableMultiSocketBinding { get; } = true; + + /// <summary> + /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. + /// Depending on the address range implemented ULA ranges might not be used. + /// </summary> + public bool TrustAllIP6Interfaces { get; set; } + + /// <summary> + /// Gets or sets the ports that HDHomerun uses. + /// </summary> + public string HDHomerunPortRange { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the PublishedServerUriBySubnet + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// </summary> + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. + /// </summary> + public bool AutoDiscoveryTracing { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// </summary> + public bool AutoDiscovery { get; set; } = true; + + /// <summary> + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>. + /// </summary> + public string[] RemoteIPFilter { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. + /// </summary> + public bool IsRemoteIPFilterBlacklist { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// </summary> + public bool EnableUPnP { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether access outside of the LAN is permitted. + /// </summary> + public bool EnableRemoteAccess { get; set; } = true; + + /// <summary> + /// Gets or sets the subnets that are deemed to make up the LAN. + /// </summary> + public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// </summary> + public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the known proxies. + /// </summary> + public string[] KnownProxies { get; set; } = Array.Empty<string>(); + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs new file mode 100644 index 0000000000..e77b17ba92 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -0,0 +1,21 @@ +using Jellyfin.Networking.Configuration; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// <summary> + /// Defines the <see cref="NetworkConfigurationExtensions" />. + /// </summary> + public static class NetworkConfigurationExtensions + { + /// <summary> + /// Retrieves the network configuration. + /// </summary> + /// <param name="config">The <see cref="IConfigurationManager"/>.</param> + /// <returns>The <see cref="NetworkConfiguration"/>.</returns> + public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) + { + return config.GetConfiguration<NetworkConfiguration>("network"); + } + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs new file mode 100644 index 0000000000..ac0485d871 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// <summary> + /// Defines the <see cref="NetworkConfigurationFactory" />. + /// </summary> + public class NetworkConfigurationFactory : IConfigurationFactory + { + /// <summary> + /// The GetConfigurations. + /// </summary> + /// <returns>The <see cref="IEnumerable{ConfigurationStore}"/>.</returns> + public IEnumerable<ConfigurationStore> GetConfigurations() + { + return new[] + { + new ConfigurationStore + { + Key = "network", + ConfigurationType = typeof(NetworkConfiguration) + } + }; + } + } +} diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj new file mode 100644 index 0000000000..cbda74361f --- /dev/null +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -0,0 +1,30 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <TargetFramework>net5.0</TargetFramework> + <GenerateAssemblyInfo>false</GenerateAssemblyInfo> + <GenerateDocumentationFile>true</GenerateDocumentationFile> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <Compile Include="..\SharedVersion.cs" /> + </ItemGroup> + + <!-- Code Analyzers--> + <ItemGroup Condition=" '$(Configuration)' == 'Debug' "> + <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" /> + <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" /> + <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" /> + </ItemGroup> + + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> + <CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + + <ItemGroup> + <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" /> + <ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" /> + </ItemGroup> +</Project> diff --git a/Jellyfin.Networking/Manager/INetworkManager.cs b/Jellyfin.Networking/Manager/INetworkManager.cs new file mode 100644 index 0000000000..eababa6a90 --- /dev/null +++ b/Jellyfin.Networking/Manager/INetworkManager.cs @@ -0,0 +1,234 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.Net.NetworkInformation; +using Jellyfin.Networking.Configuration; +using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.Http; + +namespace Jellyfin.Networking.Manager +{ + /// <summary> + /// Interface for the NetworkManager class. + /// </summary> + public interface INetworkManager + { + /// <summary> + /// Event triggered on network changes. + /// </summary> + event EventHandler NetworkChanged; + + /// <summary> + /// Gets the published server urls list. + /// </summary> + Dictionary<IPNetAddress, string> PublishedServerUrls { get; } + + /// <summary> + /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// </summary> + bool TrustAllIP6Interfaces { get; } + + /// <summary> + /// Gets the remote address filter. + /// </summary> + Collection<IPObject> RemoteAddressFilter { get; } + + /// <summary> + /// Gets or sets a value indicating whether iP6 is enabled. + /// </summary> + bool IsIP6Enabled { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether iP4 is enabled. + /// </summary> + bool IsIP4Enabled { get; set; } + + /// <summary> + /// Calculates the list of interfaces to use for Kestrel. + /// </summary> + /// <returns>A Collection{IPObject} object containing all the interfaces to bind. + /// If all the interfaces are specified, and none are excluded, it returns zero items + /// to represent any address.</returns> + /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param> + Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false); + + /// <summary> + /// Returns a collection containing the loopback interfaces. + /// </summary> + /// <returns>Collection{IPObject}.</returns> + Collection<IPObject> GetLoopbacks(); + + /// <summary> + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// The priority of selection is as follows:- + /// + /// The value contained in the startup parameter --published-server-url. + /// + /// If the user specified custom subnet overrides, the correct subnet for the source address. + /// + /// If the user specified bind interfaces to use:- + /// The bind interface that contains the source subnet. + /// The first bind interface specified that suits best first the source's endpoint. eg. external or internal. + /// + /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:- + /// The first public interface that isn't a loopback and contains the source subnet. + /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways. + /// An internal interface if there are no public ip addresses. + /// + /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:- + /// The first private interface that contains the source subnet. + /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways. + /// + /// If no interfaces meet any of these criteria, then a loopback address is returned. + /// + /// Interface that have been specifically excluded from binding are not used in any of the calculations. + /// </summary> + /// <param name="source">Source of the request.</param> + /// <param name="port">Optional port returned, if it's part of an override.</param> + /// <returns>IP Address to use, or loopback address if all else fails.</returns> + string GetBindInterface(IPObject source, out int? port); + + /// <summary> + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. + /// </summary> + /// <param name="source">Source of the request.</param> + /// <param name="port">Optional port returned, if it's part of an override.</param> + /// <returns>IP Address to use, or loopback address if all else fails.</returns> + string GetBindInterface(HttpRequest source, out int? port); + + /// <summary> + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. + /// </summary> + /// <param name="source">IP address of the request.</param> + /// <param name="port">Optional port returned, if it's part of an override.</param> + /// <returns>IP Address to use, or loopback address if all else fails.</returns> + string GetBindInterface(IPAddress source, out int? port); + + /// <summary> + /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// If no bind addresses are specified, an internal interface address is selected. + /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. + /// </summary> + /// <param name="source">Source of the request.</param> + /// <param name="port">Optional port returned, if it's part of an override.</param> + /// <returns>IP Address to use, or loopback address if all else fails.</returns> + string GetBindInterface(string source, out int? port); + + /// <summary> + /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. + /// </summary> + /// <param name="address">IP address to check.</param> + /// <returns>True if it is.</returns> + bool IsExcludedInterface(IPAddress address); + + /// <summary> + /// Get a list of all the MAC addresses associated with active interfaces. + /// </summary> + /// <returns>List of MAC addresses.</returns> + IReadOnlyCollection<PhysicalAddress> GetMacAddresses(); + + /// <summary> + /// Checks to see if the IP Address provided matches an interface that has a gateway. + /// </summary> + /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> + /// <returns>Result of the check.</returns> + bool IsGatewayInterface(IPObject? addressObj); + + /// <summary> + /// Checks to see if the IP Address provided matches an interface that has a gateway. + /// </summary> + /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> + /// <returns>Result of the check.</returns> + bool IsGatewayInterface(IPAddress? addressObj); + + /// <summary> + /// Returns true if the address is a private address. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// </summary> + /// <param name="address">Address to check.</param> + /// <returns>True or False.</returns> + bool IsPrivateAddressRange(IPObject address); + + /// <summary> + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// </summary> + /// <param name="address">IP to check.</param> + /// <returns>True if endpoint is within the LAN range.</returns> + bool IsInLocalNetwork(string address); + + /// <summary> + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// </summary> + /// <param name="address">IP to check.</param> + /// <returns>True if endpoint is within the LAN range.</returns> + bool IsInLocalNetwork(IPObject address); + + /// <summary> + /// Returns true if the address is part of the user defined LAN. + /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// </summary> + /// <param name="address">IP to check.</param> + /// <returns>True if endpoint is within the LAN range.</returns> + bool IsInLocalNetwork(IPAddress address); + + /// <summary> + /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes. + /// eg. "eth1", or "TP-LINK Wireless USB Adapter". + /// </summary> + /// <param name="token">Token to parse.</param> + /// <param name="result">Resultant object's ip addresses, if successful.</param> + /// <returns>Success of the operation.</returns> + bool TryParseInterface(string token, out Collection<IPObject>? result); + + /// <summary> + /// Parses an array of strings into a Collection{IPObject}. + /// </summary> + /// <param name="values">Values to parse.</param> + /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> + /// <returns>IPCollection object containing the value strings.</returns> + Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false); + + /// <summary> + /// Returns all the internal Bind interface addresses. + /// </summary> + /// <returns>An internal list of interfaces addresses.</returns> + Collection<IPObject> GetInternalBindAddresses(); + + /// <summary> + /// Checks to see if an IP address is still a valid interface address. + /// </summary> + /// <param name="address">IP address to check.</param> + /// <returns>True if it is.</returns> + bool IsValidInterfaceAddress(IPAddress address); + + /// <summary> + /// Returns true if the IP address is in the excluded list. + /// </summary> + /// <param name="ip">IP to check.</param> + /// <returns>True if excluded.</returns> + bool IsExcluded(IPAddress ip); + + /// <summary> + /// Returns true if the IP address is in the excluded list. + /// </summary> + /// <param name="ip">IP to check.</param> + /// <returns>True if excluded.</returns> + bool IsExcluded(EndPoint ip); + + /// <summary> + /// Gets the filtered LAN ip addresses. + /// </summary> + /// <param name="filter">Optional filter for the list.</param> + /// <returns>Returns a filtered list of LAN addresses.</returns> + Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null); + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs new file mode 100644 index 0000000000..515ae669a1 --- /dev/null +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -0,0 +1,1319 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Networking.Manager +{ + /// <summary> + /// Class to take care of network interface management. + /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. + /// </summary> + public class NetworkManager : INetworkManager, IDisposable + { + /// <summary> + /// Contains the description of the interface along with its index. + /// </summary> + private readonly Dictionary<string, int> _interfaceNames; + + /// <summary> + /// Threading lock for network properties. + /// </summary> + private readonly object _intLock = new object(); + + /// <summary> + /// List of all interface addresses and masks. + /// </summary> + private readonly Collection<IPObject> _interfaceAddresses; + + /// <summary> + /// List of all interface MAC addresses. + /// </summary> + private readonly List<PhysicalAddress> _macAddresses; + + private readonly ILogger<NetworkManager> _logger; + + private readonly IConfigurationManager _configurationManager; + + private readonly object _eventFireLock; + + /// <summary> + /// Holds the bind address overrides. + /// </summary> + private readonly Dictionary<IPNetAddress, string> _publishedServerUrls; + + /// <summary> + /// Used to stop "event-racing conditions". + /// </summary> + private bool _eventfire; + + /// <summary> + /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>) + /// or internal interface network subnets if undefined by user. + /// </summary> + private Collection<IPObject> _lanSubnets; + + /// <summary> + /// User defined list of subnets to excluded from the LAN. + /// </summary> + private Collection<IPObject> _excludedSubnets; + + /// <summary> + /// List of interface addresses to bind the WS. + /// </summary> + private Collection<IPObject> _bindAddresses; + + /// <summary> + /// List of interface addresses to exclude from bind. + /// </summary> + private Collection<IPObject> _bindExclusions; + + /// <summary> + /// Caches list of all internal filtered interface addresses and masks. + /// </summary> + private Collection<IPObject> _internalInterfaces; + + /// <summary> + /// Flag set when no custom LAN has been defined in the config. + /// </summary> + private bool _usingPrivateAddresses; + + /// <summary> + /// True if this object is disposed. + /// </summary> + private bool _disposed; + + /// <summary> + /// Initializes a new instance of the <see cref="NetworkManager"/> class. + /// </summary> + /// <param name="configurationManager">IServerConfigurationManager instance.</param> + /// <param name="logger">Logger to use for messages.</param> +#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this. + public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); + + _interfaceAddresses = new Collection<IPObject>(); + _macAddresses = new List<PhysicalAddress>(); + _interfaceNames = new Dictionary<string, int>(); + _publishedServerUrls = new Dictionary<IPNetAddress, string>(); + _eventFireLock = new object(); + + UpdateSettings(_configurationManager.GetNetworkConfiguration()); + + NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; + NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; + + _configurationManager.NamedConfigurationUpdated += ConfigurationUpdated; + } +#pragma warning restore CS8618 // Non-nullable field is uninitialized. + + /// <summary> + /// Event triggered on network changes. + /// </summary> + public event EventHandler? NetworkChanged; + + /// <summary> + /// Gets or sets a value indicating whether testing is taking place. + /// </summary> + public static string MockNetworkSettings { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether IP6 is enabled. + /// </summary> + public bool IsIP6Enabled { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether IP4 is enabled. + /// </summary> + public bool IsIP4Enabled { get; set; } + + /// <inheritdoc/> + public Collection<IPObject> RemoteAddressFilter { get; private set; } + + /// <summary> + /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// </summary> + public bool TrustAllIP6Interfaces { get; internal set; } + + /// <summary> + /// Gets the Published server override list. + /// </summary> + public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls; + + /// <summary> + /// Creates a new network collection. + /// </summary> + /// <param name="source">Items to assign the collection, or null.</param> + /// <returns>The collection created.</returns> + public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null) + { + var result = new Collection<IPObject>(); + if (source != null) + { + foreach (var item in source) + { + result.AddItem(item); + } + } + + return result; + } + + /// <inheritdoc/> + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// <inheritdoc/> + public IReadOnlyCollection<PhysicalAddress> GetMacAddresses() + { + // Populated in construction - so always has values. + return _macAddresses; + } + + /// <inheritdoc/> + public bool IsGatewayInterface(IPObject? addressObj) + { + var address = addressObj?.Address ?? IPAddress.None; + return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); + } + + /// <inheritdoc/> + public bool IsGatewayInterface(IPAddress? addressObj) + { + return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0); + } + + /// <inheritdoc/> + public Collection<IPObject> GetLoopbacks() + { + Collection<IPObject> nc = new Collection<IPObject>(); + if (IsIP4Enabled) + { + nc.AddItem(IPAddress.Loopback); + } + + if (IsIP6Enabled) + { + nc.AddItem(IPAddress.IPv6Loopback); + } + + return nc; + } + + /// <inheritdoc/> + public bool IsExcluded(IPAddress ip) + { + return _excludedSubnets.ContainsAddress(ip); + } + + /// <inheritdoc/> + public bool IsExcluded(EndPoint ip) + { + return ip != null && IsExcluded(((IPEndPoint)ip).Address); + } + + /// <inheritdoc/> + public Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false) + { + Collection<IPObject> col = new Collection<IPObject>(); + if (values == null) + { + return col; + } + + for (int a = 0; a < values.Length; a++) + { + string v = values[a].Trim(); + + try + { + if (v.StartsWith('[') && v.EndsWith(']')) + { + if (bracketed) + { + AddToCollection(col, v[1..^1]); + } + } + else if (v.StartsWith('!')) + { + if (bracketed) + { + AddToCollection(col, v[1..]); + } + } + else if (!bracketed) + { + AddToCollection(col, v); + } + } + catch (ArgumentException e) + { + _logger.LogWarning(e, "Ignoring LAN value {value}.", v); + } + } + + return col; + } + + /// <inheritdoc/> + public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false) + { + int count = _bindAddresses.Count; + + if (count == 0) + { + if (_bindExclusions.Count > 0) + { + // Return all the interfaces except the ones specifically excluded. + return _interfaceAddresses.Exclude(_bindExclusions); + } + + if (individualInterfaces) + { + return new Collection<IPObject>(_interfaceAddresses); + } + + // No bind address and no exclusions, so listen on all interfaces. + Collection<IPObject> result = new Collection<IPObject>(); + + if (IsIP4Enabled) + { + result.AddItem(IPAddress.Any); + } + + if (IsIP6Enabled) + { + result.AddItem(IPAddress.IPv6Any); + } + + return result; + } + + // Remove any excluded bind interfaces. + return _bindAddresses.Exclude(_bindExclusions); + } + + /// <inheritdoc/> + public string GetBindInterface(string source, out int? port) + { + if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host)) + { + return GetBindInterface(host, out port); + } + + return GetBindInterface(IPHost.None, out port); + } + + /// <inheritdoc/> + public string GetBindInterface(IPAddress source, out int? port) + { + return GetBindInterface(new IPNetAddress(source), out port); + } + + /// <inheritdoc/> + public string GetBindInterface(HttpRequest source, out int? port) + { + string result; + + if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host)) + { + result = GetBindInterface(host, out port); + port ??= source.Host.Port; + } + else + { + result = GetBindInterface(IPNetAddress.None, out port); + port ??= source?.Host.Port; + } + + return result; + } + + /// <inheritdoc/> + public string GetBindInterface(IPObject source, out int? port) + { + port = null; + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + // Do we have a source? + bool haveSource = !source.Address.Equals(IPAddress.None); + bool isExternal = false; + + if (haveSource) + { + if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + { + _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } + + if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) + { + _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } + + isExternal = !IsInLocalNetwork(source); + + if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + { + _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); + return res; + } + } + + _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal); + + // No preference given, so move on to bind addresses. + if (MatchesBindInterface(source, isExternal, out string result)) + { + return result; + } + + if (isExternal && MatchesExternalInterface(source, out result)) + { + return result; + } + + // Get the first LAN interface address that isn't a loopback. + var interfaces = CreateCollection(_interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => IsInLocalNetwork(p)) + .OrderBy(p => p.Tag)); + + if (interfaces.Count > 0) + { + if (haveSource) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in interfaces) + { + if (intf.Contains(source)) + { + result = FormatIP6String(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); + return result; + } + } + } + + result = FormatIP6String(interfaces.First().Address); + _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); + return result; + } + + // There isn't any others, so we'll use the loopback. + result = IsIP6Enabled ? "::" : "127.0.0.1"; + _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); + return result; + } + + /// <inheritdoc/> + public Collection<IPObject> GetInternalBindAddresses() + { + int count = _bindAddresses.Count; + + if (count == 0) + { + if (_bindExclusions.Count > 0) + { + // Return all the internal interfaces except the ones excluded. + return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); + } + + // No bind address, so return all internal interfaces. + return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + } + + return new Collection<IPObject>(_bindAddresses); + } + + /// <inheritdoc/> + public bool IsInLocalNetwork(IPObject address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.Equals(IPAddress.None)) + { + return false; + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address); + } + + /// <inheritdoc/> + public bool IsInLocalNetwork(string address) + { + if (IPHost.TryParse(address, out IPHost ep)) + { + return _lanSubnets.ContainsAddress(ep) && !_excludedSubnets.ContainsAddress(ep); + } + + return false; + } + + /// <inheritdoc/> + public bool IsInLocalNetwork(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return _lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address); + } + + /// <inheritdoc/> + public bool IsPrivateAddressRange(IPObject address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + else + { + return address.IsPrivateAddressRange(); + } + } + + /// <inheritdoc/> + public bool IsExcludedInterface(IPAddress address) + { + return _bindExclusions.ContainsAddress(address); + } + + /// <inheritdoc/> + public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null) + { + if (filter == null) + { + return _lanSubnets.Exclude(_excludedSubnets).AsNetworks(); + } + + return _lanSubnets.Exclude(filter); + } + + /// <inheritdoc/> + public bool IsValidInterfaceAddress(IPAddress address) + { + return _interfaceAddresses.ContainsAddress(address); + } + + /// <inheritdoc/> + public bool TryParseInterface(string token, out Collection<IPObject>? result) + { + result = null; + if (string.IsNullOrEmpty(token)) + { + return false; + } + + if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) + { + result = new Collection<IPObject>(); + + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); + + // Replace interface tags with the interface IP's. + foreach (IPNetAddress iface in _interfaceAddresses) + { + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + { + result.AddItem(iface); + } + } + + return true; + } + + return false; + } + + /// <summary> + /// Reloads all settings and re-initialises the instance. + /// </summary> + /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> + public void UpdateSettings(object configuration) + { + NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); + + IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4; + IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; + + if (!IsIP6Enabled && !IsIP4Enabled) + { + _logger.LogError("IPv4 and IPv6 cannot both be disabled."); + IsIP4Enabled = true; + } + + TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; + // UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding; + + if (string.IsNullOrEmpty(MockNetworkSettings)) + { + InitialiseInterfaces(); + } + else // Used in testing only. + { + // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway. + var interfaceList = MockNetworkSettings.Split(':'); + foreach (var details in interfaceList) + { + var parts = details.Split(','); + var address = IPNetAddress.Parse(parts[0]); + var index = int.Parse(parts[1], CultureInfo.InvariantCulture); + address.Tag = index; + _interfaceAddresses.AddItem(address); + _interfaceNames.Add(parts[2], Math.Abs(index)); + } + } + + InitialiseLAN(config); + InitialiseBind(config); + InitialiseRemote(config); + InitialiseOverrides(config); + } + + /// <summary> + /// Protected implementation of Dispose pattern. + /// </summary> + /// <param name="disposing"><c>True</c> to dispose the managed state.</param> + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; + NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; + NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; + } + + _disposed = true; + } + } + + /// <summary> + /// Tries to identify the string and return an object of that class. + /// </summary> + /// <param name="addr">String to parse.</param> + /// <param name="result">IPObject to return.</param> + /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns> + private static bool TryParse(string addr, out IPObject result) + { + if (!string.IsNullOrEmpty(addr)) + { + // Is it an IP address + if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) + { + result = nw; + return true; + } + + if (IPHost.TryParse(addr, out IPHost h)) + { + result = h; + return true; + } + } + + result = IPNetAddress.None; + return false; + } + + /// <summary> + /// Converts an IPAddress into a string. + /// Ipv6 addresses are returned in [ ], with their scope removed. + /// </summary> + /// <param name="address">Address to convert.</param> + /// <returns>URI safe conversion of the address.</returns> + private static string FormatIP6String(IPAddress address) + { + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase); + + if (i != -1) + { + str = str.Substring(0, i); + } + + return $"[{str}]"; + } + + return str; + } + + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) + { + if (evt.Key.Equals("network", StringComparison.Ordinal)) + { + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); + } + } + + /// <summary> + /// Checks the string to see if it matches any interface names. + /// </summary> + /// <param name="token">String to check.</param> + /// <param name="index">Interface index number.</param> + /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns> + private bool IsInterface(string token, out int index) + { + index = -1; + + // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. + // Null check required here for automated testing. + if (_interfaceNames != null && token.Length > 1) + { + bool partial = token[^1] == '*'; + if (partial) + { + token = token[0..^1]; + } + + foreach ((string interfc, int interfcIndex) in _interfaceNames) + { + if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) + || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) + { + index = interfcIndex; + return true; + } + } + } + + return false; + } + + /// <summary> + /// Parses a string and adds it into the the collection, replacing any interface references. + /// </summary> + /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param> + /// <param name="token">String value to parse.</param> + private void AddToCollection(Collection<IPObject> col, string token) + { + // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. + // Null check required here for automated testing. + if (IsInterface(token, out int index)) + { + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); + + // Replace interface tags with the interface IP's. + foreach (IPNetAddress iface in _interfaceAddresses) + { + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + { + col.AddItem(iface); + } + } + } + else if (TryParse(token, out IPObject obj)) + { + if (!IsIP6Enabled) + { + // Remove IP6 addresses from multi-homed IPHosts. + obj.Remove(AddressFamily.InterNetworkV6); + if (!obj.IsIP6()) + { + col.AddItem(obj); + } + } + else if (!IsIP4Enabled) + { + // Remove IP4 addresses from multi-homed IPHosts. + obj.Remove(AddressFamily.InterNetwork); + if (obj.IsIP6()) + { + col.AddItem(obj); + } + } + else + { + col.AddItem(obj); + } + } + else + { + _logger.LogDebug("Invalid or unknown network {Token}.", token); + } + } + + /// <summary> + /// Handler for network change events. + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param> + private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) + { + _logger.LogDebug("Network availability changed."); + OnNetworkChanged(); + } + + /// <summary> + /// Handler for network change events. + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">An <see cref="EventArgs"/>.</param> + private void OnNetworkAddressChanged(object? sender, EventArgs e) + { + _logger.LogDebug("Network address change detected."); + OnNetworkChanged(); + } + + /// <summary> + /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// </summary> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> + private async Task OnNetworkChangeAsync() + { + try + { + await Task.Delay(2000).ConfigureAwait(false); + InitialiseInterfaces(); + // Recalculate LAN caches. + InitialiseLAN(_configurationManager.GetNetworkConfiguration()); + + NetworkChanged?.Invoke(this, EventArgs.Empty); + } + finally + { + _eventfire = false; + } + } + + /// <summary> + /// Triggers our event, and re-loads interface information. + /// </summary> + private void OnNetworkChanged() + { + lock (_eventFireLock) + { + if (!_eventfire) + { + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + OnNetworkChangeAsync().GetAwaiter().GetResult(); + } + } + } + + /// <summary> + /// Parses the user defined overrides into the dictionary object. + /// Overrides are the equivalent of localised publishedServerUrl, enabling + /// different addresses to be advertised over different subnets. + /// format is subnet=ipaddress|host|uri + /// when subnet = 0.0.0.0, any external address matches. + /// </summary> + private void InitialiseOverrides(NetworkConfiguration config) + { + lock (_intLock) + { + _publishedServerUrls.Clear(); + string[] overrides = config.PublishedServerUriBySubnet; + if (overrides == null) + { + return; + } + + foreach (var entry in overrides) + { + var parts = entry.Split('='); + if (parts.Length != 2) + { + _logger.LogError("Unable to parse bind override: {Entry}", entry); + } + else + { + var replacement = parts[1].Trim(); + if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; + } + else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; + } + else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null) + { + foreach (IPNetAddress na in addresses) + { + _publishedServerUrls[na] = replacement; + } + } + else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result)) + { + _publishedServerUrls[result] = replacement; + } + else + { + _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + } + } + } + } + } + + /// <summary> + /// Initialises the network bind addresses. + /// </summary> + private void InitialiseBind(NetworkConfiguration config) + { + lock (_intLock) + { + string[] lanAddresses = config.LocalNetworkAddresses; + + // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 + + if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) + { + lanAddresses = lanAddresses[0].Split(','); + } + + // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334 + + // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. + if (config.IgnoreVirtualInterfaces) + { + var virtualInterfaceNames = config.VirtualInterfaceNames.Split(','); + var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; + Array.Copy(lanAddresses, newList, lanAddresses.Length); + Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); + lanAddresses = newList; + } + + // Read and parse bind addresses and exclusions, removing ones that don't exist. + _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); + _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); + _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); + _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); + } + } + + /// <summary> + /// Initialises the remote address values. + /// </summary> + private void InitialiseRemote(NetworkConfiguration config) + { + lock (_intLock) + { + RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); + } + } + + /// <summary> + /// Initialises internal LAN cache settings. + /// </summary> + private void InitialiseLAN(NetworkConfiguration config) + { + lock (_intLock) + { + _logger.LogDebug("Refreshing LAN information."); + + // Get config options. + string[] subnets = config.LocalNetworkSubnets; + + // Create lists from user settings. + + _lanSubnets = CreateIPCollection(subnets); + _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks(); + + // If no LAN addresses are specified - all private subnets are deemed to be the LAN + _usingPrivateAddresses = _lanSubnets.Count == 0; + + // NOTE: The order of the commands generating the collection in this statement matters. + // Altering the order will cause the collections to be created incorrectly. + if (_usingPrivateAddresses) + { + _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); + // Internal interfaces must be private and not excluded. + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); + + // Subnets are the same as the calculated internal interface. + _lanSubnets = new Collection<IPObject>(); + + // We must listen on loopback for LiveTV to function regardless of the settings. + if (IsIP6Enabled) + { + _lanSubnets.AddItem(IPNetAddress.IP6Loopback); + _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA + _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local + } + + if (IsIP4Enabled) + { + _lanSubnets.AddItem(IPNetAddress.IP4Loopback); + _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8")); + _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12")); + _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16")); + } + } + else + { + // We must listen on loopback for LiveTV to function regardless of the settings. + if (IsIP6Enabled) + { + _lanSubnets.AddItem(IPNetAddress.IP6Loopback); + } + + if (IsIP4Enabled) + { + _lanSubnets.AddItem(IPNetAddress.IP4Loopback); + } + + // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); + } + + _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); + _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString()); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks().AsString()); + } + } + + /// <summary> + /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. + /// Generate a list of all active mac addresses that aren't loopback addresses. + /// </summary> + private void InitialiseInterfaces() + { + lock (_intLock) + { + _logger.LogDebug("Refreshing interfaces."); + + _interfaceNames.Clear(); + _interfaceAddresses.Clear(); + _macAddresses.Clear(); + + try + { + IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces() + .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); + + foreach (NetworkInterface adapter in nics) + { + try + { + IPInterfaceProperties ipProperties = adapter.GetIPProperties(); + PhysicalAddress mac = adapter.GetPhysicalAddress(); + + // populate mac list + if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None) + { + _macAddresses.Add(mac); + } + + // populate interface address list + foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) + { + if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + { + IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv4Properties().Index + }; + + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + } + else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + { + IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv6Properties().Index + }; + + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + } + } + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) + { + // Ignore error, and attempt to continue. + _logger.LogError(ex, "Error encountered parsing interfaces."); + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); + _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); + + // If for some reason we don't have an interface info, resolve our DNS name. + if (_interfaceAddresses.Count == 0) + { + _logger.LogError("No interfaces information available. Resolving DNS name."); + IPHost host = new IPHost(Dns.GetHostName()); + foreach (var a in host.GetAddresses()) + { + _interfaceAddresses.AddItem(a); + } + + if (_interfaceAddresses.Count == 0) + { + _logger.LogWarning("No interfaces information available. Using loopback."); + // Last ditch attempt - use loopback address. + _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); + if (IsIP6Enabled) + { + _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + } + } + } + } + catch (NetworkInformationException ex) + { + _logger.LogError(ex, "Error in InitialiseInterfaces."); + } + } + } + + /// <summary> + /// Attempts to match the source against a user defined bind interface. + /// </summary> + /// <param name="source">IP source address to use.</param> + /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> + /// <param name="bindPreference">The published server url that matches the source address.</param> + /// <param name="port">The resultant port, if one exists.</param> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> + private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port) + { + bindPreference = string.Empty; + port = null; + + // Check for user override. + foreach (var addr in _publishedServerUrls) + { + // Remaining. Match anything. + if (addr.Key.Address.Equals(IPAddress.Broadcast)) + { + bindPreference = addr.Value; + break; + } + else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + { + // External. + bindPreference = addr.Value; + break; + } + else if (addr.Key.Contains(source)) + { + // Match ip address. + bindPreference = addr.Value; + break; + } + } + + if (string.IsNullOrEmpty(bindPreference)) + { + return false; + } + + // Has it got a port defined? + var parts = bindPreference.Split(':'); + if (parts.Length > 1) + { + if (int.TryParse(parts[1], out int p)) + { + bindPreference = parts[0]; + port = p; + } + } + + return true; + } + + /// <summary> + /// Attempts to match the source against a user defined bind interface. + /// </summary> + /// <param name="source">IP source address to use.</param> + /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> + /// <param name="result">The result, if a match is found.</param> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> + private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) + { + result = string.Empty; + var addresses = _bindAddresses.Exclude(_bindExclusions); + + int count = addresses.Count; + if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) + { + // Ignore IPAny addresses. + count = 0; + } + + if (count != 0) + { + // Check to see if any of the bind interfaces are in the same subnet. + + IPAddress? defaultGateway = null; + IPAddress? bindAddress = null; + + if (isInExternalSubnet) + { + // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. + foreach (var addr in addresses.OrderBy(p => p.Tag)) + { + if (defaultGateway == null && !IsInLocalNetwork(addr)) + { + defaultGateway = addr.Address; + } + + if (bindAddress == null && addr.Contains(source)) + { + bindAddress = addr.Address; + } + + if (defaultGateway != null && bindAddress != null) + { + break; + } + } + } + else + { + // Look for the best internal address. + bindAddress = addresses + .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) + .OrderBy(p => p.Tag) + .FirstOrDefault()?.Address; + } + + if (bindAddress != null) + { + result = FormatIP6String(bindAddress); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result); + return true; + } + + if (isInExternalSubnet && defaultGateway != null) + { + result = FormatIP6String(defaultGateway); + _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); + return true; + } + + result = FormatIP6String(addresses[0].Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); + + if (isInExternalSubnet) + { + _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source); + } + + return true; + } + + return false; + } + + /// <summary> + /// Attempts to match the source against an external interface. + /// </summary> + /// <param name="source">IP source address to use.</param> + /// <param name="result">The result, if a match is found.</param> + /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> + private bool MatchesExternalInterface(IPObject source, out string result) + { + result = string.Empty; + // Get the first WAN interface address that isn't a loopback. + var extResult = _interfaceAddresses + .Exclude(_bindExclusions) + .Where(p => !IsInLocalNetwork(p)) + .OrderBy(p => p.Tag); + + if (extResult.Any()) + { + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in extResult) + { + if (!IsInLocalNetwork(intf) && intf.Contains(source)) + { + result = FormatIP6String(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); + return true; + } + } + + result = FormatIP6String(extResult.First().Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); + return true; + } + + // Have to return something, so return an internal address + + _logger.LogWarning("{Source}: External request received, however, no WAN interface found.", source); + return false; + } + } +} diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs new file mode 100644 index 0000000000..4cede9ab16 --- /dev/null +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -0,0 +1,445 @@ +#nullable enable +using System; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace MediaBrowser.Common.Net +{ + /// <summary> + /// Object that holds a host name. + /// </summary> + public class IPHost : IPObject + { + /// <summary> + /// Gets or sets timeout value before resolve required, in minutes. + /// </summary> + public const int Timeout = 30; + + /// <summary> + /// Represents an IPHost that has no value. + /// </summary> + public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); + + /// <summary> + /// Time when last resolved in ticks. + /// </summary> + private DateTime? _lastResolved = null; + + /// <summary> + /// Gets the IP Addresses, attempting to resolve the name, if there are none. + /// </summary> + private IPAddress[] _addresses; + + /// <summary> + /// Initializes a new instance of the <see cref="IPHost"/> class. + /// </summary> + /// <param name="name">Host name to assign.</param> + public IPHost(string name) + { + HostName = name ?? throw new ArgumentNullException(nameof(name)); + _addresses = Array.Empty<IPAddress>(); + Resolved = false; + } + + /// <summary> + /// Initializes a new instance of the <see cref="IPHost"/> class. + /// </summary> + /// <param name="name">Host name to assign.</param> + /// <param name="address">Address to assign.</param> + private IPHost(string name, IPAddress address) + { + HostName = name ?? throw new ArgumentNullException(nameof(name)); + _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) }; + Resolved = !address.Equals(IPAddress.None); + } + + /// <summary> + /// Gets or sets the object's first IP address. + /// </summary> + public override IPAddress Address + { + get + { + return ResolveHost() ? this[0] : IPAddress.None; + } + + set + { + // Not implemented, as a host's address is determined by DNS. + throw new NotImplementedException("The address of a host is determined by DNS."); + } + } + + /// <summary> + /// Gets or sets the object's first IP's subnet prefix. + /// The setter does nothing, but shouldn't raise an exception. + /// </summary> + public override byte PrefixLength + { + get + { + return (byte)(ResolveHost() ? 128 : 32); + } + + set + { + // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length, + // which is automatically determined by it's IP type. Anything else is meaningless. + } + } + + /// <summary> + /// Gets a value indicating whether the address has a value. + /// </summary> + public bool HasAddress => _addresses.Length != 0; + + /// <summary> + /// Gets the host name of this object. + /// </summary> + public string HostName { get; } + + /// <summary> + /// Gets a value indicating whether this host has attempted to be resolved. + /// </summary> + public bool Resolved { get; private set; } + + /// <summary> + /// Gets or sets the IP Addresses associated with this object. + /// </summary> + /// <param name="index">Index of address.</param> + public IPAddress this[int index] + { + get + { + ResolveHost(); + return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None; + } + } + + /// <summary> + /// Attempts to parse the host string. + /// </summary> + /// <param name="host">Host name to parse.</param> + /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param> + /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns> + public static bool TryParse(string host, out IPHost hostObj) + { + if (!string.IsNullOrEmpty(host)) + { + // See if it's an IPv6 with port address e.g. [::1]:120. + int i = host.IndexOf("]:", StringComparison.OrdinalIgnoreCase); + if (i != -1) + { + return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); + } + else + { + // See if it's an IPv6 in [] with no port. + i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase); + if (i != -1) + { + return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); + } + + // Is it a host or IPv4 with port? + string[] hosts = host.Split(':'); + + if (hosts.Length > 2) + { + hostObj = new IPHost(string.Empty, IPAddress.None); + return false; + } + + // Remove port from IPv4 if it exists. + host = hosts[0]; + + if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) + { + hostObj = new IPHost(host, new IPAddress(Ipv4Loopback)); + return true; + } + + if (IPNetAddress.TryParse(host, out IPNetAddress netIP)) + { + // Host name is an ip address, so fake resolve. + hostObj = new IPHost(host, netIP.Address); + return true; + } + } + + // Only thing left is to see if it's a host string. + if (!string.IsNullOrEmpty(host)) + { + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); + if (re.Match(host).Success) + { + hostObj = new IPHost(host); + return true; + } + } + } + + hostObj = IPHost.None; + return false; + } + + /// <summary> + /// Attempts to parse the host string. + /// </summary> + /// <param name="host">Host name to parse.</param> + /// <returns>Object representing the string, if it has successfully been parsed.</returns> + public static IPHost Parse(string host) + { + if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) + { + return res; + } + + throw new InvalidCastException("Host does not contain a valid value. {host}"); + } + + /// <summary> + /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type. + /// </summary> + /// <param name="host">Host name to parse.</param> + /// <param name="family">Addressfamily filter.</param> + /// <returns>Object representing the string, if it has successfully been parsed.</returns> + public static IPHost Parse(string host, AddressFamily family) + { + if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) + { + if (family == AddressFamily.InterNetwork) + { + res.Remove(AddressFamily.InterNetworkV6); + } + else + { + res.Remove(AddressFamily.InterNetwork); + } + + return res; + } + + throw new InvalidCastException("Host does not contain a valid value. {host}"); + } + + /// <summary> + /// Returns the Addresses that this item resolved to. + /// </summary> + /// <returns>IPAddress Array.</returns> + public IPAddress[] GetAddresses() + { + ResolveHost(); + return _addresses; + } + + /// <inheritdoc/> + public override bool Contains(IPAddress address) + { + if (address != null && !Address.Equals(IPAddress.None)) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + foreach (var addr in GetAddresses()) + { + if (address.Equals(addr)) + { + return true; + } + } + } + + return false; + } + + /// <inheritdoc/> + public override bool Equals(IPObject? other) + { + if (other is IPHost otherObj) + { + // Do we have the name Hostname? + if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (!ResolveHost() || !otherObj.ResolveHost()) + { + return false; + } + + // Do any of our IP addresses match? + foreach (IPAddress addr in _addresses) + { + foreach (IPAddress otherAddress in otherObj._addresses) + { + if (addr.Equals(otherAddress)) + { + return true; + } + } + } + } + + return false; + } + + /// <inheritdoc/> + public override bool IsIP6() + { + // Returns true if interfaces are only IP6. + if (ResolveHost()) + { + foreach (IPAddress i in _addresses) + { + if (i.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + } + + return true; + } + + return false; + } + + /// <inheritdoc/> + public override string ToString() + { + // StringBuilder not optimum here. + string output = string.Empty; + if (_addresses.Length > 0) + { + bool moreThanOne = _addresses.Length > 1; + if (moreThanOne) + { + output = "["; + } + + foreach (var i in _addresses) + { + if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified) + { + output += HostName + ","; + } + else if (i.Equals(IPAddress.Any)) + { + output += "Any IP4 Address,"; + } + else if (Address.Equals(IPAddress.IPv6Any)) + { + output += "Any IP6 Address,"; + } + else if (i.Equals(IPAddress.Broadcast)) + { + output += "Any Address,"; + } + else + { + output += $"{i}/32,"; + } + } + + output = output[0..^1]; + + if (moreThanOne) + { + output += "]"; + } + } + else + { + output = HostName; + } + + return output; + } + + /// <inheritdoc/> + public override void Remove(AddressFamily family) + { + if (ResolveHost()) + { + _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray(); + } + } + + /// <inheritdoc/> + public override bool Contains(IPObject address) + { + // An IPHost cannot contain another IPObject, it can only be equal. + return Equals(address); + } + + /// <inheritdoc/> + protected override IPObject CalculateNetworkAddress() + { + var netAddr = NetworkAddressOf(this[0], PrefixLength); + return new IPNetAddress(netAddr.Address, netAddr.PrefixLength); + } + + /// <summary> + /// Attempt to resolve the ip address of a host. + /// </summary> + /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns> + private bool ResolveHost() + { + // When was the last time we resolved? + if (_lastResolved == null) + { + _lastResolved = DateTime.UtcNow; + } + + // If we haven't resolved before, or our timer has run out... + if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved?.AddMinutes(Timeout))) + { + _lastResolved = DateTime.UtcNow; + ResolveHostInternal().GetAwaiter().GetResult(); + Resolved = true; + } + + return _addresses.Length > 0; + } + + /// <summary> + /// Task that looks up a Host name and returns its IP addresses. + /// </summary> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> + private async Task ResolveHostInternal() + { + if (!string.IsNullOrEmpty(HostName)) + { + // Resolves the host name - so save a DNS lookup. + if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase)) + { + _addresses = new IPAddress[] { new IPAddress(Ipv4Loopback), new IPAddress(Ipv6Loopback) }; + return; + } + + if (Uri.CheckHostName(HostName).Equals(UriHostNameType.Dns)) + { + try + { + IPHostEntry ip = await Dns.GetHostEntryAsync(HostName).ConfigureAwait(false); + _addresses = ip.AddressList; + } + catch (SocketException ex) + { + // Log and then ignore socket errors, as the result value will just be an empty array. + Debug.WriteLine("GetHostEntryAsync failed with {Message}.", ex.Message); + } + } + } + } + } +} diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs new file mode 100644 index 0000000000..a6f5fe4b37 --- /dev/null +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -0,0 +1,277 @@ +#nullable enable +using System; +using System.Net; +using System.Net.Sockets; + +namespace MediaBrowser.Common.Net +{ + /// <summary> + /// An object that holds and IP address and subnet mask. + /// </summary> + public class IPNetAddress : IPObject + { + /// <summary> + /// Represents an IPNetAddress that has no value. + /// </summary> + public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None); + + /// <summary> + /// IPv4 multicast address. + /// </summary> + public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250"); + + /// <summary> + /// IPv6 local link multicast address. + /// </summary> + public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); + + /// <summary> + /// IPv6 site local multicast address. + /// </summary> + public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); + + /// <summary> + /// IP4Loopback address host. + /// </summary> + public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/32"); + + /// <summary> + /// IP6Loopback address host. + /// </summary> + public static readonly IPNetAddress IP6Loopback = IPNetAddress.Parse("::1"); + + /// <summary> + /// Object's IP address. + /// </summary> + private IPAddress _address; + + /// <summary> + /// Initializes a new instance of the <see cref="IPNetAddress"/> class. + /// </summary> + /// <param name="address">Address to assign.</param> + public IPNetAddress(IPAddress address) + { + _address = address ?? throw new ArgumentNullException(nameof(address)); + PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + } + + /// <summary> + /// Initializes a new instance of the <see cref="IPNetAddress"/> class. + /// </summary> + /// <param name="address">IP Address.</param> + /// <param name="prefixLength">Mask as a CIDR.</param> + public IPNetAddress(IPAddress address, byte prefixLength) + { + if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address))) + { + _address = address.MapToIPv4(); + } + else + { + _address = address; + } + + PrefixLength = prefixLength; + } + + /// <summary> + /// Gets or sets the object's IP address. + /// </summary> + public override IPAddress Address + { + get + { + return _address; + } + + set + { + _address = value ?? IPAddress.None; + } + } + + /// <inheritdoc/> + public override byte PrefixLength { get; set; } + + /// <summary> + /// Try to parse the address and subnet strings into an IPNetAddress object. + /// </summary> + /// <param name="addr">IP address to parse. Can be CIDR or X.X.X.X notation.</param> + /// <param name="ip">Resultant object.</param> + /// <returns>True if the values parsed successfully. False if not, resulting in the IP being null.</returns> + public static bool TryParse(string addr, out IPNetAddress ip) + { + if (!string.IsNullOrEmpty(addr)) + { + addr = addr.Trim(); + + // Try to parse it as is. + if (IPAddress.TryParse(addr, out IPAddress? res)) + { + ip = new IPNetAddress(res); + return true; + } + + // Is it a network? + string[] tokens = addr.Split("/"); + + if (tokens.Length == 2) + { + tokens[0] = tokens[0].TrimEnd(); + tokens[1] = tokens[1].TrimStart(); + + if (IPAddress.TryParse(tokens[0], out res)) + { + // Is the subnet part a cidr? + if (byte.TryParse(tokens[1], out byte cidr)) + { + ip = new IPNetAddress(res, cidr); + return true; + } + + // Is the subnet in x.y.a.b form? + if (IPAddress.TryParse(tokens[1], out IPAddress? mask)) + { + ip = new IPNetAddress(res, MaskToCidr(mask)); + return true; + } + } + } + } + + ip = None; + return false; + } + + /// <summary> + /// Parses the string provided, throwing an exception if it is badly formed. + /// </summary> + /// <param name="addr">String to parse.</param> + /// <returns>IPNetAddress object.</returns> + public static IPNetAddress Parse(string addr) + { + if (TryParse(addr, out IPNetAddress o)) + { + return o; + } + + throw new ArgumentException("Unable to recognise object :" + addr); + } + + /// <inheritdoc/> + public override bool Contains(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + var altAddress = NetworkAddressOf(address, PrefixLength); + return NetworkAddress.Address.Equals(altAddress.Address) && NetworkAddress.PrefixLength >= altAddress.PrefixLength; + } + + /// <inheritdoc/> + public override bool Contains(IPObject address) + { + if (address is IPHost addressObj && addressObj.HasAddress) + { + foreach (IPAddress addr in addressObj.GetAddresses()) + { + if (Contains(addr)) + { + return true; + } + } + } + else if (address is IPNetAddress netaddrObj) + { + // Have the same network address, but different subnets? + if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address)) + { + return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength; + } + + var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength); + return NetworkAddress.Address.Equals(altAddress.Address); + } + + return false; + } + + /// <inheritdoc/> + public override bool Equals(IPObject? other) + { + if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None)) + { + return Address.Equals(otherObj.Address) && + PrefixLength == otherObj.PrefixLength; + } + + return false; + } + + /// <inheritdoc/> + public override bool Equals(IPAddress address) + { + if (address != null && !address.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) + { + return address.Equals(Address); + } + + return false; + } + + /// <inheritdoc/> + public override string ToString() + { + return ToString(false); + } + + /// <summary> + /// Returns a textual representation of this object. + /// </summary> + /// <param name="shortVersion">Set to true, if the subnet is to be excluded as part of the address.</param> + /// <returns>String representation of this object.</returns> + public string ToString(bool shortVersion) + { + if (!Address.Equals(IPAddress.None)) + { + if (Address.Equals(IPAddress.Any)) + { + return "Any IP4 Address"; + } + + if (Address.Equals(IPAddress.IPv6Any)) + { + return "Any IP6 Address"; + } + + if (Address.Equals(IPAddress.Broadcast)) + { + return "Any Address"; + } + + if (shortVersion) + { + return Address.ToString(); + } + + return $"{Address}/{PrefixLength}"; + } + + return string.Empty; + } + + /// <inheritdoc/> + protected override IPObject CalculateNetworkAddress() + { + var value = NetworkAddressOf(_address, PrefixLength); + return new IPNetAddress(value.Address, value.PrefixLength); + } + } +} diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs new file mode 100644 index 0000000000..69cd57f8ae --- /dev/null +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -0,0 +1,406 @@ +#nullable enable +using System; +using System.Net; +using System.Net.Sockets; + +namespace MediaBrowser.Common.Net +{ + /// <summary> + /// Base network object class. + /// </summary> + public abstract class IPObject : IEquatable<IPObject> + { + /// <summary> + /// IPv6 Loopback address. + /// </summary> + protected static readonly byte[] Ipv6Loopback = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; + + /// <summary> + /// IPv4 Loopback address. + /// </summary> + protected static readonly byte[] Ipv4Loopback = { 127, 0, 0, 1 }; + + /// <summary> + /// The network address of this object. + /// </summary> + private IPObject? _networkAddress; + + /// <summary> + /// Gets or sets a user defined value that is associated with this object. + /// </summary> + public int Tag { get; set; } + + /// <summary> + /// Gets or sets the object's IP address. + /// </summary> + public abstract IPAddress Address { get; set; } + + /// <summary> + /// Gets the object's network address. + /// </summary> + public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); + + /// <summary> + /// Gets or sets the object's IP address. + /// </summary> + public abstract byte PrefixLength { get; set; } + + /// <summary> + /// Gets the AddressFamily of this object. + /// </summary> + public AddressFamily AddressFamily + { + get + { + // Keep terms separate as Address performs other functions in inherited objects. + IPAddress address = Address; + return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily; + } + } + + /// <summary> + /// Returns the network address of an object. + /// </summary> + /// <param name="address">IP Address to convert.</param> + /// <param name="prefixLength">Subnet prefix.</param> + /// <returns>IPAddress.</returns> + public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (IsLoopback(address)) + { + return (Address: address, PrefixLength: prefixLength); + } + + // An ip address is just a list of bytes, each one representing a segment on the network. + // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the + // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out. + // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept. + + // GetAddressBytes + Span<byte> addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + address.TryWriteBytes(addressBytes, out _); + + int div = prefixLength / 8; + int mod = prefixLength % 8; + if (mod != 0) + { + // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear. + mod = 8 - mod; + + // Shift out the bits from the octet that we don't want, by moving right then back left. + addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod); + // Move on the next byte. + div++; + } + + // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0) + for (int octet = div; octet < addressBytes.Length; octet++) + { + addressBytes[octet] = 0; + } + + // Return the network address for the prefix. + return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); + } + + /// <summary> + /// Tests to see if the ip address is a Loopback address. + /// </summary> + /// <param name="address">Value to test.</param> + /// <returns>True if it is.</returns> + public static bool IsLoopback(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (!address.Equals(IPAddress.None)) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback); + } + + return false; + } + + /// <summary> + /// Tests to see if the ip address is an IP6 address. + /// </summary> + /// <param name="address">Value to test.</param> + /// <returns>True if it is.</returns> + public static bool IsIP6(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6); + } + + /// <summary> + /// Tests to see if the address in the private address range. + /// </summary> + /// <param name="address">Object to test.</param> + /// <returns>True if it contains a private address.</returns> + public static bool IsPrivateAddressRange(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (!address.Equals(IPAddress.None)) + { + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + // GetAddressBytes + Span<byte> octet = stackalloc byte[4]; + address.TryWriteBytes(octet, out _); + + return (octet[0] == 10) + || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918 + || (octet[0] == 192 && octet[1] == 168) // RFC1918 + || (octet[0] == 127); // RFC1122 + } + else + { + // GetAddressBytes + Span<byte> octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + + uint word = (uint)(octet[0] << 8) + octet[1]; + + return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link. + || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. + } + } + + return false; + } + + /// <summary> + /// Returns true if the IPAddress contains an IP6 Local link address. + /// </summary> + /// <param name="address">IPAddress object to check.</param> + /// <returns>True if it is a local link address.</returns> + /// <remarks> + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// </remarks> + public static bool IsIPv6LinkLocal(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + + // GetAddressBytes + Span<byte> octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; + + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. + } + + /// <summary> + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// </summary> + /// <param name="cidr">Subnet mask in CIDR notation.</param> + /// <param name="family">IPv4 or IPv6 family.</param> + /// <returns>String value of the subnet mask in dotted decimal notation.</returns> + public static IPAddress CidrToMask(byte cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// <summary> + /// Convert a mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. + /// </summary> + /// <param name="mask">Subnet mask.</param> + /// <returns>Byte CIDR representing the mask.</returns> + public static byte MaskToCidr(IPAddress mask) + { + if (mask == null) + { + throw new ArgumentNullException(nameof(mask)); + } + + byte cidrnet = 0; + if (!mask.Equals(IPAddress.Any)) + { + // GetAddressBytes + Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + mask.TryWriteBytes(bytes, out _); + + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) + { + if (zeroed) + { + // Invalid netmask. + return (byte)~cidrnet; + } + + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; + } + } + } + } + + return cidrnet; + } + + /// <summary> + /// Tests to see if this object is a Loopback address. + /// </summary> + /// <returns>True if it is.</returns> + public virtual bool IsLoopback() + { + return IsLoopback(Address); + } + + /// <summary> + /// Removes all addresses of a specific type from this object. + /// </summary> + /// <param name="family">Type of address to remove.</param> + public virtual void Remove(AddressFamily family) + { + // This method only performs a function in the IPHost implementation of IPObject. + } + + /// <summary> + /// Tests to see if this object is an IPv6 address. + /// </summary> + /// <returns>True if it is.</returns> + public virtual bool IsIP6() + { + return IsIP6(Address); + } + + /// <summary> + /// Returns true if this IP address is in the RFC private address range. + /// </summary> + /// <returns>True this object has a private address.</returns> + public virtual bool IsPrivateAddressRange() + { + return IsPrivateAddressRange(Address); + } + + /// <summary> + /// Compares this to the object passed as a parameter. + /// </summary> + /// <param name="ip">Object to compare to.</param> + /// <returns>Equality result.</returns> + public virtual bool Equals(IPAddress ip) + { + if (ip != null) + { + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + return !Address.Equals(IPAddress.None) && Address.Equals(ip); + } + + return false; + } + + /// <summary> + /// Compares this to the object passed as a parameter. + /// </summary> + /// <param name="other">Object to compare to.</param> + /// <returns>Equality result.</returns> + public virtual bool Equals(IPObject? other) + { + if (other != null) + { + return !Address.Equals(IPAddress.None) && Address.Equals(other.Address); + } + + return false; + } + + /// <summary> + /// Compares the address in this object and the address in the object passed as a parameter. + /// </summary> + /// <param name="address">Object's IP address to compare to.</param> + /// <returns>Comparison result.</returns> + public abstract bool Contains(IPObject address); + + /// <summary> + /// Compares the address in this object and the address in the object passed as a parameter. + /// </summary> + /// <param name="address">Object's IP address to compare to.</param> + /// <returns>Comparison result.</returns> + public abstract bool Contains(IPAddress address); + + /// <inheritdoc/> + public override int GetHashCode() + { + return Address.GetHashCode(); + } + + /// <inheritdoc/> + public override bool Equals(object? obj) + { + return Equals(obj as IPObject); + } + + /// <summary> + /// Calculates the network address of this object. + /// </summary> + /// <returns>Returns the network address of this object.</returns> + protected abstract IPObject CalculateNetworkAddress(); + } +} diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs new file mode 100644 index 0000000000..d07bba249b --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -0,0 +1,262 @@ +#pragma warning disable CA1062 // Validate arguments of public methods +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.Runtime.CompilerServices; +using System.Text; + +namespace MediaBrowser.Common.Net +{ + /// <summary> + /// Defines the <see cref="NetworkExtensions" />. + /// </summary> + public static class NetworkExtensions + { + /// <summary> + /// Add an address to the collection. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="ip">Item to add.</param> + public static void AddItem(this Collection<IPObject> source, IPAddress ip) + { + if (!source.ContainsAddress(ip)) + { + source.Add(new IPNetAddress(ip, 32)); + } + } + + /// <summary> + /// Adds a network to the collection. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="item">Item to add.</param> + public static void AddItem(this Collection<IPObject> source, IPObject item) + { + if (!source.ContainsAddress(item)) + { + source.Add(item); + } + } + + /// <summary> + /// Converts this object to a string. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <returns>Returns a string representation of this object.</returns> + public static string AsString(this Collection<IPObject> source) + { + return $"[{string.Join(',', source)}]"; + } + + /// <summary> + /// Returns true if the collection contains an item with the ip address, + /// or the ip address falls within any of the collection's network ranges. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="item">The item to look for.</param> + /// <returns>True if the collection contains the item.</returns> + public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item) + { + if (source.Count == 0) + { + return false; + } + + if (item == null) + { + throw new ArgumentNullException(nameof(item)); + } + + if (item.IsIPv4MappedToIPv6) + { + item = item.MapToIPv4(); + } + + foreach (var i in source) + { + if (i.Contains(item)) + { + return true; + } + } + + return false; + } + + /// <summary> + /// Returns true if the collection contains an item with the ip address, + /// or the ip address falls within any of the collection's network ranges. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="item">The item to look for.</param> + /// <returns>True if the collection contains the item.</returns> + public static bool ContainsAddress(this Collection<IPObject> source, IPObject item) + { + if (source.Count == 0) + { + return false; + } + + if (item == null) + { + throw new ArgumentNullException(nameof(item)); + } + + foreach (var i in source) + { + if (i.Contains(item)) + { + return true; + } + } + + return false; + } + + /// <summary> + /// Compares two Collection{IPObject} objects. The order is ignored. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="dest">Item to compare to.</param> + /// <returns>True if both are equal.</returns> + public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest) + { + if (dest == null || source.Count != dest.Count) + { + return false; + } + + foreach (var sourceItem in source) + { + bool found = false; + foreach (var destItem in dest) + { + if (sourceItem.Equals(destItem)) + { + found = true; + break; + } + } + + if (!found) + { + return false; + } + } + + return true; + } + + /// <summary> + /// Returns a collection containing the subnets of this collection given. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <returns>Collection{IPObject} object containing the subnets.</returns> + public static Collection<IPObject> AsNetworks(this Collection<IPObject> source) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + Collection<IPObject> res = new Collection<IPObject>(); + + foreach (IPObject i in source) + { + if (i is IPNetAddress nw) + { + // Add the subnet calculated from the interface address/mask. + var na = nw.NetworkAddress; + na.Tag = i.Tag; + res.AddItem(na); + } + else if (i is IPHost ipHost) + { + // Flatten out IPHost and add all its ip addresses. + foreach (var addr in ipHost.GetAddresses()) + { + IPNetAddress host = new IPNetAddress(addr) + { + Tag = i.Tag + }; + + res.AddItem(host); + } + } + } + + return res; + } + + /// <summary> + /// Excludes all the items from this list that are found in excludeList. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="excludeList">Items to exclude.</param> + /// <returns>A new collection, with the items excluded.</returns> + public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList) + { + if (source.Count == 0 || excludeList == null) + { + return new Collection<IPObject>(source); + } + + Collection<IPObject> results = new Collection<IPObject>(); + + bool found; + foreach (var outer in source) + { + found = false; + + foreach (var inner in excludeList) + { + if (outer.Equals(inner)) + { + found = true; + break; + } + } + + if (!found) + { + results.AddItem(outer); + } + } + + return results; + } + + /// <summary> + /// Returns all items that co-exist in this object and target. + /// </summary> + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <param name="target">Collection to compare with.</param> + /// <returns>A collection containing all the matches.</returns> + public static Collection<IPObject> Union(this Collection<IPObject> source, Collection<IPObject> target) + { + if (source.Count == 0) + { + return new Collection<IPObject>(); + } + + if (target == null) + { + throw new ArgumentNullException(nameof(target)); + } + + Collection<IPObject> nc = new Collection<IPObject>(); + + foreach (IPObject i in source) + { + if (target.ContainsAddress(i)) + { + nc.AddItem(i); + } + } + + return nc; + } + } +} diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs new file mode 100644 index 0000000000..bffaa85945 --- /dev/null +++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs @@ -0,0 +1,20 @@ +#nullable enable + +namespace MediaBrowser.Model.Configuration +{ + /// <summary> + /// Defines the <see cref="PathSubstitution" />. + /// </summary> + public class PathSubstitution + { + /// <summary> + /// Gets or sets the value to substitute. + /// </summary> + public string From { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the value to substitution with. + /// </summary> + public string To { get; set; } = string.Empty; + } +} diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 23a5201f7a..06985ebf40 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -1,5 +1,5 @@ -#nullable disable #pragma warning disable CS1591 +#pragma warning disable CA1819 using System; using System.Collections.Generic; @@ -13,326 +13,23 @@ namespace MediaBrowser.Model.Configuration /// </summary> public class ServerConfiguration : BaseApplicationConfiguration { + /// <summary> + /// The default value for <see cref="HttpServerPortNumber"/>. + /// </summary> public const int DefaultHttpPort = 8096; + + /// <summary> + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. + /// </summary> public const int DefaultHttpsPort = 8920; - private string _baseUrl; - /// <summary> - /// Gets or sets a value indicating whether to enable automatic port forwarding. - /// </summary> - public bool EnableUPnP { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether to enable prometheus metrics exporting. - /// </summary> - public bool EnableMetrics { get; set; } - - /// <summary> - /// Gets or sets the public mapped port. - /// </summary> - /// <value>The public mapped port.</value> - public int PublicPort { get; set; } - - /// <summary> - /// Gets or sets the public HTTPS port. - /// </summary> - /// <value>The public HTTPS port.</value> - public int PublicHttpsPort { get; set; } - - /// <summary> - /// Gets or sets the HTTP server port number. - /// </summary> - /// <value>The HTTP server port number.</value> - public int HttpServerPortNumber { get; set; } - - /// <summary> - /// Gets or sets the HTTPS server port number. - /// </summary> - /// <value>The HTTPS server port number.</value> - public int HttpsPortNumber { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether to use HTTPS. - /// </summary> - /// <remarks> - /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be - /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>. - /// </remarks> - public bool EnableHttps { get; set; } - - public bool EnableNormalizedItemByNameIds { get; set; } - - /// <summary> - /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. - /// </summary> - public string CertificatePath { get; set; } - - /// <summary> - /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. - /// </summary> - public string CertificatePassword { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether this instance is port authorized. - /// </summary> - /// <value><c>true</c> if this instance is port authorized; otherwise, <c>false</c>.</value> - public bool IsPortAuthorized { get; set; } - - /// <summary> - /// Gets or sets if quick connect is available for use on this server. - /// </summary> - public bool QuickConnectAvailable { get; set; } - - public bool EnableRemoteAccess { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether [enable case sensitive item ids]. - /// </summary> - /// <value><c>true</c> if [enable case sensitive item ids]; otherwise, <c>false</c>.</value> - public bool EnableCaseSensitiveItemIds { get; set; } - - public bool DisableLiveTvChannelUserDataName { get; set; } - - /// <summary> - /// Gets or sets the metadata path. - /// </summary> - /// <value>The metadata path.</value> - public string MetadataPath { get; set; } - - public string MetadataNetworkPath { get; set; } - - /// <summary> - /// Gets or sets the preferred metadata language. - /// </summary> - /// <value>The preferred metadata language.</value> - public string PreferredMetadataLanguage { get; set; } - - /// <summary> - /// Gets or sets the metadata country code. - /// </summary> - /// <value>The metadata country code.</value> - public string MetadataCountryCode { get; set; } - - /// <summary> - /// Characters to be replaced with a ' ' in strings to create a sort name. - /// </summary> - /// <value>The sort replace characters.</value> - public string[] SortReplaceCharacters { get; set; } - - /// <summary> - /// Characters to be removed from strings to create a sort name. - /// </summary> - /// <value>The sort remove characters.</value> - public string[] SortRemoveCharacters { get; set; } - - /// <summary> - /// Words to be removed from strings to create a sort name. - /// </summary> - /// <value>The sort remove words.</value> - public string[] SortRemoveWords { get; set; } - - /// <summary> - /// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated. - /// </summary> - /// <value>The min resume PCT.</value> - public int MinResumePct { get; set; } - - /// <summary> - /// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched. - /// </summary> - /// <value>The max resume PCT.</value> - public int MaxResumePct { get; set; } - - /// <summary> - /// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates.. - /// </summary> - /// <value>The min resume duration seconds.</value> - public int MinResumeDurationSeconds { get; set; } - - /// <summary> - /// The delay in seconds that we will wait after a file system change to try and discover what has been added/removed - /// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several - /// different directories and files. - /// </summary> - /// <value>The file watcher delay.</value> - public int LibraryMonitorDelay { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether [enable dashboard response caching]. - /// Allows potential contributors without visual studio to modify production dashboard code and test changes. - /// </summary> - /// <value><c>true</c> if [enable dashboard response caching]; otherwise, <c>false</c>.</value> - public bool EnableDashboardResponseCaching { get; set; } - - /// <summary> - /// Gets or sets the image saving convention. - /// </summary> - /// <value>The image saving convention.</value> - public ImageSavingConvention ImageSavingConvention { get; set; } - - public MetadataOptions[] MetadataOptions { get; set; } - - public bool SkipDeserializationForBasicTypes { get; set; } - - public string ServerName { get; set; } - - public string BaseUrl - { - get => _baseUrl; - set - { - // Normalize the start of the string - if (string.IsNullOrWhiteSpace(value)) - { - // If baseUrl is empty, set an empty prefix string - _baseUrl = string.Empty; - return; - } - - if (value[0] != '/') - { - // If baseUrl was not configured with a leading slash, append one for consistency - value = "/" + value; - } - - // Normalize the end of the string - if (value[value.Length - 1] == '/') - { - // If baseUrl was configured with a trailing slash, remove it for consistency - value = value.Remove(value.Length - 1); - } - - _baseUrl = value; - } - } - - public string UICulture { get; set; } - - public bool SaveMetadataHidden { get; set; } - - public NameValuePair[] ContentTypes { get; set; } - - public int RemoteClientBitrateLimit { get; set; } - - public bool EnableFolderView { get; set; } - - public bool EnableGroupingIntoCollections { get; set; } - - public bool DisplaySpecialsWithinSeasons { get; set; } - - public string[] LocalNetworkSubnets { get; set; } - - public string[] LocalNetworkAddresses { get; set; } - - public string[] CodecsUsed { get; set; } - - public List<RepositoryInfo> PluginRepositories { get; set; } - - public bool IgnoreVirtualInterfaces { get; set; } - - public bool EnableExternalContentInSuggestions { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether the server should force connections over HTTPS. - /// </summary> - public bool RequireHttps { get; set; } - - public bool EnableNewOmdbSupport { get; set; } - - public string[] RemoteIPFilter { get; set; } - - public bool IsRemoteIPFilterBlacklist { get; set; } - - public int ImageExtractionTimeoutMs { get; set; } - - public PathSubstitution[] PathSubstitutions { get; set; } - - public bool EnableSimpleArtistDetection { get; set; } - - public string[] UninstalledPlugins { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether slow server responses should be logged as a warning. - /// </summary> - public bool EnableSlowResponseWarning { get; set; } - - /// <summary> - /// Gets or sets the threshold for the slow response time warning in ms. - /// </summary> - public long SlowResponseThresholdMs { get; set; } - - /// <summary> - /// Gets or sets the cors hosts. - /// </summary> - public string[] CorsHosts { get; set; } - - /// <summary> - /// Gets or sets the known proxies. - /// </summary> - public string[] KnownProxies { get; set; } - - /// <summary> - /// Gets or sets the number of days we should retain activity logs. - /// </summary> - public int? ActivityLogRetentionDays { get; set; } + private string _baseUrl = string.Empty; /// <summary> /// Initializes a new instance of the <see cref="ServerConfiguration" /> class. /// </summary> public ServerConfiguration() { - UninstalledPlugins = Array.Empty<string>(); - RemoteIPFilter = Array.Empty<string>(); - LocalNetworkSubnets = Array.Empty<string>(); - LocalNetworkAddresses = Array.Empty<string>(); - CodecsUsed = Array.Empty<string>(); - PathSubstitutions = Array.Empty<PathSubstitution>(); - IgnoreVirtualInterfaces = false; - EnableSimpleArtistDetection = false; - SkipDeserializationForBasicTypes = true; - - PluginRepositories = new List<RepositoryInfo>(); - - DisplaySpecialsWithinSeasons = true; - EnableExternalContentInSuggestions = true; - - ImageSavingConvention = ImageSavingConvention.Compatible; - PublicPort = DefaultHttpPort; - PublicHttpsPort = DefaultHttpsPort; - HttpServerPortNumber = DefaultHttpPort; - HttpsPortNumber = DefaultHttpsPort; - EnableMetrics = false; - EnableHttps = false; - EnableDashboardResponseCaching = true; - EnableCaseSensitiveItemIds = true; - EnableNormalizedItemByNameIds = true; - DisableLiveTvChannelUserDataName = true; - EnableNewOmdbSupport = true; - - EnableRemoteAccess = true; - QuickConnectAvailable = false; - - EnableUPnP = false; - MinResumePct = 5; - MaxResumePct = 90; - - // 5 minutes - MinResumeDurationSeconds = 300; - - LibraryMonitorDelay = 60; - - ContentTypes = Array.Empty<NameValuePair>(); - - PreferredMetadataLanguage = "en"; - MetadataCountryCode = "US"; - - SortReplaceCharacters = new[] { ".", "+", "%" }; - SortRemoveCharacters = new[] { ",", "&", "-", "{", "}", "'" }; - SortRemoveWords = new[] { "the", "a", "an" }; - - BaseUrl = string.Empty; - UICulture = "en-US"; - MetadataOptions = new[] { new MetadataOptions() @@ -381,19 +78,366 @@ namespace MediaBrowser.Model.Configuration DisabledImageFetchers = new[] { "The Open Movie Database", "TheMovieDb" } } }; - - EnableSlowResponseWarning = true; - SlowResponseThresholdMs = 500; - CorsHosts = new[] { "*" }; - KnownProxies = Array.Empty<string>(); - ActivityLogRetentionDays = 30; } - } - public class PathSubstitution - { - public string From { get; set; } + /// <summary> + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// </summary> + public bool EnableUPnP { get; set; } = false; - public string To { get; set; } + /// <summary> + /// Gets or sets a value indicating whether to enable prometheus metrics exporting. + /// </summary> + public bool EnableMetrics { get; set; } = false; + + /// <summary> + /// Gets or sets the public mapped port. + /// </summary> + /// <value>The public mapped port.</value> + public int PublicPort { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. + /// </summary> + public bool UPnPCreateHttpPortMap { get; set; } = false; + + /// <summary> + /// Gets or sets client udp port range. + /// </summary> + public string UDPPortRange { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether IPV6 capability is enabled. + /// </summary> + public bool EnableIPV6 { get; set; } = false; + + /// <summary> + /// Gets or sets a value indicating whether IPV4 capability is enabled. + /// </summary> + public bool EnableIPV4 { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. + /// </summary> + public bool EnableSSDPTracing { get; set; } = false; + + /// <summary> + /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. + /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// </summary> + public string SSDPTracingFilter { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the number of times SSDP UDP messages are sent. + /// </summary> + public int UDPSendCount { get; set; } = 2; + + /// <summary> + /// Gets or sets the delay between each groups of SSDP messages (in ms). + /// </summary> + public int UDPSendDelay { get; set; } = 100; + + /// <summary> + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding. + /// </summary> + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>. + /// </summary> + public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + + /// <summary> + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. + /// </summary> + public int GatewayMonitorPeriod { get; set; } = 60; + + /// <summary> + /// Gets a value indicating whether multi-socket binding is available. + /// </summary> + public bool EnableMultiSocketBinding { get; } = true; + + /// <summary> + /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. + /// Depending on the address range implemented ULA ranges might not be used. + /// </summary> + public bool TrustAllIP6Interfaces { get; set; } = false; + + /// <summary> + /// Gets or sets the ports that HDHomerun uses. + /// </summary> + public string HDHomerunPortRange { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// </summary> + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. + /// </summary> + public bool AutoDiscoveryTracing { get; set; } = false; + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// </summary> + public bool AutoDiscovery { get; set; } = true; + + /// <summary> + /// Gets or sets the public HTTPS port. + /// </summary> + /// <value>The public HTTPS port.</value> + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets the HTTP server port number. + /// </summary> + /// <value>The HTTP server port number.</value> + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets the HTTPS server port number. + /// </summary> + /// <value>The HTTPS server port number.</value> + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets a value indicating whether to use HTTPS. + /// </summary> + /// <remarks> + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>. + /// </remarks> + public bool EnableHttps { get; set; } = false; + + public bool EnableNormalizedItemByNameIds { get; set; } = true; + + /// <summary> + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// </summary> + public string CertificatePath { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. + /// </summary> + public string CertificatePassword { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether this instance is port authorized. + /// </summary> + /// <value><c>true</c> if this instance is port authorized; otherwise, <c>false</c>.</value> + public bool IsPortAuthorized { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether quick connect is available for use on this server. + /// </summary> + public bool QuickConnectAvailable { get; set; } = false; + + /// <summary> + /// Gets or sets a value indicating whether access outside of the LAN is permitted. + /// </summary> + public bool EnableRemoteAccess { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether [enable case sensitive item ids]. + /// </summary> + /// <value><c>true</c> if [enable case sensitive item ids]; otherwise, <c>false</c>.</value> + public bool EnableCaseSensitiveItemIds { get; set; } = true; + + public bool DisableLiveTvChannelUserDataName { get; set; } = true; + + /// <summary> + /// Gets or sets the metadata path. + /// </summary> + /// <value>The metadata path.</value> + public string MetadataPath { get; set; } = string.Empty; + + public string MetadataNetworkPath { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the preferred metadata language. + /// </summary> + /// <value>The preferred metadata language.</value> + public string PreferredMetadataLanguage { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the metadata country code. + /// </summary> + /// <value>The metadata country code.</value> + public string MetadataCountryCode { get; set; } = "US"; + + /// <summary> + /// Gets or sets characters to be replaced with a ' ' in strings to create a sort name. + /// </summary> + /// <value>The sort replace characters.</value> + public string[] SortReplaceCharacters { get; set; } = new[] { ".", "+", "%" }; + + /// <summary> + /// Gets or sets characters to be removed from strings to create a sort name. + /// </summary> + /// <value>The sort remove characters.</value> + public string[] SortRemoveCharacters { get; set; } = new[] { ",", "&", "-", "{", "}", "'" }; + + /// <summary> + /// Gets or sets words to be removed from strings to create a sort name. + /// </summary> + /// <value>The sort remove words.</value> + public string[] SortRemoveWords { get; set; } = new[] { "the", "a", "an" }; + + /// <summary> + /// Gets or sets the minimum percentage of an item that must be played in order for playstate to be updated. + /// </summary> + /// <value>The min resume PCT.</value> + public int MinResumePct { get; set; } = 5; + + /// <summary> + /// Gets or sets the maximum percentage of an item that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched. + /// </summary> + /// <value>The max resume PCT.</value> + public int MaxResumePct { get; set; } = 90; + + /// <summary> + /// Gets or sets the minimum duration that an item must have in order to be eligible for playstate updates.. + /// </summary> + /// <value>The min resume duration seconds.</value> + public int MinResumeDurationSeconds { get; set; } = 300; + + /// <summary> + /// Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed + /// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several + /// different directories and files. + /// </summary> + /// <value>The file watcher delay.</value> + public int LibraryMonitorDelay { get; set; } = 60; + + /// <summary> + /// Gets or sets a value indicating whether [enable dashboard response caching]. + /// Allows potential contributors without visual studio to modify production dashboard code and test changes. + /// </summary> + /// <value><c>true</c> if [enable dashboard response caching]; otherwise, <c>false</c>.</value> + public bool EnableDashboardResponseCaching { get; set; } = true; + + /// <summary> + /// Gets or sets the image saving convention. + /// </summary> + /// <value>The image saving convention.</value> + public ImageSavingConvention ImageSavingConvention { get; set; } + + public MetadataOptions[] MetadataOptions { get; set; } + + public bool SkipDeserializationForBasicTypes { get; set; } = true; + + public string ServerName { get; set; } = string.Empty; + + public string BaseUrl + { + get => _baseUrl; + set + { + // Normalize the start of the string + if (string.IsNullOrWhiteSpace(value)) + { + // If baseUrl is empty, set an empty prefix string + _baseUrl = string.Empty; + return; + } + + if (value[0] != '/') + { + // If baseUrl was not configured with a leading slash, append one for consistency + value = "/" + value; + } + + // Normalize the end of the string + if (value[value.Length - 1] == '/') + { + // If baseUrl was configured with a trailing slash, remove it for consistency + value = value.Remove(value.Length - 1); + } + + _baseUrl = value; + } + } + + public string UICulture { get; set; } = "en-US"; + + public bool SaveMetadataHidden { get; set; } = false; + + public NameValuePair[] ContentTypes { get; set; } = Array.Empty<NameValuePair>(); + + public int RemoteClientBitrateLimit { get; set; } = 0; + + public bool EnableFolderView { get; set; } = false; + + public bool EnableGroupingIntoCollections { get; set; } = false; + + public bool DisplaySpecialsWithinSeasons { get; set; } = true; + + /// <summary> + /// Gets or sets the subnets that are deemed to make up the LAN. + /// </summary> + public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// </summary> + public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); + + public string[] CodecsUsed { get; set; } = Array.Empty<string>(); + + public List<RepositoryInfo> PluginRepositories { get; set; } = new List<RepositoryInfo>(); + + public bool EnableExternalContentInSuggestions { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// </summary> + public bool RequireHttps { get; set; } = false; + + public bool EnableNewOmdbSupport { get; set; } = true; + + /// <summary> + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>. + /// </summary> + public string[] RemoteIPFilter { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. + /// </summary> + public bool IsRemoteIPFilterBlacklist { get; set; } = false; + + public int ImageExtractionTimeoutMs { get; set; } = 0; + + public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty<PathSubstitution>(); + + public bool EnableSimpleArtistDetection { get; set; } = false; + + public string[] UninstalledPlugins { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether slow server responses should be logged as a warning. + /// </summary> + public bool EnableSlowResponseWarning { get; set; } = true; + + /// <summary> + /// Gets or sets the threshold for the slow response time warning in ms. + /// </summary> + public long SlowResponseThresholdMs { get; set; } = 500; + + /// <summary> + /// Gets or sets the cors hosts. + /// </summary> + public string[] CorsHosts { get; set; } = new[] { "*" }; + + /// <summary> + /// Gets or sets the known proxies. + /// </summary> + public string[] KnownProxies { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the number of days we should retain activity logs. + /// </summary> + public int? ActivityLogRetentionDays { get; set; } = 30; } } diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 25402aee13..d460c0ab0c 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26730.3 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server", "Jellyfin.Server\Jellyfin.Server.csproj", "{07E39F42-A2C6-4B32-AF8C-725F957A73FF}" EndProject @@ -66,12 +66,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Data", "Jellyfin.D EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementations", "Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj", "{DAE48069-6D86-4BA6-B148-D1D49B6DDA52}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {17E1F4E6-8ABD-4FE5-9ECF-43D4B6087BA2}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -132,10 +138,6 @@ Global {960295EE-4AF4-4440-A525-B4C295B01A61}.Debug|Any CPU.Build.0 = Debug|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.ActiveCfg = Release|Any CPU {960295EE-4AF4-4440-A525-B4C295B01A61}.Release|Any CPU.Build.0 = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {07E39F42-A2C6-4B32-AF8C-725F957A73FF}.Release|Any CPU.Build.0 = Release|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {154872D9-6C12-4007-96E3-8F70A58386CE}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -176,10 +178,22 @@ Global {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Debug|Any CPU.Build.0 = Debug|Any CPU {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.ActiveCfg = Release|Any CPU {DAE48069-6D86-4BA6-B148-D1D49B6DDA52}.Release|Any CPU.Build.0 = Release|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} EndGlobalSection @@ -201,12 +215,4 @@ Global $0.DotNetNamingPolicy = $2 $2.DirectoryNamespaceAssociation = PrefixedHierarchical EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {DF194677-DFD3-42AF-9F75-D44D5A416478} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {28464062-0939-4AA7-9F7B-24DDDA61A7C0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {3998657B-1CCC-49DD-A19F-275DC8495F57} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - EndGlobalSection EndGlobal From 05bd1383c141e165f0e72a5dd2ec626376cf33a2 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 13:22:23 +0000 Subject: [PATCH 0465/1930] Null pointer fix. (#4527) Co-authored-by: Patrick Barron <18354464+barronpm@users.noreply.github.com> --- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 332479ff8a..e540e44713 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -114,7 +114,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var seasonResult = await GetSeasonRootObject(seriesImdbId, seasonNumber, cancellationToken).ConfigureAwait(false); - if (seasonResult == null) + if (seasonResult?.Episodes == null) { return false; } From f5973d57e8c070692450f0e04e01615c78c954d9 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 21 Nov 2020 14:26:03 +0100 Subject: [PATCH 0466/1930] Remove UTF8 bom from some files --- Jellyfin.Api/Controllers/ApiKeyController.cs | 2 +- Jellyfin.Api/Controllers/ArtistsController.cs | 2 +- Jellyfin.Api/Controllers/BrandingController.cs | 2 +- Jellyfin.Api/Controllers/CollectionController.cs | 2 +- Jellyfin.Api/Controllers/DashboardController.cs | 2 +- Jellyfin.Api/Controllers/FilterController.cs | 2 +- Jellyfin.Api/Controllers/GenresController.cs | 2 +- Jellyfin.Api/Controllers/HlsSegmentController.cs | 2 +- Jellyfin.Api/Controllers/ImageController.cs | 2 +- Jellyfin.Api/Controllers/InstantMixController.cs | 2 +- Jellyfin.Api/Controllers/ItemLookupController.cs | 2 +- Jellyfin.Api/Controllers/ItemUpdateController.cs | 2 +- Jellyfin.Api/Controllers/LocalizationController.cs | 2 +- Jellyfin.Api/Controllers/MediaInfoController.cs | 2 +- Jellyfin.Api/Controllers/MoviesController.cs | 2 +- Jellyfin.Api/Controllers/MusicGenresController.cs | 2 +- Jellyfin.Api/Controllers/PersonsController.cs | 2 +- Jellyfin.Api/Controllers/PlaylistsController.cs | 2 +- Jellyfin.Api/Controllers/PlaystateController.cs | 2 +- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- Jellyfin.Api/Controllers/StudiosController.cs | 2 +- Jellyfin.Api/Controllers/SuggestionsController.cs | 2 +- Jellyfin.Api/Controllers/SyncPlayController.cs | 2 +- Jellyfin.Api/Controllers/SystemController.cs | 2 +- Jellyfin.Api/Controllers/TimeSyncController.cs | 2 +- Jellyfin.Api/Controllers/UniversalAudioController.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 2 +- Jellyfin.Api/Controllers/UserViewsController.cs | 2 +- Jellyfin.Api/Controllers/YearsController.cs | 2 +- 29 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Api/Controllers/ApiKeyController.cs b/Jellyfin.Api/Controllers/ApiKeyController.cs index e8d6ccdf27..8c43d786a7 100644 --- a/Jellyfin.Api/Controllers/ApiKeyController.cs +++ b/Jellyfin.Api/Controllers/ApiKeyController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Globalization; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index f684c649af..c65dc86201 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/BrandingController.cs b/Jellyfin.Api/Controllers/BrandingController.cs index 1d4836f278..d3ea412015 100644 --- a/Jellyfin.Api/Controllers/BrandingController.cs +++ b/Jellyfin.Api/Controllers/BrandingController.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Branding; using Microsoft.AspNetCore.Http; diff --git a/Jellyfin.Api/Controllers/CollectionController.cs b/Jellyfin.Api/Controllers/CollectionController.cs index 2a342c2cbe..2a7b2b5c62 100644 --- a/Jellyfin.Api/Controllers/CollectionController.cs +++ b/Jellyfin.Api/Controllers/CollectionController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index a859ac114c..ccc81dfc55 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index c97a1ed146..31cb9e2736 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.ModelBinders; diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 2dd504770d..d2b41e0a8d 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index ccdbbb2970..f519877326 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.IO; diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 366f701632..f48c1df72b 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index d17a26db43..6913afd0f5 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index a7c1a63882..6c38f77ce1 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; diff --git a/Jellyfin.Api/Controllers/ItemUpdateController.cs b/Jellyfin.Api/Controllers/ItemUpdateController.cs index 0a6ed31ae3..9e1a398538 100644 --- a/Jellyfin.Api/Controllers/ItemUpdateController.cs +++ b/Jellyfin.Api/Controllers/ItemUpdateController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Jellyfin.Api/Controllers/LocalizationController.cs b/Jellyfin.Api/Controllers/LocalizationController.cs index ef2e7e8b15..3d8b9e0cac 100644 --- a/Jellyfin.Api/Controllers/LocalizationController.cs +++ b/Jellyfin.Api/Controllers/LocalizationController.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Jellyfin.Api.Constants; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index 186024585b..b42e6686ec 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Buffers; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index ebc148fe56..75dfd4e68b 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 8c61043028..e7d0a61c58 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 9dc79b3884..aaad36551c 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index bc47ecbd1c..3e55434c06 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs index 5c15e9a0d7..7a60b0deb4 100644 --- a/Jellyfin.Api/Controllers/PlaystateController.cs +++ b/Jellyfin.Api/Controllers/PlaystateController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 0f8ceba291..98f1bc2d23 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index af28b4f597..5090bf1dee 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index 69292186e5..9f1dec712a 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index e16a10ba4d..346431e60c 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading; diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 4cb1984a2f..92875d7357 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; diff --git a/Jellyfin.Api/Controllers/TimeSyncController.cs b/Jellyfin.Api/Controllers/TimeSyncController.cs index 2dc744e7ca..27c7186fcb 100644 --- a/Jellyfin.Api/Controllers/TimeSyncController.cs +++ b/Jellyfin.Api/Controllers/TimeSyncController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using MediaBrowser.Model.SyncPlay; using Microsoft.AspNetCore.Http; diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 2555323077..34c9f32fa4 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 0f7c25d0e4..9805b84b1a 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; diff --git a/Jellyfin.Api/Controllers/UserViewsController.cs b/Jellyfin.Api/Controllers/UserViewsController.cs index 60fd1df013..e1483ce9d5 100644 --- a/Jellyfin.Api/Controllers/UserViewsController.cs +++ b/Jellyfin.Api/Controllers/UserViewsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 9c3ecb4cee..ec7c3de97f 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; From 616caca2b7a936b1f7ed4d94ec0ad5a10f4a78df Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 13:27:27 +0000 Subject: [PATCH 0467/1930] Added more comments. --- Emby.Server.Implementations/ApplicationHost.cs | 7 ++++++- .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 3 ++- Jellyfin.Api/Helpers/ClassMigrationHelper.cs | 11 ++++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 418f634bef..aff67f1637 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -271,9 +271,10 @@ namespace Emby.Server.Implementations _fileSystemManager = fileSystem; ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); + // Have to migrate settings here as migration subsystem not yet initialised. MigrateNetworkConfiguration(); - // Have to pre-register the NetworkConfigurationFactory. + // Have to pre-register the NetworkConfigurationFactory, as the configuration sub-system is not yet initialised. ConfigurationManager.RegisterConfiguration<NetworkConfigurationFactory>(); NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>()); @@ -301,6 +302,10 @@ namespace Emby.Server.Implementations ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; } + /// <summary> + /// Temporary function to migration network settings out of system.xml and into network.xml. + /// TODO: remove at the point when a fixed migration path has been decided upon. + /// </summary> private void MigrateNetworkConfiguration() { string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml"); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index b092ffd6e1..2eda1ab8bd 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -54,6 +54,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun /// <summary> /// Returns an unused UDP port number in the range specified. + /// Temporarily placed here until future network PR merged. /// </summary> /// <param name="range">Upper and Lower boundary of ports to select.</param> /// <returns>System.Int32.</returns> @@ -78,7 +79,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun var mediaSource = OriginalMediaSource; var uri = new Uri(mediaSource.Path); - // Temporary Code to reduce PR size. + // Temporary code to reduce PR size. This will be updated by a future network pr. var localPort = GetUdpPortFromRange((49152, 65535)); Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath)); diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs index 123fd012de..7184d49d5b 100644 --- a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs +++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs @@ -4,7 +4,8 @@ using System.Reflection; namespace Jellyfin.Api.Migrations { /// <summary> - /// A static class for reflection type functions. Temporary until web changed. + /// A static class for copying matching properties from one object to another. + /// TODO: remove at the point when a fixed migration path has been decided upon. /// </summary> public static class ClassMigrationHelper { @@ -15,17 +16,17 @@ namespace Jellyfin.Api.Migrations /// <param name="destination">The destination.</param> public static void CopyProperties(this object source, object destination) { - // If any this null throw an exception + // If any this null throw an exception. if (source == null || destination == null) { throw new Exception("Source or/and Destination Objects are null"); } - // Getting the Types of the objects + // Getting the Types of the objects. Type typeDest = destination.GetType(); Type typeSrc = source.GetType(); - // Iterate the Properties of the source instance and populate them from their desination counterparts. + // Iterate the Properties of the source instance and populate them from their destination counterparts. PropertyInfo[] srcProps = typeSrc.GetProperties(); foreach (PropertyInfo srcProp in srcProps) { @@ -62,7 +63,7 @@ namespace Jellyfin.Api.Migrations continue; } - // Passed all tests, lets set the value + // Passed all tests, lets set the value. targetProperty.SetValue(destination, srcProp.GetValue(source, null), null); } } From 33f6b13d4f9bb86f9e9740c36107275ef11e87aa Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 14:05:28 +0000 Subject: [PATCH 0468/1930] Moved INetworkManager --- .../Manager/INetworkManager.cs | 234 ------------------ 1 file changed, 234 deletions(-) delete mode 100644 Jellyfin.Networking/Manager/INetworkManager.cs diff --git a/Jellyfin.Networking/Manager/INetworkManager.cs b/Jellyfin.Networking/Manager/INetworkManager.cs deleted file mode 100644 index eababa6a90..0000000000 --- a/Jellyfin.Networking/Manager/INetworkManager.cs +++ /dev/null @@ -1,234 +0,0 @@ -#nullable enable -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Net; -using System.Net.NetworkInformation; -using Jellyfin.Networking.Configuration; -using MediaBrowser.Common.Net; -using Microsoft.AspNetCore.Http; - -namespace Jellyfin.Networking.Manager -{ - /// <summary> - /// Interface for the NetworkManager class. - /// </summary> - public interface INetworkManager - { - /// <summary> - /// Event triggered on network changes. - /// </summary> - event EventHandler NetworkChanged; - - /// <summary> - /// Gets the published server urls list. - /// </summary> - Dictionary<IPNetAddress, string> PublishedServerUrls { get; } - - /// <summary> - /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. - /// </summary> - bool TrustAllIP6Interfaces { get; } - - /// <summary> - /// Gets the remote address filter. - /// </summary> - Collection<IPObject> RemoteAddressFilter { get; } - - /// <summary> - /// Gets or sets a value indicating whether iP6 is enabled. - /// </summary> - bool IsIP6Enabled { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether iP4 is enabled. - /// </summary> - bool IsIP4Enabled { get; set; } - - /// <summary> - /// Calculates the list of interfaces to use for Kestrel. - /// </summary> - /// <returns>A Collection{IPObject} object containing all the interfaces to bind. - /// If all the interfaces are specified, and none are excluded, it returns zero items - /// to represent any address.</returns> - /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param> - Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false); - - /// <summary> - /// Returns a collection containing the loopback interfaces. - /// </summary> - /// <returns>Collection{IPObject}.</returns> - Collection<IPObject> GetLoopbacks(); - - /// <summary> - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) - /// If no bind addresses are specified, an internal interface address is selected. - /// The priority of selection is as follows:- - /// - /// The value contained in the startup parameter --published-server-url. - /// - /// If the user specified custom subnet overrides, the correct subnet for the source address. - /// - /// If the user specified bind interfaces to use:- - /// The bind interface that contains the source subnet. - /// The first bind interface specified that suits best first the source's endpoint. eg. external or internal. - /// - /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:- - /// The first public interface that isn't a loopback and contains the source subnet. - /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways. - /// An internal interface if there are no public ip addresses. - /// - /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:- - /// The first private interface that contains the source subnet. - /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways. - /// - /// If no interfaces meet any of these criteria, then a loopback address is returned. - /// - /// Interface that have been specifically excluded from binding are not used in any of the calculations. - /// </summary> - /// <param name="source">Source of the request.</param> - /// <param name="port">Optional port returned, if it's part of an override.</param> - /// <returns>IP Address to use, or loopback address if all else fails.</returns> - string GetBindInterface(IPObject source, out int? port); - - /// <summary> - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) - /// If no bind addresses are specified, an internal interface address is selected. - /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. - /// </summary> - /// <param name="source">Source of the request.</param> - /// <param name="port">Optional port returned, if it's part of an override.</param> - /// <returns>IP Address to use, or loopback address if all else fails.</returns> - string GetBindInterface(HttpRequest source, out int? port); - - /// <summary> - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) - /// If no bind addresses are specified, an internal interface address is selected. - /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. - /// </summary> - /// <param name="source">IP address of the request.</param> - /// <param name="port">Optional port returned, if it's part of an override.</param> - /// <returns>IP Address to use, or loopback address if all else fails.</returns> - string GetBindInterface(IPAddress source, out int? port); - - /// <summary> - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) - /// If no bind addresses are specified, an internal interface address is selected. - /// (See <see cref="GetBindInterface(IPObject, out int?)"/>. - /// </summary> - /// <param name="source">Source of the request.</param> - /// <param name="port">Optional port returned, if it's part of an override.</param> - /// <returns>IP Address to use, or loopback address if all else fails.</returns> - string GetBindInterface(string source, out int? port); - - /// <summary> - /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. - /// </summary> - /// <param name="address">IP address to check.</param> - /// <returns>True if it is.</returns> - bool IsExcludedInterface(IPAddress address); - - /// <summary> - /// Get a list of all the MAC addresses associated with active interfaces. - /// </summary> - /// <returns>List of MAC addresses.</returns> - IReadOnlyCollection<PhysicalAddress> GetMacAddresses(); - - /// <summary> - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// </summary> - /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> - /// <returns>Result of the check.</returns> - bool IsGatewayInterface(IPObject? addressObj); - - /// <summary> - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// </summary> - /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> - /// <returns>Result of the check.</returns> - bool IsGatewayInterface(IPAddress? addressObj); - - /// <summary> - /// Returns true if the address is a private address. - /// The config option TrustIP6Interfaces overrides this functions behaviour. - /// </summary> - /// <param name="address">Address to check.</param> - /// <returns>True or False.</returns> - bool IsPrivateAddressRange(IPObject address); - - /// <summary> - /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. - /// </summary> - /// <param name="address">IP to check.</param> - /// <returns>True if endpoint is within the LAN range.</returns> - bool IsInLocalNetwork(string address); - - /// <summary> - /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. - /// </summary> - /// <param name="address">IP to check.</param> - /// <returns>True if endpoint is within the LAN range.</returns> - bool IsInLocalNetwork(IPObject address); - - /// <summary> - /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. - /// </summary> - /// <param name="address">IP to check.</param> - /// <returns>True if endpoint is within the LAN range.</returns> - bool IsInLocalNetwork(IPAddress address); - - /// <summary> - /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes. - /// eg. "eth1", or "TP-LINK Wireless USB Adapter". - /// </summary> - /// <param name="token">Token to parse.</param> - /// <param name="result">Resultant object's ip addresses, if successful.</param> - /// <returns>Success of the operation.</returns> - bool TryParseInterface(string token, out Collection<IPObject>? result); - - /// <summary> - /// Parses an array of strings into a Collection{IPObject}. - /// </summary> - /// <param name="values">Values to parse.</param> - /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> - /// <returns>IPCollection object containing the value strings.</returns> - Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false); - - /// <summary> - /// Returns all the internal Bind interface addresses. - /// </summary> - /// <returns>An internal list of interfaces addresses.</returns> - Collection<IPObject> GetInternalBindAddresses(); - - /// <summary> - /// Checks to see if an IP address is still a valid interface address. - /// </summary> - /// <param name="address">IP address to check.</param> - /// <returns>True if it is.</returns> - bool IsValidInterfaceAddress(IPAddress address); - - /// <summary> - /// Returns true if the IP address is in the excluded list. - /// </summary> - /// <param name="ip">IP to check.</param> - /// <returns>True if excluded.</returns> - bool IsExcluded(IPAddress ip); - - /// <summary> - /// Returns true if the IP address is in the excluded list. - /// </summary> - /// <param name="ip">IP to check.</param> - /// <returns>True if excluded.</returns> - bool IsExcluded(EndPoint ip); - - /// <summary> - /// Gets the filtered LAN ip addresses. - /// </summary> - /// <param name="filter">Optional filter for the list.</param> - /// <returns>Returns a filtered list of LAN addresses.</returns> - Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null); - } -} From 086e2fdaa1153588042a38fd06c9b4802127ed71 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 14:09:56 +0000 Subject: [PATCH 0469/1930] Fixed a couple of merge errors. --- MediaBrowser.Model/Configuration/PathSubstitution.cs | 7 ------- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 4 ++-- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Model/Configuration/PathSubstitution.cs b/MediaBrowser.Model/Configuration/PathSubstitution.cs index f47eabd1e9..bffaa85945 100644 --- a/MediaBrowser.Model/Configuration/PathSubstitution.cs +++ b/MediaBrowser.Model/Configuration/PathSubstitution.cs @@ -1,11 +1,4 @@ #nullable enable -#pragma warning disable CS1591 -#pragma warning disable CA1819 - -using System; -using System.Collections.Generic; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Updates; namespace MediaBrowser.Model.Configuration { diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index d3e29d6a4a..830c8bd102 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -233,7 +233,7 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets a value indicating whether quick connect is available for use on this server. /// </summary> public bool QuickConnectAvailable { get; set; } = false; - + /// <summary> /// Gets or sets a value indicating whether access outside of the LAN is permitted. /// </summary> @@ -440,4 +440,4 @@ namespace MediaBrowser.Model.Configuration /// </summary> public int? ActivityLogRetentionDays { get; set; } = 30; } -} \ No newline at end of file +} From 8f25eaeb9d09ea0c0292484a1019dcc206a5ecae Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:02:54 +0000 Subject: [PATCH 0470/1930] Update Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 2eda1ab8bd..983b89f7b9 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -67,9 +67,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun .Where(n => n.Port >= range.Min && n.Port <= range.Max) .Select(n => n.Port); - return Enumerable.Range(range.Min, range.Max) - .Where(i => !udpListenerPorts.Contains(i)) - .FirstOrDefault(); + return Enumerable + .Range(range.Min, range.Max) + .FirstOrDefault(i => !udpListenerPorts.Contains(i)); } public override async Task Open(CancellationToken openCancellationToken) From ead881d4870f93cc3cd2876ba3c13256b466da39 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:03:16 +0000 Subject: [PATCH 0471/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index 03b733a9ab..926dd9599f 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -8,8 +8,6 @@ using MediaBrowser.Common.Net; using Moq; using Microsoft.Extensions.Logging.Abstractions; using Xunit; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; -using XMLProperties = System.Collections.Generic.Dictionary<string, string>; namespace NetworkTesting { From 56754a2af2bf3a1d10e2b8cbedcb99e693da4431 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:03:25 +0000 Subject: [PATCH 0472/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index 926dd9599f..e5885a4b2f 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -11,7 +11,7 @@ using Xunit; namespace NetworkTesting { - public class NetTesting + public class NetworkParseTests { /// <summary> /// Trys to identify the string and return an object of that class. From 46e6128f6c4194b1f3a478e79c866be363897b4a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:08:19 +0000 Subject: [PATCH 0473/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index e5885a4b2f..b1f0420fbc 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -9,7 +9,7 @@ using Moq; using Microsoft.Extensions.Logging.Abstractions; using Xunit; -namespace NetworkTesting +namespace Jellyfin.Networking.Tests { public class NetworkParseTests { From 7403b9a9e5d2a5647f698e988071adda1598284b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:10:35 +0000 Subject: [PATCH 0474/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index b1f0420fbc..b5d59093fd 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -105,7 +105,6 @@ namespace Jellyfin.Networking.Tests [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] [InlineData("192.168.1.2/255.255.255.0")] [InlineData("192.168.1.2/24")] - public void TestCollectionCreation(string address) { Assert.True(TryParse(address, out _)); From e41d1773bac5657e2a1787f131435f5edb6c4d70 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:14:00 +0000 Subject: [PATCH 0475/1930] changes --- Jellyfin.Api/Helpers/ClassMigrationHelper.cs | 2 +- .../NetworkTesting/UnitTesting.cs | 24 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs index 7184d49d5b..a911a33241 100644 --- a/Jellyfin.Api/Helpers/ClassMigrationHelper.cs +++ b/Jellyfin.Api/Helpers/ClassMigrationHelper.cs @@ -1,7 +1,7 @@ using System; using System.Reflection; -namespace Jellyfin.Api.Migrations +namespace Jellyfin.Api.Helpers { /// <summary> /// A static class for copying matching properties from one object to another. diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs index b5d59093fd..0bd442f0b6 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs @@ -8,13 +8,14 @@ using MediaBrowser.Common.Net; using Moq; using Microsoft.Extensions.Logging.Abstractions; using Xunit; +using System.Collections.ObjectModel; namespace Jellyfin.Networking.Tests { public class NetworkParseTests { /// <summary> - /// Trys to identify the string and return an object of that class. + /// Tries to identify the string and return an object of that class. /// </summary> /// <param name="addr">String to parse.</param> /// <param name="result">IPObject to return.</param> @@ -121,7 +122,6 @@ namespace Jellyfin.Networking.Tests } [Theory] - // Src, IncIP6, incIP4, exIP6, ecIP4, net [InlineData("127.0.0.1#", "[]", "[]", @@ -168,10 +168,10 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); // Test included, IP6. - NetCollection nc = nm.CreateIPCollection(settings.Split(","), false); + Collection<IPObject> nc = nm.CreateIPCollection(settings.Split(","), false); Assert.True(string.Equals(nc?.AsString(), result1, System.StringComparison.OrdinalIgnoreCase)); - // Text excluded, non IP6. + // Test excluded, non IP6. nc = nm.CreateIPCollection(settings.Split(","), true); Assert.True(string.Equals(nc?.AsString(), result3, System.StringComparison.OrdinalIgnoreCase)); @@ -224,8 +224,8 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); - NetCollection nc1 = nm.CreateIPCollection(settings.Split(","), false); - NetCollection nc2 = nm.CreateIPCollection(compare.Split(","), false); + Collection<IPObject> nc1 = nm.CreateIPCollection(settings.Split(","), false); + Collection<IPObject> nc2 = nm.CreateIPCollection(compare.Split(","), false); Assert.True(nc1.Union(nc2).AsString() == result); } @@ -334,10 +334,10 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); // Test included, IP6. - NetCollection ncSource = nm.CreateIPCollection(source.Split(",")); - NetCollection ncDest = nm.CreateIPCollection(dest.Split(",")); - NetCollection ncResult = ncSource.Union(ncDest); - NetCollection resultCollection = nm.CreateIPCollection(result.Split(",")); + Collection<IPObject> ncSource = nm.CreateIPCollection(source.Split(",")); + Collection<IPObject> ncDest = nm.CreateIPCollection(dest.Split(",")); + Collection<IPObject> ncResult = ncSource.Union(ncDest); + Collection<IPObject> resultCollection = nm.CreateIPCollection(result.Split(",")); Assert.True(ncResult.Compare(resultCollection)); } @@ -401,7 +401,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out NetCollection? resultObj); + _ = nm.TryParseInterface(result, out Collection<IPObject>? resultObj); if (resultObj != null) { @@ -468,7 +468,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out NetCollection? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out Collection<IPObject>? resultObj) && resultObj != null) { // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). result = ((IPNetAddress)resultObj[0]).ToString(true); From 9b5ae690c1d80fc8466b653f93edf7399753aa14 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 16:17:26 +0000 Subject: [PATCH 0476/1930] renamed file. --- Emby.Server.Implementations/ApplicationHost.cs | 1 - .../NetworkTesting/{UnitTesting.cs => NetworkParseTests.cs} | 0 2 files changed, 1 deletion(-) rename tests/Jellyfin.Networking.Tests/NetworkTesting/{UnitTesting.cs => NetworkParseTests.cs} (100%) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index aff67f1637..c695c02315 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -47,7 +47,6 @@ using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; -using Jellyfin.Api.Migrations; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common; diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs similarity index 100% rename from tests/Jellyfin.Networking.Tests/NetworkTesting/UnitTesting.cs rename to tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs From 2f00d05eae2277d00a777d27be763b606688ed03 Mon Sep 17 00:00:00 2001 From: Mario Campos <mario-campos@github.com> Date: Sat, 21 Nov 2020 11:49:52 -0600 Subject: [PATCH 0477/1930] Create codeql-analysis.yml --- .github/workflows/codeql-analysis.yml | 34 +++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000000..5ad2c1636b --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,34 @@ +name: "CodeQL" + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + schedule: + - cron: '24 2 * * 4' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + language: [ 'csharp' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 From e2aa7635bdd6e40b95f158390e38913464d7f773 Mon Sep 17 00:00:00 2001 From: Mario Campos <mario-campos@github.com> Date: Sat, 21 Nov 2020 12:03:09 -0600 Subject: [PATCH 0478/1930] Update codeql-analysis.yml --- .github/workflows/codeql-analysis.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 5ad2c1636b..24d75ae2c7 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -21,14 +21,15 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v2 - + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '5.0.100' - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} - - name: Autobuild uses: github/codeql-action/autobuild@v1 - - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 From f17e95abea3ee81c82d5bdb128bb1e9eb4407b1a Mon Sep 17 00:00:00 2001 From: Mario Campos <mario-campos@github.com> Date: Sat, 21 Nov 2020 12:21:58 -0600 Subject: [PATCH 0479/1930] Update codeql-analysis.yml --- .github/workflows/codeql-analysis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 24d75ae2c7..5388948189 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -29,6 +29,7 @@ jobs: uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} + queries: +security-extended - name: Autobuild uses: github/codeql-action/autobuild@v1 - name: Perform CodeQL Analysis From c8c5feacb601215b7b75952a97f589a9a1ecb09e Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 21 Nov 2020 11:37:22 -0700 Subject: [PATCH 0480/1930] Convert ClientCapabilities to a Dto with JsonConverters --- Jellyfin.Api/Controllers/SessionController.cs | 5 +- .../SessionDtos/ClientCapabilitiesDto.cs | 87 +++++++++++++++++++ .../Session/SessionInfo.cs | 5 +- .../Session/ClientCapabilities.cs | 5 +- 4 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 6c9b9050e6..e2269a2ce2 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -6,6 +6,7 @@ using System.Threading; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Api.Models.SessionDtos; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; @@ -412,14 +413,14 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult PostFullCapabilities( [FromQuery] string? id, - [FromBody, Required] ClientCapabilities capabilities) + [FromBody, Required] ClientCapabilitiesDto capabilities) { if (string.IsNullOrWhiteSpace(id)) { id = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id; } - _sessionManager.ReportCapabilities(id, capabilities); + _sessionManager.ReportCapabilities(id, capabilities.ToClientCapabilities()); return NoContent(); } diff --git a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs new file mode 100644 index 0000000000..ac1259ef29 --- /dev/null +++ b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using MediaBrowser.Common.Json.Converters; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Session; +using Newtonsoft.Json; + +namespace Jellyfin.Api.Models.SessionDtos +{ + /// <summary> + /// Client capabilities dto. + /// </summary> + public class ClientCapabilitiesDto + { + /// <summary> + /// Gets or sets the list of playable media types. + /// </summary> + public IReadOnlyList<string> PlayableMediaTypes { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the list of supported commands. + /// </summary> + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList<GeneralCommandType> SupportedCommands { get; set; } = Array.Empty<GeneralCommandType>(); + + /// <summary> + /// Gets or sets a value indicating whether session supports media control. + /// </summary> + public bool SupportsMediaControl { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether session supports content uploading. + /// </summary> + public bool SupportsContentUploading { get; set; } + + /// <summary> + /// Gets or sets the message callback url. + /// </summary> + public string? MessageCallbackUrl { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether session supports a persistent identifier. + /// </summary> + public bool SupportsPersistentIdentifier { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether session supports sync. + /// </summary> + public bool SupportsSync { get; set; } + + /// <summary> + /// Gets or sets the device profile. + /// </summary> + public DeviceProfile? DeviceProfile { get; set; } + + /// <summary> + /// Gets or sets the app store url. + /// </summary> + public string? AppStoreUrl { get; set; } + + /// <summary> + /// Gets or sets the icon url. + /// </summary> + public string? IconUrl { get; set; } + + /// <summary> + /// Convert the dto to the full <see cref="ClientCapabilities"/> model. + /// </summary> + /// <returns>The converted <see cref="ClientCapabilities"/> model.</returns> + public ClientCapabilities ToClientCapabilities() + { + return new ClientCapabilities + { + PlayableMediaTypes = PlayableMediaTypes, + SupportedCommands = SupportedCommands, + SupportsMediaControl = SupportsMediaControl, + SupportsContentUploading = SupportsContentUploading, + MessageCallbackUrl = MessageCallbackUrl, + SupportsPersistentIdentifier = SupportsPersistentIdentifier, + SupportsSync = SupportsSync, + DeviceProfile = DeviceProfile, + AppStoreUrl = AppStoreUrl, + IconUrl = IconUrl + }; + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index ce58a60b9a..d09852870e 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; using System.Threading; @@ -54,7 +55,7 @@ namespace MediaBrowser.Controller.Session /// Gets or sets the playable media types. /// </summary> /// <value>The playable media types.</value> - public string[] PlayableMediaTypes + public IReadOnlyList<string> PlayableMediaTypes { get { @@ -230,7 +231,7 @@ namespace MediaBrowser.Controller.Session /// Gets or sets the supported commands. /// </summary> /// <value>The supported commands.</value> - public GeneralCommandType[] SupportedCommands + public IReadOnlyList<GeneralCommandType> SupportedCommands => Capabilities == null ? Array.Empty<GeneralCommandType>() : Capabilities.SupportedCommands; public Tuple<ISessionController, bool> EnsureController<T>(Func<SessionInfo, ISessionController> factory) diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs index a85e6ff2a4..5852f4e37a 100644 --- a/MediaBrowser.Model/Session/ClientCapabilities.cs +++ b/MediaBrowser.Model/Session/ClientCapabilities.cs @@ -2,15 +2,16 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using MediaBrowser.Model.Dlna; namespace MediaBrowser.Model.Session { public class ClientCapabilities { - public string[] PlayableMediaTypes { get; set; } + public IReadOnlyList<string> PlayableMediaTypes { get; set; } - public GeneralCommandType[] SupportedCommands { get; set; } + public IReadOnlyList<GeneralCommandType> SupportedCommands { get; set; } public bool SupportsMediaControl { get; set; } From 40531db1aea0af90777c42275ec1cb55bb587030 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 21 Nov 2020 11:58:35 -0700 Subject: [PATCH 0481/1930] Add NullableEnumModelBinder and NullableEnumModelBinderProvider --- .../ModelBinders/NullableEnumModelBinder.cs | 47 +++++++++++++++++++ .../NullableEnumModelBinderProvider.cs | 27 +++++++++++ .../ApiServiceCollectionExtensions.cs | 3 ++ 3 files changed, 77 insertions(+) create mode 100644 Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs create mode 100644 Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs diff --git a/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs new file mode 100644 index 0000000000..5d296227e6 --- /dev/null +++ b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs @@ -0,0 +1,47 @@ +using System; +using System.ComponentModel; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.ModelBinders +{ + /// <summary> + /// Nullable enum model binder. + /// </summary> + public class NullableEnumModelBinder : IModelBinder + { + private readonly ILogger<NullableEnumModelBinder> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="NullableEnumModelBinder"/> class. + /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger{NullableEnumModelBinder}"/> interface.</param> + public NullableEnumModelBinder(ILogger<NullableEnumModelBinder> logger) + { + _logger = logger; + } + + /// <inheritdoc /> + public Task BindModelAsync(ModelBindingContext bindingContext) + { + var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0]; + var converter = TypeDescriptor.GetConverter(elementType); + if (valueProviderResult.Length != 0) + { + try + { + var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue); + bindingContext.Result = ModelBindingResult.Success(convertedValue); + } + catch (FormatException e) + { + _logger.LogWarning(e, "Error converting value."); + } + } + + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs b/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs new file mode 100644 index 0000000000..bc12ad05da --- /dev/null +++ b/Jellyfin.Api/ModelBinders/NullableEnumModelBinderProvider.cs @@ -0,0 +1,27 @@ +using System; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.ModelBinders +{ + /// <summary> + /// Nullable enum model binder provider. + /// </summary> + public class NullableEnumModelBinderProvider : IModelBinderProvider + { + /// <inheritdoc /> + public IModelBinder? GetBinder(ModelBinderProviderContext context) + { + var nullableType = Nullable.GetUnderlyingType(context.Metadata.ModelType); + if (nullableType == null || !nullableType.IsEnum) + { + // Type isn't nullable or isn't an enum. + return null; + } + + var logger = context.Services.GetRequiredService<ILogger<NullableEnumModelBinder>>(); + return new NullableEnumModelBinder(logger); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index cc98955df7..6cb88c9f73 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -17,6 +17,7 @@ using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Auth.RequiresElevationPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; +using Jellyfin.Api.ModelBinders; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -169,6 +170,8 @@ namespace Jellyfin.Server.Extensions opts.OutputFormatters.Add(new CssOutputFormatter()); opts.OutputFormatters.Add(new XmlOutputFormatter()); + + opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider()); }) // Clear app parts to avoid other assemblies being picked up From 5224200e8cb180f160f75ca7ffe9a121bcf993cf Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 19:50:40 +0000 Subject: [PATCH 0482/1930] Fixed baseurl in dlna. --- Emby.Dlna/Server/DescriptionXmlBuilder.cs | 18 +----------------- .../Controllers/DlnaServerController.cs | 2 +- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/Emby.Dlna/Server/DescriptionXmlBuilder.cs b/Emby.Dlna/Server/DescriptionXmlBuilder.cs index bca9e81cd0..09525aae4e 100644 --- a/Emby.Dlna/Server/DescriptionXmlBuilder.cs +++ b/Emby.Dlna/Server/DescriptionXmlBuilder.cs @@ -40,8 +40,6 @@ namespace Emby.Dlna.Server _serverId = serverId; } - private static bool EnableAbsoluteUrls => false; - public string GetXml() { var builder = new StringBuilder(); @@ -75,13 +73,6 @@ namespace Emby.Dlna.Server builder.Append("<minor>0</minor>"); builder.Append("</specVersion>"); - if (!EnableAbsoluteUrls) - { - builder.Append("<URLBase>") - .Append(SecurityElement.Escape(_serverAddress)) - .Append("</URLBase>"); - } - AppendDeviceInfo(builder); builder.Append("</root>"); @@ -257,14 +248,7 @@ namespace Emby.Dlna.Server return string.Empty; } - url = url.TrimStart('/'); - - url = "/dlna/" + _serverUdn + "/" + url; - - if (EnableAbsoluteUrls) - { - url = _serverAddress.TrimEnd('/') + url; - } + url = _serverAddress.TrimEnd('/') + "/dlna/" + _serverUdn + "/" + url.TrimStart('/'); return SecurityElement.Escape(url); } diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 4e6455eaa7..4fd9c2fbf6 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -252,7 +252,7 @@ namespace Jellyfin.Api.Controllers private string GetAbsoluteUri() { - return $"{Request.Scheme}://{Request.Host}{Request.Path}"; + return $"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}"; } private Task<ControlResponse> ProcessControlRequestInternalAsync(string id, Stream requestStream, IUpnpService service) From 23fa9533af2edd399e9e6c4021cce7322297e555 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:00:17 +0000 Subject: [PATCH 0483/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 0bd442f0b6..301dafb51d 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -476,7 +476,7 @@ namespace Jellyfin.Networking.Tests var intf = nm.GetBindInterface(source, out int? _); - Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(intf, result); } } } From ac03516f89e6ea95bafa1bd19968481ef526d4f8 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:00:37 +0000 Subject: [PATCH 0484/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 301dafb51d..c13053900d 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -90,7 +90,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); - Assert.True(!nm.IsInLocalNetwork(value)); + Assert.False(nm.IsInLocalNetwork(value)); } [Theory] From 5ac25364db9a90b46a84b7754e3121375ee5d5ba Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:01:01 +0000 Subject: [PATCH 0485/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index c13053900d..867120246b 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -1,6 +1,5 @@ using System; using System.Net; -using Emby.Dlna.PlayTo; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; From 13162184f41029436ab295b8d4b467c6909f71b9 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:01:58 +0000 Subject: [PATCH 0486/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 867120246b..6adce623f8 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -168,7 +168,7 @@ namespace Jellyfin.Networking.Tests // Test included, IP6. Collection<IPObject> nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc?.AsString(), result1, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(nc.AsString(), result1); // Test excluded, non IP6. nc = nm.CreateIPCollection(settings.Split(","), true); From b4e70328724c5e7a6b7fc52378beffc418578685 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:02:19 +0000 Subject: [PATCH 0487/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 6adce623f8..b75af51265 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -407,7 +407,7 @@ namespace Jellyfin.Networking.Tests result = ((IPNetAddress)resultObj[0]).ToString(true); var intf = nm.GetBindInterface(source, out int? _); - Assert.True(string.Equals(intf, result, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(intf, result); } } From acb79eb56a5b7f91dd8db3f50095f548310a8ad7 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:02:36 +0000 Subject: [PATCH 0488/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index b75af51265..945b87a03a 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -172,7 +172,7 @@ namespace Jellyfin.Networking.Tests // Test excluded, non IP6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc?.AsString(), result3, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(nc.AsString(), result3); conf.EnableIPV6 = false; nm.UpdateSettings(conf); From c14f468099e9994f6b83b8f1a7710b43833bf25b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:04:02 +0000 Subject: [PATCH 0489/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 945b87a03a..1893964394 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -183,7 +183,7 @@ namespace Jellyfin.Networking.Tests // Test excluded, including IPv6. nc = nm.CreateIPCollection(settings.Split(","), true); - Assert.True(string.Equals(nc?.AsString(), result4, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(nc.AsString(), result4); conf.EnableIPV6 = true; nm.UpdateSettings(conf); From e33200db71934b5d45a88571255428a0b992101e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:04:16 +0000 Subject: [PATCH 0490/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 1893964394..e8f07726c0 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -191,7 +191,7 @@ namespace Jellyfin.Networking.Tests // Test network addresses of collection. nc = nm.CreateIPCollection(settings.Split(","), false); nc = nc.AsNetworks(); - Assert.True(string.Equals(nc?.AsString(), result5, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(nc.AsString(), result5); } [Theory] From c3fa9d00ae392e79d90a2602a573dd56b71033b1 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:04:58 +0000 Subject: [PATCH 0491/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index e8f07726c0..3a8e2e65d7 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -226,7 +226,7 @@ namespace Jellyfin.Networking.Tests Collection<IPObject> nc1 = nm.CreateIPCollection(settings.Split(","), false); Collection<IPObject> nc2 = nm.CreateIPCollection(compare.Split(","), false); - Assert.True(nc1.Union(nc2).AsString() == result); + Assert.Equal(nc1.Union(nc2).AsString(), result); } [Theory] From 3f2c331755f48679d05bc09acf39882d7a574196 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:05:11 +0000 Subject: [PATCH 0492/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 3a8e2e65d7..78db84d911 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -68,7 +68,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.True(string.Equals(nm.GetInternalBindAddresses().AsString(), value, StringComparison.Ordinal)); + Assert.Equal(nm.GetInternalBindAddresses().AsString(), value); } [Theory] From 1e13627a944249dfd94e5a0befd943e726bf0f28 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:05:31 +0000 Subject: [PATCH 0493/1930] Update tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- .../NetworkTesting/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 78db84d911..f7fc9ebc68 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -179,7 +179,7 @@ namespace Jellyfin.Networking.Tests // Test included, non IP6. nc = nm.CreateIPCollection(settings.Split(","), false); - Assert.True(string.Equals(nc?.AsString(), result2, System.StringComparison.OrdinalIgnoreCase)); + Assert.Equal(nc.AsString(), result2); // Test excluded, including IPv6. nc = nm.CreateIPCollection(settings.Split(","), true); From dc1ad3fe2aa1061157b037f1e986b590e4027953 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 20:31:24 +0000 Subject: [PATCH 0494/1930] Better named tests methods. --- .../NetworkTesting/NetworkParseTests.cs | 56 +++++++++++++++---- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index f7fc9ebc68..56d11ef521 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -51,6 +51,12 @@ namespace Jellyfin.Networking.Tests return (IConfigurationManager)configManager.Object; } + /// <summary> + /// Checks the ability to ignore interfaces + /// </summary> + /// <param name="interfaces">Mock network setup, in the format (IP address, interface index, interface name) : .... </param> + /// <param name="lan">LAN addresses.</param> + /// <param name="value">Bind addresses that are excluded.</param> [Theory] [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] @@ -71,9 +77,14 @@ namespace Jellyfin.Networking.Tests Assert.Equal(nm.GetInternalBindAddresses().AsString(), value); } + /// <summary> + /// Check that the value given is in the network provided. + /// </summary> + /// <param name="network">Network address.</param> + /// <param name="value">Value to check.</param> [Theory] [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")] - public void TextIsInNetwork(string network, string value) + public void IsInNetwork(string network, string value) { if (network == null) { @@ -92,6 +103,10 @@ namespace Jellyfin.Networking.Tests Assert.False(nm.IsInLocalNetwork(value)); } + /// <summary> + /// Checks IP address formats. + /// </summary> + /// <param name="address"></param> [Theory] [InlineData("127.0.0.1")] [InlineData("127.0.0.1:123")] @@ -105,21 +120,36 @@ namespace Jellyfin.Networking.Tests [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] [InlineData("192.168.1.2/255.255.255.0")] [InlineData("192.168.1.2/24")] - public void TestCollectionCreation(string address) + public void ValidIPStrings(string address) { Assert.True(TryParse(address, out _)); } + + /// <summary> + /// All should be invalid address strings. + /// </summary> + /// <param name="address">Invalid address strings.</param> [Theory] [InlineData("256.128.0.0.0.1")] [InlineData("127.0.0.1#")] [InlineData("localhost!")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] - public void TestInvalidCollectionCreation(string address) + public void InvalidAddressString(string address) { Assert.False(TryParse(address, out _)); } + + /// <summary> + /// Test collection parsing. + /// </summary> + /// <param name="settings">Collection to parse.</param> + /// <param name="result1">Included addresses from the collection.</param> + /// <param name="result2">Included IP4 addresses from the collection.</param> + /// <param name="result3">Excluded addresses from the collection.</param> + /// <param name="result4">Excluded IP4 addresses from the collection.</param> + /// <param name="result5">Network addresses of the collection.</param> [Theory] [InlineData("127.0.0.1#", "[]", @@ -166,22 +196,22 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); - // Test included, IP6. + // Test included. Collection<IPObject> nc = nm.CreateIPCollection(settings.Split(","), false); Assert.Equal(nc.AsString(), result1); - // Test excluded, non IP6. + // Test excluded. nc = nm.CreateIPCollection(settings.Split(","), true); Assert.Equal(nc.AsString(), result3); conf.EnableIPV6 = false; nm.UpdateSettings(conf); - // Test included, non IP6. + // Test IP4 included. nc = nm.CreateIPCollection(settings.Split(","), false); Assert.Equal(nc.AsString(), result2); - // Test excluded, including IPv6. + // Test IP4 excluded. nc = nm.CreateIPCollection(settings.Split(","), true); Assert.Equal(nc.AsString(), result4); @@ -194,6 +224,12 @@ namespace Jellyfin.Networking.Tests Assert.Equal(nc.AsString(), result5); } + /// <summary> + /// Union two collections. + /// </summary> + /// <param name="settings">Source.</param> + /// <param name="compare">Destination.</param> + /// <param name="result">Result.</param> [Theory] [InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")] [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")] @@ -293,7 +329,7 @@ namespace Jellyfin.Networking.Tests [InlineData("10.10.10.0/24", "10.10.10.1/32")] [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")] - public void TestSubnets(string network, string ip) + public void TestSubnetContains(string network, string ip) { Assert.True(TryParse(network, out IPObject? networkObj)); Assert.True(TryParse(ip, out IPObject? ipObj)); @@ -307,7 +343,7 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")] [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")] - public void TestMatches(string source, string dest, string result) + public void TestCollectionEquality(string source, string dest, string result) { if (source == null) { @@ -353,7 +389,7 @@ namespace Jellyfin.Networking.Tests [Theory] - // Testing bind interfaces. These are set for my system so won't work elsewhere. + // Testing bind interfaces. // On my system eth16 is internal, eth11 external (Windows defines the indexes). // // This test is to replicate how DNLA requests work throughout the system. From 79855a76b1eca5c6aee3afc596f1569167862dd0 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 23:21:15 +0000 Subject: [PATCH 0495/1930] Update MetadataService.cs removed async line 232 --- MediaBrowser.Providers/Manager/MetadataService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 3542f90e1e..ba59303232 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -229,7 +229,7 @@ namespace MediaBrowser.Providers.Manager await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false); } - private async Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) + private Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) { var personsToSave = new List<BaseItem>(); From d3b0080a27152337d26e2d94d8f3421d314fbf8b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 23:29:52 +0000 Subject: [PATCH 0496/1930] Update MetadataService.cs added return Task.CompletedTask; --- MediaBrowser.Providers/Manager/MetadataService.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index ba59303232..6dbce3067e 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -272,6 +272,7 @@ namespace MediaBrowser.Providers.Manager LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload); LibraryManager.CreateItems(personsToSave, null, CancellationToken.None); + return Task.CompletedTask; } protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) From 969b9e2a18aa76fd0b2915960ea799a12a9605a0 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 21 Nov 2020 23:33:41 +0000 Subject: [PATCH 0497/1930] Update ImageFetcherPostScanTask.cs --- Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs index b18a0c1a80..d4e790c9a6 100644 --- a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs +++ b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.Library { await _libraryManager.UpdateImagesAsync(queuedItem.item, queuedItem.updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); } - catch (HttpException ex) + catch (Exception ex) { _logger.LogError(ex, "Failed to fetch images for {Type} item with id {ItemId}", itemType, itemId); } From c1db8869f06105b13f93f15d12061ada523dbb78 Mon Sep 17 00:00:00 2001 From: hoanghuy309 <hoanghuy309@gmail.com> Date: Sun, 22 Nov 2020 04:00:14 +0000 Subject: [PATCH 0498/1930] Translated using Weblate (Vietnamese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/vi/ --- Emby.Server.Implementations/Localization/Core/vi.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index 0549995c8c..79bc4800b0 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -16,7 +16,7 @@ "Albums": "Albums", "Artists": "Các Nghệ Sĩ", "TaskDownloadMissingSubtitlesDescription": "Tìm kiếm phụ đề bị thiếu trên Internet dựa trên cấu hình dữ liệu mô tả.", - "TaskDownloadMissingSubtitles": "Tải xuống phụ đề bị thiếu", + "TaskDownloadMissingSubtitles": "Tải Xuống Phụ Đề Bị Thiếu", "TaskRefreshChannelsDescription": "Làm mới thông tin kênh internet.", "TaskRefreshChannels": "Làm Mới Kênh", "TaskCleanTranscodeDescription": "Xóa các tệp chuyển mã cũ hơn một ngày.", @@ -24,11 +24,11 @@ "TaskUpdatePluginsDescription": "Tải xuống và cài đặt các bản cập nhật cho các plugin được định cấu hình để cập nhật tự động.", "TaskUpdatePlugins": "Cập Nhật Plugins", "TaskRefreshPeopleDescription": "Cập nhật thông tin chi tiết cho diễn viên và đạo diễn trong thư viện phương tiện của bạn.", - "TaskRefreshPeople": "Làm mới Người dùng", + "TaskRefreshPeople": "Làm Mới Người Dùng", "TaskCleanLogsDescription": "Xóa tập tin nhật ký cũ hơn {0} ngày.", - "TaskCleanLogs": "Làm sạch nhật ký", - "TaskRefreshLibraryDescription": "Quét thư viện phương tiện của bạn để tìm các tệp mới và làm mới thông tin chi tiết.", - "TaskRefreshLibrary": "Quét Thư viện Phương tiện", + "TaskCleanLogs": "Làm Sạch Thư Mục Nhật Ký", + "TaskRefreshLibraryDescription": "Quét thư viện phương tiện của bạn để tìm tệp mới và làm mới dữ liệu mô tả.", + "TaskRefreshLibrary": "Quét Thư Viện Phương Tiện", "TaskRefreshChapterImagesDescription": "Tạo hình thu nhỏ cho video có các phân cảnh.", "TaskRefreshChapterImages": "Trích Xuất Ảnh Phân Cảnh", "TaskCleanCacheDescription": "Xóa các tệp cache không còn cần thiết của hệ thống.", From a34fca6f8e4ded6c36495f2937c80baee15e09c3 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 22 Nov 2020 11:40:50 +0000 Subject: [PATCH 0499/1930] Update Startup.cs --- Jellyfin.Server/Startup.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index a615e9aeb9..8ddfdc1c85 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -4,6 +4,7 @@ using Jellyfin.Networking.Configuration; using Jellyfin.Server.Extensions; using Jellyfin.Server.Implementations; using Jellyfin.Server.Middleware; +using Jellyfin.Server.Networking; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -122,7 +123,7 @@ namespace Jellyfin.Server mainApp.UseCors(); - if (_serverConfigurationManager.Configuration.RequireHttps + if (_serverConfigurationManager.GetNetworkConfiguration().RequireHttps && _serverApplicationHost.ListenWithHttps) { mainApp.UseHttpsRedirection(); From dfee591c2aff3174ef8eb3a664c065dd475a119f Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 22 Nov 2020 12:06:39 +0000 Subject: [PATCH 0500/1930] Update Startup.cs Late night --- Jellyfin.Server/Startup.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 8ddfdc1c85..4ffcb940ff 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -4,7 +4,6 @@ using Jellyfin.Networking.Configuration; using Jellyfin.Server.Extensions; using Jellyfin.Server.Implementations; using Jellyfin.Server.Middleware; -using Jellyfin.Server.Networking; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; From fe3e22be98353eebb67be2fa5422d0724e5056f0 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sun, 22 Nov 2020 13:11:05 +0000 Subject: [PATCH 0501/1930] Null Pointer --- .../Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 3984e49537..bcf9459ef8 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -129,6 +129,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken) .ConfigureAwait(false); + if (movieResult == null) + { + return new MetadataResult<Movie>(); + } + var movie = new Movie { Name = movieResult.Title ?? movieResult.OriginalTitle, @@ -266,7 +271,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies } } - if (movieResult.Videos?.Results != null) { var trailers = new List<MediaUrl>(); From 812300ad333a8ee844ba1c5e7facbe35c98f983c Mon Sep 17 00:00:00 2001 From: Orry Verducci <orry@orryverducci.co.uk> Date: Sun, 22 Nov 2020 16:54:41 +0000 Subject: [PATCH 0502/1930] Revert "Fix frame rate probing for interlaced MKV files" This reverts commit 84fd5a09532bd1e854ec3745609f845aa7098da2. --- .../Probing/ProbeResultNormalizer.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index cdeefbbbdf..22537a4d95 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -666,16 +666,6 @@ namespace MediaBrowser.MediaEncoding.Probing stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate); stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate); - // Interlaced video streams in Matroska containers return the field rate instead of the frame rate - // as both the average and real frame rate, so we half the returned frame rates to get the correct values - // - // https://gitlab.com/mbunkus/mkvtoolnix/-/wikis/Wrong-frame-rate-displayed - if (stream.IsInterlaced && formatInfo.FormatName.Contains("matroska", StringComparison.OrdinalIgnoreCase)) - { - stream.AverageFrameRate /= 2; - stream.RealFrameRate /= 2; - } - if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)) { From c5f5633ec6b5a18ae5d7bd30a8dd27671b83b92a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 22 Nov 2020 12:35:45 -0700 Subject: [PATCH 0503/1930] Handle invalid plugins --- .../Updates/InstallationManager.cs | 61 ++++++++++--------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 7a071c071a..f2c096b8af 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -6,13 +6,15 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; -using System.Runtime.Serialization; +using System.Net.Http.Json; using System.Security.Cryptography; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -21,8 +23,6 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Events; using MediaBrowser.Controller.Events.Updates; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Net; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Updates; using Microsoft.Extensions.Logging; @@ -40,9 +40,9 @@ namespace Emby.Server.Implementations.Updates private readonly IApplicationPaths _appPaths; private readonly IEventManager _eventManager; private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _jsonSerializer; private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; + private readonly JsonSerializerOptions _jsonSerializerOptions; /// <summary> /// Gets the application host. @@ -70,7 +70,6 @@ namespace Emby.Server.Implementations.Updates IApplicationPaths appPaths, IEventManager eventManager, IHttpClientFactory httpClientFactory, - IJsonSerializer jsonSerializer, IServerConfigurationManager config, IFileSystem fileSystem, IZipClient zipClient) @@ -83,10 +82,10 @@ namespace Emby.Server.Implementations.Updates _appPaths = appPaths; _eventManager = eventManager; _httpClientFactory = httpClientFactory; - _jsonSerializer = jsonSerializer; _config = config; _fileSystem = fileSystem; _zipClient = zipClient; + _jsonSerializerOptions = JsonDefaults.GetOptions(); } /// <inheritdoc /> @@ -97,31 +96,29 @@ namespace Emby.Server.Implementations.Updates { try { - using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetAsync(new Uri(manifest), cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - - try + var packages = await _httpClientFactory.CreateClient(NamedClient.Default) + .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); + if (packages == null) { - var package = await _jsonSerializer.DeserializeFromStreamAsync<IList<PackageInfo>>(stream).ConfigureAwait(false); - - // Store the repository and repository url with each version, as they may be spread apart. - foreach (var entry in package) - { - foreach (var ver in entry.versions) - { - ver.repositoryName = manifestName; - ver.repositoryUrl = manifest; - } - } - - return package; - } - catch (SerializationException ex) - { - _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest); return Array.Empty<PackageInfo>(); } + + // Store the repository and repository url with each version, as they may be spread apart. + foreach (var entry in packages) + { + foreach (var ver in entry.versions) + { + ver.repositoryName = manifestName; + ver.repositoryUrl = manifest; + } + } + + return packages; + } + catch (JsonException ex) + { + _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest); + return Array.Empty<PackageInfo>(); } catch (UriFormatException ex) { @@ -187,7 +184,13 @@ namespace Emby.Server.Implementations.Updates // Where repositories have the same content, the details of the first is taken. foreach (var package in await GetPackages(repository.Name, repository.Url, cancellationToken).ConfigureAwait(true)) { - var existing = FilterPackages(result, package.name, Guid.Parse(package.guid)).FirstOrDefault(); + if (!Guid.TryParse(package.guid, out var packageGuid)) + { + // Package doesn't have a valid GUID, skip. + continue; + } + + var existing = FilterPackages(result, package.name, packageGuid).FirstOrDefault(); if (existing != null) { // Assumption is both lists are ordered, so slot these into the correct place. From 2aefe9ed5a32a91c6e089456a082471f2c51b94b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 22 Nov 2020 14:17:42 -0700 Subject: [PATCH 0504/1930] Only trim file name if folder name is shorter --- Emby.Naming/Video/VideoListResolver.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 5f83355c8f..4c33941296 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -226,8 +226,11 @@ namespace Emby.Naming.Video { testFilename = cleanName.ToString(); } + else if (folderName.Length <= testFilename.Length) + { + testFilename = testFilename.Substring(folderName.Length).Trim(); + } - testFilename = testFilename.Substring(folderName.Length).Trim(); return string.IsNullOrEmpty(testFilename) || testFilename[0].Equals('-') || testFilename[0].Equals('_') From 20251e670f485dde010de5ff63454cacb2f6ba5f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 22 Nov 2020 14:39:34 -0700 Subject: [PATCH 0505/1930] Fix tests --- Emby.Naming/Video/VideoListResolver.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 4c33941296..fd16774739 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -226,7 +226,8 @@ namespace Emby.Naming.Video { testFilename = cleanName.ToString(); } - else if (folderName.Length <= testFilename.Length) + + if (folderName.Length <= testFilename.Length) { testFilename = testFilename.Substring(folderName.Length).Trim(); } From d88504c1d6b763e1438678f673a2f62de8d7c10f Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 16:47:59 -0500 Subject: [PATCH 0506/1930] Set systemctl enabled on Jellyfin service This was not set for Fedora; I do not recall if this was just an oversight or was explicitly removed in the past; open to feedback there. Reported in the LUP Bug-A-Thon --- fedora/jellyfin.spec | 3 +++ 1 file changed, 3 insertions(+) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 13305488e2..74fe5bd292 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -127,6 +127,9 @@ if [ $1 -gt 1 ] ; then if [ "${service_state}" = "active" ]; then systemctl start jellyfin.service fi + if [ "${service_state}" != "active" ]; then + systemctl enable jellyfin.service + fi fi %systemd_post jellyfin.service From be4e485bd30f19811392ee1ddcc58df2d3f26504 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 16:58:07 -0500 Subject: [PATCH 0507/1930] Make use of the $1 flag to set installed only --- fedora/jellyfin.spec | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 74fe5bd292..82ff947b3f 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -127,7 +127,8 @@ if [ $1 -gt 1 ] ; then if [ "${service_state}" = "active" ]; then systemctl start jellyfin.service fi - if [ "${service_state}" != "active" ]; then + if [ $1 -eq 1 ]; then + # On fresh install only, enable the jellyfin.service unit systemctl enable jellyfin.service fi fi From 5f135a4b469a1e8dbbc0e8dcfdb1d61496a81fb5 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 17:01:13 -0500 Subject: [PATCH 0508/1930] Use --now to the enable to start too --- fedora/jellyfin.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 82ff947b3f..4f4a301876 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -129,7 +129,7 @@ if [ $1 -gt 1 ] ; then fi if [ $1 -eq 1 ]; then # On fresh install only, enable the jellyfin.service unit - systemctl enable jellyfin.service + systemctl enable --now jellyfin.service fi fi %systemd_post jellyfin.service From 1079ddb46cceea1af45d5e00cdaa4b92e2a306f1 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 17:12:29 -0500 Subject: [PATCH 0509/1930] Run explicit service start if restart failed Should solve the occasional bugs with the restart in the WebUI. Sometimes the service stops and then doesn't start again; this will run an explicit start action afterwards. If this doesn't fix it I'm certain there would be more tweaking that can be done. --- debian/bin/restart.sh | 6 +++--- fedora/restart.sh | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/debian/bin/restart.sh b/debian/bin/restart.sh index 9b64b6d728..e499bf3369 100755 --- a/debian/bin/restart.sh +++ b/debian/bin/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin" | at now + echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin" | at now ;; 'service') - echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart" | at now + echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start" | at now ;; 'sysv') - echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart" | at now + echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start" | at now ;; esac exit 0 diff --git a/fedora/restart.sh b/fedora/restart.sh index 9e53efecd0..e499bf3369 100755 --- a/fedora/restart.sh +++ b/fedora/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin" | at now + echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin" | at now ;; 'service') - echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart" | at now + echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start" | at now ;; 'sysv') - echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart" | at now + echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start" | at now ;; esac exit 0 From 97665c947865973936863edc21717c1ae5df6193 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 17:19:39 -0500 Subject: [PATCH 0510/1930] Remove the `at now` hack --- debian/bin/restart.sh | 6 +++--- fedora/restart.sh | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/debian/bin/restart.sh b/debian/bin/restart.sh index e499bf3369..4436ea991a 100755 --- a/debian/bin/restart.sh +++ b/debian/bin/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin" | at now + sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin ;; 'service') - echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start" | at now + sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start ;; 'sysv') - echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start" | at now + sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start ;; esac exit 0 diff --git a/fedora/restart.sh b/fedora/restart.sh index e499bf3369..4436ea991a 100755 --- a/fedora/restart.sh +++ b/fedora/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - echo "sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin" | at now + sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin ;; 'service') - echo "sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start" | at now + sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start ;; 'sysv') - echo "sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start" | at now + sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start ;; esac exit 0 From 6de79e03a2a68a6684dab9d298ca7224da0088b0 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 18:32:16 -0500 Subject: [PATCH 0511/1930] Go back to at with lower sleep and start --- debian/bin/restart.sh | 6 +++--- fedora/restart.sh | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/debian/bin/restart.sh b/debian/bin/restart.sh index 4436ea991a..34fce06708 100755 --- a/debian/bin/restart.sh +++ b/debian/bin/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin + echo "sleep 0.5; /usr/bin/sudo $( which systemctl ) start jellyfin" | at now ;; 'service') - sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start + echo "sleep 0.5; /usr/bin/sudo $( which service ) jellyfin start" | at now ;; 'sysv') - sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start + echo "sleep 0.5; /usr/bin/sudo /etc/init.d/jellyfin start" | at now ;; esac exit 0 diff --git a/fedora/restart.sh b/fedora/restart.sh index 4436ea991a..34fce06708 100755 --- a/fedora/restart.sh +++ b/fedora/restart.sh @@ -24,13 +24,13 @@ cmd="$( get_service_command )" echo "Detected service control platform '$cmd'; using it to restart Jellyfin..." case $cmd in 'systemctl') - sleep 2; /usr/bin/sudo $( which systemctl ) restart jellyfin || /usr/bin/sudo $( which systemctl ) start jellyfin + echo "sleep 0.5; /usr/bin/sudo $( which systemctl ) start jellyfin" | at now ;; 'service') - sleep 2; /usr/bin/sudo $( which service ) jellyfin restart || /usr/bin/sudo $( which service ) jellyfin start + echo "sleep 0.5; /usr/bin/sudo $( which service ) jellyfin start" | at now ;; 'sysv') - sleep 2; /usr/bin/sudo /etc/init.d/jellyfin restart || /usr/bin/sudo /etc/init.d/jellyfin start + echo "sleep 0.5; /usr/bin/sudo /etc/init.d/jellyfin start" | at now ;; esac exit 0 From 91dd95faa3d3cd108c2cfc7a26af792f37e937be Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sun, 22 Nov 2020 18:32:34 -0500 Subject: [PATCH 0512/1930] Add at to the dependencies on Fedora (as in Deb) --- fedora/jellyfin.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 13305488e2..197126ee56 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -40,7 +40,7 @@ Jellyfin is a free software media system that puts you in control of managing an Summary: The Free Software Media System Server backend Requires(pre): shadow-utils Requires: ffmpeg -Requires: libcurl, fontconfig, freetype, openssl, glibc libicu +Requires: libcurl, fontconfig, freetype, openssl, glibc, libicu, at %description server The Jellyfin media server backend. From 3bff1ff8a2e7e3e2fad69c9242165f1ae9d9fd50 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 22 Nov 2020 18:46:55 -0700 Subject: [PATCH 0513/1930] Fix namespace and add attribute --- Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs index ac1259ef29..e58095536a 100644 --- a/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs +++ b/Jellyfin.Api/Models/SessionDtos/ClientCapabilitiesDto.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; +using System.Text.Json.Serialization; using MediaBrowser.Common.Json.Converters; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Session; -using Newtonsoft.Json; namespace Jellyfin.Api.Models.SessionDtos { @@ -15,6 +15,7 @@ namespace Jellyfin.Api.Models.SessionDtos /// <summary> /// Gets or sets the list of playable media types. /// </summary> + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] public IReadOnlyList<string> PlayableMediaTypes { get; set; } = Array.Empty<string>(); /// <summary> From 5de8c249a060dc9a923c42aa544313713ce6d8ed Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 23 Nov 2020 08:18:07 -0700 Subject: [PATCH 0514/1930] Don't send activity event if notification type is null --- .../Events/Consumers/Session/PlaybackStopLogger.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs index 51a882c143..a0bad29e9b 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs @@ -59,6 +59,12 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session var user = eventArgs.Users[0]; + var notificationType = GetPlaybackStoppedNotificationType(item.MediaType); + if (notificationType == null) + { + return; + } + await _activityManager.CreateAsync(new ActivityLog( string.Format( CultureInfo.InvariantCulture, @@ -66,7 +72,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session user.Username, GetItemName(item), eventArgs.DeviceName), - GetPlaybackStoppedNotificationType(item.MediaType), + notificationType, user.Id)) .ConfigureAwait(false); } From f336d20b065c873f0f321c7a1cec565f5a77a806 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 23 Nov 2020 09:49:42 -0700 Subject: [PATCH 0515/1930] Fix sending PlaybackInfo --- .../Controllers/MediaInfoController.cs | 56 ++++++++---- .../Models/MediaInfoDtos/PlaybackInfoDto.cs | 86 +++++++++++++++++++ 2 files changed, 123 insertions(+), 19 deletions(-) create mode 100644 Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index b42e6686ec..cab1aa19cd 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -81,6 +81,9 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Gets live playback media info for an item. /// </summary> + /// <remarks> + /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence. + /// </remarks> /// <param name="itemId">The item id.</param> /// <param name="userId">The user id.</param> /// <param name="maxStreamingBitrate">The maximum streaming bitrate.</param> @@ -90,13 +93,13 @@ namespace Jellyfin.Api.Controllers /// <param name="maxAudioChannels">The maximum number of audio channels.</param> /// <param name="mediaSourceId">The media source id.</param> /// <param name="liveStreamId">The livestream id.</param> - /// <param name="deviceProfile">The device profile.</param> /// <param name="autoOpenLiveStream">Whether to auto open the livestream.</param> /// <param name="enableDirectPlay">Whether to enable direct play. Default: true.</param> /// <param name="enableDirectStream">Whether to enable direct stream. Default: true.</param> /// <param name="enableTranscoding">Whether to enable transcoding. Default: true.</param> /// <param name="allowVideoStreamCopy">Whether to allow to copy the video stream. Default: true.</param> /// <param name="allowAudioStreamCopy">Whether to allow to copy the audio stream. Default: true.</param> + /// <param name="playbackInfoDto">The playback info.</param> /// <response code="200">Playback info returned.</response> /// <returns>A <see cref="Task"/> containing a <see cref="PlaybackInfoResponse"/> with the playback info.</returns> [HttpPost("Items/{itemId}/PlaybackInfo")] @@ -111,18 +114,17 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? maxAudioChannels, [FromQuery] string? mediaSourceId, [FromQuery] string? liveStreamId, - [FromBody] DeviceProfileDto? deviceProfile, - [FromQuery] bool autoOpenLiveStream = false, - [FromQuery] bool enableDirectPlay = true, - [FromQuery] bool enableDirectStream = true, - [FromQuery] bool enableTranscoding = true, - [FromQuery] bool allowVideoStreamCopy = true, - [FromQuery] bool allowAudioStreamCopy = true) + [FromQuery] bool? autoOpenLiveStream, + [FromQuery] bool? enableDirectPlay, + [FromQuery] bool? enableDirectStream, + [FromQuery] bool? enableTranscoding, + [FromQuery] bool? allowVideoStreamCopy, + [FromQuery] bool? allowAudioStreamCopy, + [FromBody] PlaybackInfoDto? playbackInfoDto) { var authInfo = _authContext.GetAuthorizationInfo(Request); - var profile = deviceProfile?.DeviceProfile; - + var profile = playbackInfoDto?.DeviceProfile?.DeviceProfile; _logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", profile); if (profile == null) @@ -134,6 +136,22 @@ namespace Jellyfin.Api.Controllers } } + // Copy params from posted body + userId ??= playbackInfoDto?.UserId; + maxStreamingBitrate ??= playbackInfoDto?.MaxStreamingBitrate; + startTimeTicks ??= playbackInfoDto?.StartTimeTicks; + audioStreamIndex ??= playbackInfoDto?.AudioStreamIndex; + subtitleStreamIndex ??= playbackInfoDto?.SubtitleStreamIndex; + maxAudioChannels ??= playbackInfoDto?.MaxAudioChannels; + mediaSourceId ??= playbackInfoDto?.MediaSourceId; + liveStreamId ??= playbackInfoDto?.LiveStreamId; + autoOpenLiveStream ??= playbackInfoDto?.AutoOpenLiveStream ?? false; + enableDirectPlay ??= playbackInfoDto?.EnableDirectPlay ?? true; + enableDirectStream ??= playbackInfoDto?.EnableDirectStream ?? true; + enableTranscoding ??= playbackInfoDto?.EnableTranscoding ?? true; + allowVideoStreamCopy ??= playbackInfoDto?.AllowVideoStreamCopy ?? true; + allowAudioStreamCopy ??= playbackInfoDto?.AllowAudioStreamCopy ?? true; + var info = await _mediaInfoHelper.GetPlaybackInfo( itemId, userId, @@ -161,18 +179,18 @@ namespace Jellyfin.Api.Controllers maxAudioChannels, info!.PlaySessionId!, userId ?? Guid.Empty, - enableDirectPlay, - enableDirectStream, - enableTranscoding, - allowVideoStreamCopy, - allowAudioStreamCopy, + enableDirectPlay.Value, + enableDirectStream.Value, + enableTranscoding.Value, + allowVideoStreamCopy.Value, + allowAudioStreamCopy.Value, Request.HttpContext.GetNormalizedRemoteIp()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); } - if (autoOpenLiveStream) + if (autoOpenLiveStream.Value) { var mediaSource = string.IsNullOrWhiteSpace(mediaSourceId) ? info.MediaSources[0] : info.MediaSources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.Ordinal)); @@ -183,9 +201,9 @@ namespace Jellyfin.Api.Controllers new LiveStreamRequest { AudioStreamIndex = audioStreamIndex, - DeviceProfile = deviceProfile?.DeviceProfile, - EnableDirectPlay = enableDirectPlay, - EnableDirectStream = enableDirectStream, + DeviceProfile = playbackInfoDto?.DeviceProfile?.DeviceProfile, + EnableDirectPlay = enableDirectPlay.Value, + EnableDirectStream = enableDirectStream.Value, ItemId = itemId, MaxAudioChannels = maxAudioChannels, MaxStreamingBitrate = maxStreamingBitrate, diff --git a/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs new file mode 100644 index 0000000000..818f78b529 --- /dev/null +++ b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs @@ -0,0 +1,86 @@ +using System; +using Jellyfin.Api.Models.VideoDtos; + +namespace Jellyfin.Api.Models.MediaInfoDtos +{ + /// <summary> + /// Plabyback info dto. + /// </summary> + public class PlaybackInfoDto + { + /// <summary> + /// Gets or sets the playback userId. + /// </summary> + public Guid? UserId { get; set; } + + /// <summary> + /// Gets or sets the max streaming bitrate. + /// </summary> + public int? MaxStreamingBitrate { get; set; } + + /// <summary> + /// Gets or sets the start time in ticks. + /// </summary> + public long? StartTimeTicks { get; set; } + + /// <summary> + /// Gets or sets the audio stream index. + /// </summary> + public int? AudioStreamIndex { get; set; } + + /// <summary> + /// Gets or sets the subtitle stream index. + /// </summary> + public int? SubtitleStreamIndex { get; set; } + + /// <summary> + /// Gets or sets the max audio channels. + /// </summary> + public int? MaxAudioChannels { get; set; } + + /// <summary> + /// Gets or sets the media source id. + /// </summary> + public string? MediaSourceId { get; set; } + + /// <summary> + /// Gets or sets the live stream id. + /// </summary> + public string? LiveStreamId { get; set; } + + /// <summary> + /// Gets or sets the device profile. + /// </summary> + public DeviceProfileDto? DeviceProfile { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable direct play. + /// </summary> + public bool? EnableDirectPlay { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable direct stream. + /// </summary> + public bool? EnableDirectStream { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable transcoding. + /// </summary> + public bool? EnableTranscoding { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable video stream copy. + /// </summary> + public bool? AllowVideoStreamCopy { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to allow audio stream copy. + /// </summary> + public bool? AllowAudioStreamCopy { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to auto open the live stream. + /// </summary> + public bool? AutoOpenLiveStream { get; set; } + } +} \ No newline at end of file From fafddfc45eed4e76c4072167428b43d2ed026bcd Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 23 Nov 2020 09:51:24 -0700 Subject: [PATCH 0516/1930] Add TODO notice --- Jellyfin.Api/Controllers/MediaInfoController.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index cab1aa19cd..c03a69cb9c 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -137,6 +137,7 @@ namespace Jellyfin.Api.Controllers } // Copy params from posted body + // TODO clean up when breaking API compatibility. userId ??= playbackInfoDto?.UserId; maxStreamingBitrate ??= playbackInfoDto?.MaxStreamingBitrate; startTimeTicks ??= playbackInfoDto?.StartTimeTicks; From 1dafd70f5141c1fa8fefa72dd97399f51df4d116 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 23 Nov 2020 10:50:18 -0700 Subject: [PATCH 0517/1930] Don't nest DeviceProfile --- Jellyfin.Api/Controllers/MediaInfoController.cs | 5 ++--- .../Models/MediaInfoDtos/PlaybackInfoDto.cs | 4 ++-- Jellyfin.Api/Models/VideoDtos/DeviceProfileDto.cs | 15 --------------- 3 files changed, 4 insertions(+), 20 deletions(-) delete mode 100644 Jellyfin.Api/Models/VideoDtos/DeviceProfileDto.cs diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index c03a69cb9c..a76dc057a0 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -8,7 +8,6 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.MediaInfoDtos; -using Jellyfin.Api.Models.VideoDtos; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; @@ -124,7 +123,7 @@ namespace Jellyfin.Api.Controllers { var authInfo = _authContext.GetAuthorizationInfo(Request); - var profile = playbackInfoDto?.DeviceProfile?.DeviceProfile; + var profile = playbackInfoDto?.DeviceProfile; _logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", profile); if (profile == null) @@ -202,7 +201,7 @@ namespace Jellyfin.Api.Controllers new LiveStreamRequest { AudioStreamIndex = audioStreamIndex, - DeviceProfile = playbackInfoDto?.DeviceProfile?.DeviceProfile, + DeviceProfile = playbackInfoDto?.DeviceProfile, EnableDirectPlay = enableDirectPlay.Value, EnableDirectStream = enableDirectStream.Value, ItemId = itemId, diff --git a/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs index 818f78b529..2cfdba507e 100644 --- a/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs +++ b/Jellyfin.Api/Models/MediaInfoDtos/PlaybackInfoDto.cs @@ -1,5 +1,5 @@ using System; -using Jellyfin.Api.Models.VideoDtos; +using MediaBrowser.Model.Dlna; namespace Jellyfin.Api.Models.MediaInfoDtos { @@ -51,7 +51,7 @@ namespace Jellyfin.Api.Models.MediaInfoDtos /// <summary> /// Gets or sets the device profile. /// </summary> - public DeviceProfileDto? DeviceProfile { get; set; } + public DeviceProfile? DeviceProfile { get; set; } /// <summary> /// Gets or sets a value indicating whether to enable direct play. diff --git a/Jellyfin.Api/Models/VideoDtos/DeviceProfileDto.cs b/Jellyfin.Api/Models/VideoDtos/DeviceProfileDto.cs deleted file mode 100644 index db55dc34b5..0000000000 --- a/Jellyfin.Api/Models/VideoDtos/DeviceProfileDto.cs +++ /dev/null @@ -1,15 +0,0 @@ -using MediaBrowser.Model.Dlna; - -namespace Jellyfin.Api.Models.VideoDtos -{ - /// <summary> - /// Device profile dto. - /// </summary> - public class DeviceProfileDto - { - /// <summary> - /// Gets or sets device profile. - /// </summary> - public DeviceProfile? DeviceProfile { get; set; } - } -} From 41b3a7869e7f5f6491b7938a499f1e2ccb00b076 Mon Sep 17 00:00:00 2001 From: Antonio Sarro <sarroantonio1999@gmail.com> Date: Mon, 23 Nov 2020 16:43:39 +0000 Subject: [PATCH 0518/1930] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 9e37ddc27c..110f8043d7 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Libreria", "TasksMaintenanceCategory": "Manutenzione", "TaskCleanActivityLog": "Attività di Registro Completate", - "TaskCleanActivityLogDescription": "Elimina gli inserimenti nel registro delle attività più vecchie dell’età configurata." + "TaskCleanActivityLogDescription": "Elimina gli inserimenti nel registro delle attività più vecchie dell’età configurata.", + "Undefined": "Non Definito", + "Forced": "Forzato", + "Default": "Predefinito" } From c4925ad70bd84477bd1e8df59de3db1196432fc2 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 23 Nov 2020 16:07:15 -0700 Subject: [PATCH 0519/1930] Serialize Guid.Empty to null --- .../Json/Converters/JsonGuidConverter.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs index d35a761f35..54325a02b0 100644 --- a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs @@ -15,6 +15,15 @@ namespace MediaBrowser.Common.Json.Converters /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) - => writer.WriteStringValue(value); + { + if (value == Guid.Empty) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value); + } + } } } From 6676ca4d1b6f8ba2c3582ab916ea9e2f88afae65 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 24 Nov 2020 05:06:36 +0000 Subject: [PATCH 0520/1930] Remove ResourceFileManager (#4567) --- .../ApplicationHost.cs | 1 - .../ResourceFileManager.cs | 45 ------------------- .../IResourceFileManager.cs | 9 ---- 3 files changed, 55 deletions(-) delete mode 100644 Emby.Server.Implementations/ResourceFileManager.cs delete mode 100644 MediaBrowser.Controller/IResourceFileManager.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index c695c02315..30ccaf8de4 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -640,7 +640,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>(); - ServiceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>(); ServiceCollection.AddSingleton<EncodingHelper>(); ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>(); diff --git a/Emby.Server.Implementations/ResourceFileManager.cs b/Emby.Server.Implementations/ResourceFileManager.cs deleted file mode 100644 index 22fc62293a..0000000000 --- a/Emby.Server.Implementations/ResourceFileManager.cs +++ /dev/null @@ -1,45 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.IO; -using MediaBrowser.Controller; -using MediaBrowser.Controller.Net; -using MediaBrowser.Model.IO; -using Microsoft.Extensions.Logging; - -namespace Emby.Server.Implementations -{ - public class ResourceFileManager : IResourceFileManager - { - private readonly IFileSystem _fileSystem; - private readonly ILogger<ResourceFileManager> _logger; - - public ResourceFileManager(ILogger<ResourceFileManager> logger, IFileSystem fileSystem) - { - _logger = logger; - _fileSystem = fileSystem; - } - - public string GetResourcePath(string basePath, string virtualPath) - { - var fullPath = Path.Combine(basePath, virtualPath.Replace('/', Path.DirectorySeparatorChar)); - - try - { - fullPath = Path.GetFullPath(fullPath); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error retrieving full path"); - } - - // Don't allow file system access outside of the source folder - if (!_fileSystem.ContainsSubPath(basePath, fullPath)) - { - throw new SecurityException("Access denied"); - } - - return fullPath; - } - } -} diff --git a/MediaBrowser.Controller/IResourceFileManager.cs b/MediaBrowser.Controller/IResourceFileManager.cs deleted file mode 100644 index 26f0424b7a..0000000000 --- a/MediaBrowser.Controller/IResourceFileManager.cs +++ /dev/null @@ -1,9 +0,0 @@ -#pragma warning disable CS1591 - -namespace MediaBrowser.Controller -{ - public interface IResourceFileManager - { - string GetResourcePath(string basePath, string virtualPath); - } -} From 50e375020a580078ed309e2d59cf124d10b4a2ed Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 24 Nov 2020 05:11:02 +0000 Subject: [PATCH 0521/1930] [Fix] NetworkManager binding to [::] (#4549) * Autodiscovery enable/disable patch * Fixed [::] issue on bind. Altered test. * Update UdpServerEntryPoint.cs * Update Jellyfin.Networking.Tests.csproj * Update Jellyfin.Networking.Tests.csproj * Update INetworkManager.cs --- Jellyfin.Networking/Manager/NetworkManager.cs | 37 +++++++++++-------- MediaBrowser.Common/Net/INetworkManager.cs | 12 +++--- .../NetworkTesting/NetworkParseTests.cs | 16 ++++---- 3 files changed, 36 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 515ae669a1..1a5614b7b0 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -84,7 +84,7 @@ namespace Jellyfin.Networking.Manager private Collection<IPObject> _internalInterfaces; /// <summary> - /// Flag set when no custom LAN has been defined in the config. + /// Flag set when no custom LAN has been defined in the configuration. /// </summary> private bool _usingPrivateAddresses; @@ -228,7 +228,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false) + public Collection<IPObject> CreateIPCollection(string[] values, bool negated = false) { Collection<IPObject> col = new Collection<IPObject>(); if (values == null) @@ -242,21 +242,14 @@ namespace Jellyfin.Networking.Manager try { - if (v.StartsWith('[') && v.EndsWith(']')) + if (v.StartsWith('!')) { - if (bracketed) - { - AddToCollection(col, v[1..^1]); - } - } - else if (v.StartsWith('!')) - { - if (bracketed) + if (negated) { AddToCollection(col, v[1..]); } } - else if (!bracketed) + else if (!negated) { AddToCollection(col, v); } @@ -730,7 +723,7 @@ namespace Jellyfin.Networking.Manager } /// <summary> - /// Parses a string and adds it into the the collection, replacing any interface references. + /// Parses a string and adds it into the collection, replacing any interface references. /// </summary> /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param> /// <param name="token">String value to parse.</param> @@ -755,7 +748,19 @@ namespace Jellyfin.Networking.Manager } else if (TryParse(token, out IPObject obj)) { - if (!IsIP6Enabled) + // Expand if the ip address is "any". + if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled) + || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled)) + { + foreach (IPNetAddress iface in _interfaceAddresses) + { + if (obj.AddressFamily == iface.AddressFamily) + { + col.AddItem(iface); + } + } + } + else if (!IsIP6Enabled) { // Remove IP6 addresses from multi-homed IPHosts. obj.Remove(AddressFamily.InterNetworkV6); @@ -872,7 +877,7 @@ namespace Jellyfin.Networking.Manager else { var replacement = parts[1].Trim(); - if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) { _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; } @@ -956,7 +961,7 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Refreshing LAN information."); - // Get config options. + // Get configuration options. string[] subnets = config.LocalNetworkSubnets; // Create lists from user settings. diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 43562afe38..b6c390d239 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -149,7 +149,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns true if the address is a private address. - /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// </summary> /// <param name="address">Address to check.</param> /// <returns>True or False.</returns> @@ -157,7 +157,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// </summary> /// <param name="address">IP to check.</param> /// <returns>True if endpoint is within the LAN range.</returns> @@ -165,7 +165,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// </summary> /// <param name="address">IP to check.</param> /// <returns>True if endpoint is within the LAN range.</returns> @@ -173,7 +173,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns true if the address is part of the user defined LAN. - /// The config option TrustIP6Interfaces overrides this functions behaviour. + /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// </summary> /// <param name="address">IP to check.</param> /// <returns>True if endpoint is within the LAN range.</returns> @@ -192,9 +192,9 @@ namespace MediaBrowser.Common.Net /// Parses an array of strings into a Collection{IPObject}. /// </summary> /// <param name="values">Values to parse.</param> - /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> + /// <param name="negated">When true, only include values beginning with !. When false, ignore ! values.</param> /// <returns>IPCollection object containing the value strings.</returns> - Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false); + Collection<IPObject> CreateIPCollection(string[] values, bool negated = false); /// <summary> /// Returns all the internal Bind interface addresses. diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 56d11ef521..c350685af0 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -135,6 +135,7 @@ namespace Jellyfin.Networking.Tests [InlineData("127.0.0.1#")] [InlineData("localhost!")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] + [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public void InvalidAddressString(string address) { Assert.False(TryParse(address, out _)); @@ -157,7 +158,7 @@ namespace Jellyfin.Networking.Tests "[]", "[]", "[]")] - [InlineData("[127.0.0.1]", + [InlineData("!127.0.0.1", "[]", "[]", "[127.0.0.1/32]", @@ -169,18 +170,19 @@ namespace Jellyfin.Networking.Tests "[]", "[]", "[]")] + [InlineData( + "192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, !10.10.10.10", + "[192.158.1.2/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]", + "[192.158.1.2/16,127.0.0.1/32]", + "[10.10.10.10/32]", + "[10.10.10.10/32]", + "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] [InlineData("192.158.1.2/255.255.0.0,192.169.1.2/8", "[192.158.1.2/16,192.169.1.2/8]", "[192.158.1.2/16,192.169.1.2/8]", "[]", "[]", "[192.158.0.0/16,192.0.0.0/8]")] - [InlineData("192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, [10.10.10.10]", - "[192.158.1.2/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]", - "[192.158.1.2/16,127.0.0.1/32]", - "[10.10.10.10/32]", - "[10.10.10.10/32]", - "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5) { if (settings == null) From 29e686b0423c0177c0f3337ebe033b567e77855e Mon Sep 17 00:00:00 2001 From: hoanghuy309 <hoanghuy309@gmail.com> Date: Tue, 24 Nov 2020 10:31:19 +0000 Subject: [PATCH 0522/1930] Translated using Weblate (Vietnamese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/vi/ --- Emby.Server.Implementations/Localization/Core/vi.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index 79bc4800b0..40368d464e 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -80,7 +80,7 @@ "NotificationOptionApplicationUpdateAvailable": "Bản cập nhật ứng dụng hiện sẵn có", "NewVersionIsAvailable": "Một phiên bản mới của Jellyfin Server sẵn có để tải.", "NameSeasonUnknown": "Không Rõ Mùa", - "NameSeasonNumber": "Mùa {0}", + "NameSeasonNumber": "Phần {0}", "NameInstallFailed": "{0} cài đặt thất bại", "MusicVideos": "Video Nhạc", "Music": "Nhạc", From 9b14e7d6e4a291958915fb4f53cb344c9519f9e0 Mon Sep 17 00:00:00 2001 From: CutterXYZ <cutterx@free.fr> Date: Tue, 24 Nov 2020 10:51:26 +0000 Subject: [PATCH 0523/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 3d5d69f36a..1e195378ff 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -93,8 +93,8 @@ "ValueSpecialEpisodeName": "Spécial - {0}", "VersionNumber": "Version {0}", "TasksChannelsCategory": "Chaines en ligne", - "TaskDownloadMissingSubtitlesDescription": "Cherche les sous-titres manquant sur internet en se basant sur la configuration des métadonnées.", - "TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquant", + "TaskDownloadMissingSubtitlesDescription": "Recherche les sous-titres manquants sur internet en se basant sur la configuration des métadonnées.", + "TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquants", "TaskRefreshChannelsDescription": "Rafraîchit les informations des chaines en ligne.", "TaskRefreshChannels": "Rafraîchir les chaines", "TaskCleanTranscodeDescription": "Supprime les fichiers transcodés de plus d'un jour.", From eefb192584be01bcb2540811400549419b831279 Mon Sep 17 00:00:00 2001 From: Mikko Puntanen <mikko95@hotmail.com> Date: Tue, 24 Nov 2020 10:59:05 +0000 Subject: [PATCH 0524/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- Emby.Server.Implementations/Localization/Core/fi.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index 8e219a9cef..61bef29ed2 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -112,5 +112,7 @@ "TaskCleanCache": "Tyhjennä välimuisti-hakemisto", "TasksChannelsCategory": "Internet kanavat", "TasksApplicationCategory": "Sovellus", - "TasksLibraryCategory": "Kirjasto" + "TasksLibraryCategory": "Kirjasto", + "Forced": "Pakotettu", + "Default": "Oletus" } From bee69e409bd3053658bdaef9461e8c85683dc6c6 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Tue, 24 Nov 2020 22:09:13 +0800 Subject: [PATCH 0525/1930] add tonemapping for intel vaapi hwdec->scale->tonemap->hwenc hwdec->scale->tonemap->textsubs->hwenc * grapical subs requires overlay_vaapi, but it's still in ffmpeg mailing list. --- .../MediaEncoding/EncodingHelper.cs | 133 +++++++++++++----- 1 file changed, 101 insertions(+), 32 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 9a6f1231f1..f101752124 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -112,6 +112,13 @@ namespace MediaBrowser.Controller.MediaEncoding return _mediaEncoder.SupportsHwaccel("vaapi"); } + private bool IsTonemappingSupported(EncodingJobInfo state, EncodingOptions options) + { + var videoStream = state.VideoStream; + var isColorDepth10 = IsColorDepth10(state); + return isColorDepth10 && _mediaEncoder.SupportsHwaccel("opencl") && options.EnableTonemapping && !string.IsNullOrEmpty(videoStream.VideoRange) && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase); + } + /// <summary> /// Gets the name of the output video codec. /// </summary> @@ -468,6 +475,7 @@ namespace MediaBrowser.Controller.MediaEncoding var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + var isTonemappingSupported = IsTonemappingSupported(state, encodingOptions); if (!IsCopyCodec(outputVideoCodec)) { @@ -477,10 +485,24 @@ namespace MediaBrowser.Controller.MediaEncoding { if (isVaapiDecoder) { - arg.Append("-hwaccel_output_format vaapi ") - .Append("-vaapi_device ") - .Append(encodingOptions.VaapiDevice) - .Append(' '); + if (isTonemappingSupported) + { + arg.Append("-init_hw_device vaapi=va:") + .Append(encodingOptions.VaapiDevice) + .Append(' ') + .Append("-init_hw_device opencl=ocl@va ") + .Append("-hwaccel vaapi ") + .Append("-hwaccel_device va ") + .Append("-hwaccel_output_format vaapi ") + .Append("-filter_hw_device ocl "); + } + else + { + arg.Append("-hwaccel_output_format vaapi ") + .Append("-vaapi_device ") + .Append(encodingOptions.VaapiDevice) + .Append(' '); + } } else if (!isVaapiDecoder && isVaapiEncoder) { @@ -529,13 +551,7 @@ namespace MediaBrowser.Controller.MediaEncoding && (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder) || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder)) { - var isColorDepth10 = IsColorDepth10(state); - - if (isColorDepth10 - && _mediaEncoder.SupportsHwaccel("opencl") - && encodingOptions.EnableTonemapping - && !string.IsNullOrEmpty(state.VideoStream.VideoRange) - && state.VideoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) + if (isTonemappingSupported) { arg.Append("-init_hw_device opencl=ocl:") .Append(encodingOptions.OpenclDevice) @@ -1997,6 +2013,7 @@ namespace MediaBrowser.Controller.MediaEncoding public List<string> GetScalingFilters( EncodingJobInfo state, + EncodingOptions options, int? videoWidth, int? videoHeight, Video3DFormat? threedFormat, @@ -2035,6 +2052,19 @@ namespace MediaBrowser.Controller.MediaEncoding || state.DeInterlace("h265", true) || state.DeInterlace("hevc", true); + var isTonemappingSupported = IsTonemappingSupported(state, options); + var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && !qsv_or_vaapi; + + var outputPixFmt = string.Empty; + if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + { + outputPixFmt = "format=p010:out_range=limited"; + } + else + { + outputPixFmt = "format=nv12"; + } + if (!videoWidth.HasValue || outputWidth != videoWidth.Value || !videoHeight.HasValue @@ -2045,10 +2075,11 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add( string.Format( CultureInfo.InvariantCulture, - "{0}=w={1}:h={2}:format=nv12{3}", + "{0}=w={1}:h={2}{3}{4}", qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi", outputWidth, outputHeight, + ":" + outputPixFmt, (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty)); } else @@ -2056,8 +2087,9 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add( string.Format( CultureInfo.InvariantCulture, - "{0}=format=nv12{1}", + "{0}={1}{2}", qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi", + outputPixFmt, (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty)); } } @@ -2290,6 +2322,7 @@ namespace MediaBrowser.Controller.MediaEncoding var isSwDecoder = string.IsNullOrEmpty(videoDecoder); var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1; @@ -2300,6 +2333,10 @@ namespace MediaBrowser.Controller.MediaEncoding var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1; var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isColorDepth10 = IsColorDepth10(state); + var isTonemappingSupported = IsTonemappingSupported(state, options); + var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder; + var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder; + var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; @@ -2311,18 +2348,13 @@ namespace MediaBrowser.Controller.MediaEncoding var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true); var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true); - if ((string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder) - || (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder)) + if (isTonemappingSupportedOnNvenc || isTonemappingSupportedOnAmf || isTonemappingSupportedOnVaapi) { // Currently only with the use of NVENC decoder can we get a decent performance. // Currently only the HEVC/H265 format is supported with NVDEC decoder. // NVIDIA Pascal and Turing or higher are recommended. // AMD Polaris and Vega or higher are recommended. - if (isColorDepth10 - && _mediaEncoder.SupportsHwaccel("opencl") - && options.EnableTonemapping - && !string.IsNullOrEmpty(videoStream.VideoRange) - && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) + if (isTonemappingSupported) { var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}"; @@ -2353,12 +2385,32 @@ namespace MediaBrowser.Controller.MediaEncoding // Convert to hardware pixel format p010 when using SW decoder. filters.Add("format=p010"); + + // Upload the HDR10 or HLG data to the OpenCL device, + // use tonemap_opencl filter for tone mapping, + // and then download the SDR data to memory. + filters.Add("hwupload"); + } + + if (isVaapiDecoder) + { + isScalingInAdvance = true; + filters.AddRange( + GetScalingFilters( + state, + options, + inputWidth, + inputHeight, + threeDFormat, + videoDecoder, + outputVideoCodec, + request.Width, + request.Height, + request.MaxWidth, + request.MaxHeight)); + filters.Add("hwmap"); } - // Upload the HDR10 or HLG data to the OpenCL device, - // use tonemap_opencl filter for tone mapping, - // and then download the SDR data to memory. - filters.Add("hwupload"); filters.Add( string.Format( CultureInfo.InvariantCulture, @@ -2369,21 +2421,30 @@ namespace MediaBrowser.Controller.MediaEncoding options.TonemappingPeak, options.TonemappingParam, options.TonemappingRange)); - filters.Add("hwdownload"); - if (isLibX264Encoder - || isLibX265Encoder - || hasGraphicalSubs - || (isNvdecHevcDecoder && isDeinterlaceHevc) - || (!isNvdecHevcDecoder && isDeinterlaceH264 || isDeinterlaceHevc)) + if (isSwDecoder || isD3d11vaDecoder) { - filters.Add("format=nv12"); + filters.Add("hwdownload"); + + if (isLibX264Encoder + || isLibX265Encoder + || hasGraphicalSubs + || (isNvdecHevcDecoder && isDeinterlaceHevc) + || (!isNvdecHevcDecoder && isDeinterlaceH264 || isDeinterlaceHevc)) + { + filters.Add("format=nv12"); + } + } + + if (isVaapiDecoder) + { + filters.Add("hwmap=derive_device=vaapi:reverse=1"); } } } // When the input may or may not be hardware VAAPI decodable - if (isVaapiH264Encoder || isVaapiHevcEncoder) + if ((isVaapiH264Encoder || isVaapiHevcEncoder) && !isTonemappingSupported && !isTonemappingSupportedOnVaapi) { filters.Add("format=nv12|vaapi"); filters.Add("hwupload"); @@ -2467,6 +2528,7 @@ namespace MediaBrowser.Controller.MediaEncoding filters.AddRange( GetScalingFilters( state, + options, inputWidth, inputHeight, threeDFormat, @@ -2483,6 +2545,13 @@ namespace MediaBrowser.Controller.MediaEncoding { if (hasTextSubs) { + // Convert hw context from ocl to va. + // For tonemapping and text subs burn-in. + if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + { + filters.Add("scale_vaapi"); + } + // Test passed on Intel and AMD gfx filters.Add("hwmap=mode=read+write"); filters.Add("format=nv12"); From f8229529ab5ca98d65eabdc0b672fb24432096ea Mon Sep 17 00:00:00 2001 From: Oatavandi <oatavandi@gmail.com> Date: Tue, 24 Nov 2020 14:52:36 +0000 Subject: [PATCH 0526/1930] Translated using Weblate (Tamil) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ta/ --- Emby.Server.Implementations/Localization/Core/ta.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index 5fcdb1f748..c737ba42b8 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -21,7 +21,7 @@ "Inherit": "மரபுரிமையாகப் பெறு", "HeaderRecordingGroups": "பதிவு குழுக்கள்", "Folders": "கோப்புறைகள்", - "FailedLoginAttemptWithUserName": "{0} இலிருந்து உள்நுழைவு முயற்சி தோல்வியடைந்தது", + "FailedLoginAttemptWithUserName": "{0} இல் இருந்து உள்நுழைவு முயற்சி தோல்வியடைந்தது", "DeviceOnlineWithName": "{0} இணைக்கப்பட்டது", "DeviceOfflineWithName": "{0} துண்டிக்கப்பட்டது", "Collections": "தொகுப்புகள்", @@ -99,7 +99,7 @@ "MessageNamedServerConfigurationUpdatedWithValue": "சேவையக உள்ளமைவு பிரிவு {0} புதுப்பிக்கப்பட்டது", "TaskCleanCacheDescription": "கணினிக்கு இனி தேவைப்படாத தற்காலிக கோப்புகளை நீக்கு.", "UserOfflineFromDevice": "{0} இலிருந்து {1} துண்டிக்கப்பட்டுள்ளது", - "SubtitleDownloadFailureFromForItem": "வசன வரிகள் {0} இலிருந்து {1} க்கு பதிவிறக்கத் தவறிவிட்டன", + "SubtitleDownloadFailureFromForItem": "வசன வரிகள் {0} இல் இருந்து {1} க்கு பதிவிறக்கத் தவறிவிட்டன", "TaskDownloadMissingSubtitlesDescription": "மீத்தரவு உள்ளமைவின் அடிப்படையில் வசன வரிகள் காணாமல் போனதற்கு இணையத்தைத் தேடுகிறது.", "TaskCleanTranscodeDescription": "ஒரு நாளைக்கு மேற்பட்ட பழைய டிரான்ஸ்கோட் கோப்புகளை நீக்குகிறது.", "TaskUpdatePluginsDescription": "தானாகவே புதுப்பிக்க கட்டமைக்கப்பட்ட உட்செருகிகளுக்கான புதுப்பிப்புகளை பதிவிறக்குகிறது மற்றும் நிறுவுகிறது.", From 9c703a75ececd4f5abd0d7ecf156685c65a6ff02 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Tue, 24 Nov 2020 23:10:34 +0800 Subject: [PATCH 0527/1930] disable graphical subs burn-in when tonemapping --- .../MediaEncoding/EncodingHelper.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index f101752124..3292806a20 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1882,6 +1882,19 @@ namespace MediaBrowser.Controller.MediaEncoding var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty; var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isTonemappingSupported = IsTonemappingSupported(state, options); + var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + + // Tonemapping and burn-in graphical subtitles requires overlay_vaapi. + // But it's still in ffmpeg mailing list. Disable it for now. + if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + { + return GetOutputSizeParam(state, options, outputVideoCodec); + } + // Setup subtitle scaling if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue) { From 75963d91814ae32b606253e825c39c233287e47a Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Tue, 24 Nov 2020 23:25:32 +0800 Subject: [PATCH 0528/1930] enable cl-va p010 interop --- Jellyfin.Server/Program.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index db67f64708..a1a7a30534 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -106,6 +106,10 @@ namespace Jellyfin.Server // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); + // Enable cl-va P010 interop for tonemapping on Intel VAAPI + Environment.SetEnvironmentVariable("NEOReadDebugKeys", "1"); + Environment.SetEnvironmentVariable("EnableExtendedVaFormats", "1"); + await InitLoggingConfigFile(appPaths).ConfigureAwait(false); // Create an instance of the application configuration to use for application startup From 44dc1c372907d373c3a217491f29ca7c96f61829 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Tue, 24 Nov 2020 16:27:46 +0000 Subject: [PATCH 0529/1930] Apply suggestions from code review Co-authored-by: Cody Robibero <cody@robibe.ro> --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 3292806a20..5bf8102a61 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -115,8 +115,11 @@ namespace MediaBrowser.Controller.MediaEncoding private bool IsTonemappingSupported(EncodingJobInfo state, EncodingOptions options) { var videoStream = state.VideoStream; - var isColorDepth10 = IsColorDepth10(state); - return isColorDepth10 && _mediaEncoder.SupportsHwaccel("opencl") && options.EnableTonemapping && !string.IsNullOrEmpty(videoStream.VideoRange) && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase); + return IsColorDepth10(state) + && _mediaEncoder.SupportsHwaccel("opencl") + && options.EnableTonemapping + && !string.IsNullOrEmpty(videoStream.VideoRange) + && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase); } /// <summary> From 9534f55eb077249b102e56cc0bc64e95b704cf85 Mon Sep 17 00:00:00 2001 From: nextlooper42 <nextlooper42@protonmail.com> Date: Tue, 24 Nov 2020 18:04:14 +0000 Subject: [PATCH 0530/1930] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- Emby.Server.Implementations/Localization/Core/sk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 8e50269444..8e75b358ca 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -2,7 +2,7 @@ "Albums": "Albumy", "AppDeviceValues": "Aplikácia: {0}, Zariadenie: {1}", "Application": "Aplikácia", - "Artists": "Umelci", + "Artists": "Interpreti", "AuthenticationSucceededWithUserName": "{0} úspešne overený", "Books": "Knihy", "CameraImageUploadedFrom": "Z {0} bola nahraná nová fotografia", From 922b02733b1e1e6b66226912b8c0a9e25b773732 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Tue, 24 Nov 2020 17:25:50 -0500 Subject: [PATCH 0531/1930] Revert "Enable jellyfin.service unit on Fedora fresh install" --- fedora/jellyfin.spec | 4 ---- 1 file changed, 4 deletions(-) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 0ab1e410a4..197126ee56 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -127,10 +127,6 @@ if [ $1 -gt 1 ] ; then if [ "${service_state}" = "active" ]; then systemctl start jellyfin.service fi - if [ $1 -eq 1 ]; then - # On fresh install only, enable the jellyfin.service unit - systemctl enable --now jellyfin.service - fi fi %systemd_post jellyfin.service From 9b2999237ff0253a6421e7c2b34e1286b3713a4b Mon Sep 17 00:00:00 2001 From: nextlooper42 <nextlooper42@protonmail.com> Date: Tue, 24 Nov 2020 21:27:10 +0000 Subject: [PATCH 0532/1930] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- Emby.Server.Implementations/Localization/Core/sk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 8e75b358ca..c78adc2b04 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -15,7 +15,7 @@ "Favorites": "Obľúbené", "Folders": "Priečinky", "Genres": "Žánre", - "HeaderAlbumArtists": "Umelci albumu", + "HeaderAlbumArtists": "Interpreti albumu", "HeaderContinueWatching": "Pokračovať v pozeraní", "HeaderFavoriteAlbums": "Obľúbené albumy", "HeaderFavoriteArtists": "Obľúbení umelci", From 49eadd324629dc2e949260959096d4f1cf55bd6a Mon Sep 17 00:00:00 2001 From: volodymyr <volodymyr.korenkov@gmail.com> Date: Tue, 24 Nov 2020 22:55:49 +0000 Subject: [PATCH 0533/1930] Translated using Weblate (Ukrainian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/uk/ --- Emby.Server.Implementations/Localization/Core/uk.json | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/uk.json b/Emby.Server.Implementations/Localization/Core/uk.json index 06cc5f633e..b6073bf6a8 100644 --- a/Emby.Server.Implementations/Localization/Core/uk.json +++ b/Emby.Server.Implementations/Localization/Core/uk.json @@ -27,7 +27,7 @@ "Channels": "Канали", "CameraImageUploadedFrom": "Нова фотографія завантажена з {0}", "Books": "Книги", - "AuthenticationSucceededWithUserName": "{0} успішно авторизований", + "AuthenticationSucceededWithUserName": "{0} успішно автентифіковано", "Artists": "Виконавці", "Application": "Додаток", "AppDeviceValues": "Додаток: {0}, Пристрій: {1}", @@ -112,5 +112,10 @@ "MessageServerConfigurationUpdated": "Конфігурація сервера оновлена", "MessageNamedServerConfigurationUpdatedWithValue": "Розділ конфігурації сервера {0} оновлено", "Inherit": "Успадкувати", - "HeaderRecordingGroups": "Групи запису" + "HeaderRecordingGroups": "Групи запису", + "Forced": "Примусово", + "TaskCleanActivityLogDescription": "Видаляє старші за встановлений термін записи з журналу активності.", + "TaskCleanActivityLog": "Очистити журнал активності", + "Undefined": "Не визначено", + "Default": "За замовчуванням" } From 0acea5b0770dc08516b032f0d27dee9b559afa7d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 24 Nov 2020 16:42:27 -0700 Subject: [PATCH 0534/1930] Don't throw null reference if ContentType is null. --- .../LiveTv/TunerHosts/SharedHttpStream.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 2de447ad9a..f7507e6ba0 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts var extension = "ts"; var requiresRemux = false; - var contentType = response.Content.Headers.ContentType.ToString(); + var contentType = response.Content.Headers.ContentType?.ToString() ?? string.Empty; if (contentType.IndexOf("matroska", StringComparison.OrdinalIgnoreCase) != -1) { requiresRemux = true; From 4edbd6d182f6923db0764d05958e6f205899ff81 Mon Sep 17 00:00:00 2001 From: nextlooper42 <nextlooper42@protonmail.com> Date: Wed, 25 Nov 2020 01:24:27 +0000 Subject: [PATCH 0535/1930] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- Emby.Server.Implementations/Localization/Core/sk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index c78adc2b04..1b566bb52a 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -71,7 +71,7 @@ "ScheduledTaskStartedWithName": "{0} zahájených", "ServerNameNeedsToBeRestarted": "{0} vyžaduje reštart", "Shows": "Seriály", - "Songs": "Piesne", + "Songs": "Skladby", "StartupEmbyServerIsLoading": "Jellyfin Server sa spúšťa. Prosím, skúste to o chvíľu znova.", "SubtitleDownloadFailureForItem": "Sťahovanie titulkov pre {0} zlyhalo", "SubtitleDownloadFailureFromForItem": "Sťahovanie titulkov z {0} pre {1} zlyhalo", From b042a9f539aca5a1b78ca4353a516963e3a6cde9 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Wed, 25 Nov 2020 10:33:16 +0800 Subject: [PATCH 0536/1930] minor changes --- .../MediaEncoding/EncodingHelper.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 5bf8102a61..3baa59caed 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2370,6 +2370,7 @@ namespace MediaBrowser.Controller.MediaEncoding // Currently only the HEVC/H265 format is supported with NVDEC decoder. // NVIDIA Pascal and Turing or higher are recommended. // AMD Polaris and Vega or higher are recommended. + // Intel Kaby Lake or newer is required. if (isTonemappingSupported) { var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}"; @@ -2401,7 +2402,10 @@ namespace MediaBrowser.Controller.MediaEncoding // Convert to hardware pixel format p010 when using SW decoder. filters.Add("format=p010"); + } + if (isNvdecHevcDecoder || isSwDecoder || isD3d11vaDecoder) + { // Upload the HDR10 or HLG data to the OpenCL device, // use tonemap_opencl filter for tone mapping, // and then download the SDR data to memory. @@ -2424,6 +2428,8 @@ namespace MediaBrowser.Controller.MediaEncoding request.Height, request.MaxWidth, request.MaxHeight)); + + // hwmap the HDR data to opencl device by cl-va p010 interop. filters.Add("hwmap"); } @@ -2438,10 +2444,13 @@ namespace MediaBrowser.Controller.MediaEncoding options.TonemappingParam, options.TonemappingRange)); - if (isSwDecoder || isD3d11vaDecoder) + if (isNvdecHevcDecoder || isSwDecoder || isD3d11vaDecoder) { filters.Add("hwdownload"); + } + if (isSwDecoder || isD3d11vaDecoder) + { if (isLibX264Encoder || isLibX265Encoder || hasGraphicalSubs @@ -2454,25 +2463,26 @@ namespace MediaBrowser.Controller.MediaEncoding if (isVaapiDecoder) { + // Reverse the data route from opencl to vaapi. filters.Add("hwmap=derive_device=vaapi:reverse=1"); } } } - // When the input may or may not be hardware VAAPI decodable + // When the input may or may not be hardware VAAPI decodable. if ((isVaapiH264Encoder || isVaapiHevcEncoder) && !isTonemappingSupported && !isTonemappingSupportedOnVaapi) { filters.Add("format=nv12|vaapi"); filters.Add("hwupload"); } - // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context + // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context. else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)) { filters.Add("hwupload=extra_hw_frames=64"); } - // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first + // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first. else if (IsVaapiSupported(state) && isVaapiDecoder && (isLibX264Encoder || isLibX265Encoder)) { var codec = videoStream.Codec.ToLowerInvariant(); @@ -2499,7 +2509,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } - // Add hardware deinterlace filter before scaling filter + // Add hardware deinterlace filter before scaling filter. if (isDeinterlaceH264) { if (isVaapiH264Encoder) @@ -2512,7 +2522,7 @@ namespace MediaBrowser.Controller.MediaEncoding } } - // Add software deinterlace filter before scaling filter + // Add software deinterlace filter before scaling filter. if ((isDeinterlaceH264 || isDeinterlaceHevc) && !isVaapiH264Encoder && !isVaapiHevcEncoder From 8275a5d635f0fe462443ebc0b0e0d63a958025c8 Mon Sep 17 00:00:00 2001 From: Ignatius Bagus <ignatius.mbs@gmail.com> Date: Wed, 25 Nov 2020 04:28:18 +0000 Subject: [PATCH 0537/1930] Translated using Weblate (Indonesian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/id/ --- Emby.Server.Implementations/Localization/Core/id.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/id.json b/Emby.Server.Implementations/Localization/Core/id.json index ef3ed2580a..105ef7be99 100644 --- a/Emby.Server.Implementations/Localization/Core/id.json +++ b/Emby.Server.Implementations/Localization/Core/id.json @@ -112,5 +112,10 @@ "TaskRefreshPeople": "Muat ulang Orang", "TaskCleanLogsDescription": "Menghapus file log yang lebih dari {0} hari.", "TaskCleanLogs": "Bersihkan Log Direktori", - "TaskRefreshLibrary": "Pindai Pustaka Media" + "TaskRefreshLibrary": "Pindai Pustaka Media", + "TaskCleanActivityLogDescription": "Menghapus log aktivitas yang lebih tua dari umur yang dikonfigurasi.", + "TaskCleanActivityLog": "Bersihkan Log Aktivitas", + "Undefined": "Tidak terdefinisi", + "Forced": "Dipaksa", + "Default": "Bawaan" } From abf0f851239301c104f645e4d14e83df428e57eb Mon Sep 17 00:00:00 2001 From: nextlooper42 <nextlooper42@protonmail.com> Date: Wed, 25 Nov 2020 09:32:40 +0000 Subject: [PATCH 0538/1930] Translated using Weblate (Slovak) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sk/ --- .../Localization/Core/sk.json | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sk.json b/Emby.Server.Implementations/Localization/Core/sk.json index 1b566bb52a..99fbd39540 100644 --- a/Emby.Server.Implementations/Localization/Core/sk.json +++ b/Emby.Server.Implementations/Localization/Core/sk.json @@ -18,10 +18,10 @@ "HeaderAlbumArtists": "Interpreti albumu", "HeaderContinueWatching": "Pokračovať v pozeraní", "HeaderFavoriteAlbums": "Obľúbené albumy", - "HeaderFavoriteArtists": "Obľúbení umelci", + "HeaderFavoriteArtists": "Obľúbení interpreti", "HeaderFavoriteEpisodes": "Obľúbené epizódy", "HeaderFavoriteShows": "Obľúbené seriály", - "HeaderFavoriteSongs": "Obľúbené piesne", + "HeaderFavoriteSongs": "Obľúbené skladby", "HeaderLiveTV": "Živá TV", "HeaderNextUp": "Nasleduje", "HeaderRecordingGroups": "Skupiny nahrávok", @@ -33,13 +33,13 @@ "LabelRunningTimeValue": "Dĺžka: {0}", "Latest": "Najnovšie", "MessageApplicationUpdated": "Jellyfin Server bol aktualizovaný", - "MessageApplicationUpdatedTo": "Jellyfin Server bol aktualizový na verziu {0}", + "MessageApplicationUpdatedTo": "Jellyfin Server bol aktualizovaný na verziu {0}", "MessageNamedServerConfigurationUpdatedWithValue": "Sekcia {0} konfigurácie servera bola aktualizovaná", "MessageServerConfigurationUpdated": "Konfigurácia servera bola aktualizovaná", "MixedContent": "Zmiešaný obsah", "Movies": "Filmy", "Music": "Hudba", - "MusicVideos": "Hudobné videá", + "MusicVideos": "Hudobné videoklipy", "NameInstallFailed": "Inštalácia {0} zlyhala", "NameSeasonNumber": "Séria {0}", "NameSeasonUnknown": "Neznáma séria", @@ -89,29 +89,34 @@ "UserPolicyUpdatedWithName": "Používateľské zásady pre {0} boli aktualizované", "UserStartedPlayingItemWithValues": "{0} spustil prehrávanie {1} na {2}", "UserStoppedPlayingItemWithValues": "{0} ukončil prehrávanie {1} na {2}", - "ValueHasBeenAddedToLibrary": "{0} bol pridané do vašej knižnice médií", + "ValueHasBeenAddedToLibrary": "{0} bol pridaný do vašej knižnice médií", "ValueSpecialEpisodeName": "Špeciál - {0}", "VersionNumber": "Verzia {0}", "TaskDownloadMissingSubtitlesDescription": "Vyhľadá na internete chýbajúce titulky podľa toho, ako sú nakonfigurované metadáta.", "TaskDownloadMissingSubtitles": "Stiahnuť chýbajúce titulky", "TaskRefreshChannelsDescription": "Obnoví informácie o internetových kanáloch.", "TaskRefreshChannels": "Obnoviť kanály", - "TaskCleanTranscodeDescription": "Vymaže súbory transkódovania, ktoré sú staršie ako jeden deň.", - "TaskCleanTranscode": "Vyčistiť priečinok pre transkódovanie", + "TaskCleanTranscodeDescription": "Vymaže prekódované súbory, ktoré sú staršie ako jeden deň.", + "TaskCleanTranscode": "Vyčistiť priečinok pre prekódovanie", "TaskUpdatePluginsDescription": "Stiahne a nainštaluje aktualizácie pre zásuvné moduly, ktoré sú nastavené tak, aby sa aktualizovali automaticky.", "TaskUpdatePlugins": "Aktualizovať zásuvné moduly", "TaskRefreshPeopleDescription": "Aktualizuje metadáta pre hercov a režisérov vo vašej mediálnej knižnici.", "TaskRefreshPeople": "Obnoviť osoby", - "TaskCleanLogsDescription": "Vymaže log súbory, ktoré su staršie ako {0} deň/dni/dní.", + "TaskCleanLogsDescription": "Vymaže log súbory, ktoré sú staršie ako {0} deň/dni/dní.", "TaskCleanLogs": "Vyčistiť priečinok s logmi", "TaskRefreshLibraryDescription": "Hľadá vo vašej mediálnej knižnici nové súbory a obnovuje metadáta.", "TaskRefreshLibrary": "Prehľadávať knižnicu medií", "TaskRefreshChapterImagesDescription": "Vytvorí náhľady pre videá, ktoré majú kapitoly.", "TaskRefreshChapterImages": "Extrahovať obrázky kapitol", - "TaskCleanCacheDescription": "Vymaže cache súbory, ktoré nie sú už potrebné pre systém.", - "TaskCleanCache": "Vyčistiť Cache priečinok", + "TaskCleanCacheDescription": "Vymaže súbory vyrovnávacej pamäte, ktoré už nie sú potrebné pre systém.", + "TaskCleanCache": "Vyčistiť priečinok vyrovnávacej pamäte", "TasksChannelsCategory": "Internetové kanály", "TasksApplicationCategory": "Aplikácia", "TasksLibraryCategory": "Knižnica", - "TasksMaintenanceCategory": "Údržba" + "TasksMaintenanceCategory": "Údržba", + "TaskCleanActivityLogDescription": "Vymaže záznamy aktivít v logu, ktoré sú staršie ako zadaná doba.", + "TaskCleanActivityLog": "Vyčistiť log aktivít", + "Undefined": "Nedefinované", + "Forced": "Vynútené", + "Default": "Predvolené" } From 6c0188c42be9bcb5581b0e18d8230c91928c0e41 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 25 Nov 2020 07:44:11 -0700 Subject: [PATCH 0539/1930] Fix efcore not returning a UTC DateTime --- Jellyfin.Server.Implementations/JellyfinDb.cs | 2 + .../ModelBuilderExtensions.cs | 48 +++++++++++++++++++ .../DateTimeKindValueConverter.cs | 21 ++++++++ .../JsonDateTimeIso8601Converter.cs | 24 ---------- MediaBrowser.Common/Json/JsonDefaults.cs | 1 - 5 files changed, 71 insertions(+), 25 deletions(-) create mode 100644 Jellyfin.Server.Implementations/ModelBuilderExtensions.cs create mode 100644 Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs delete mode 100644 MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 45e71f16eb..bf8818f8d6 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 +using System; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Interfaces; @@ -140,6 +141,7 @@ namespace Jellyfin.Server.Implementations /// <inheritdoc /> protected override void OnModelCreating(ModelBuilder modelBuilder) { + modelBuilder.SetDefaultDateTimeKind(DateTimeKind.Utc); base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultSchema("jellyfin"); diff --git a/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs b/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs new file mode 100644 index 0000000000..80ad65a42c --- /dev/null +++ b/Jellyfin.Server.Implementations/ModelBuilderExtensions.cs @@ -0,0 +1,48 @@ +using System; +using Jellyfin.Server.Implementations.ValueConverters; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Jellyfin.Server.Implementations +{ + /// <summary> + /// Model builder extensions. + /// </summary> + public static class ModelBuilderExtensions + { + /// <summary> + /// Specify value converter for the object type. + /// </summary> + /// <param name="modelBuilder">The model builder.</param> + /// <param name="converter">The <see cref="ValueConverter{TModel,TProvider}"/>.</param> + /// <typeparam name="T">The type to convert.</typeparam> + /// <returns>The modified <see cref="ModelBuilder"/>.</returns> + public static ModelBuilder UseValueConverterForType<T>(this ModelBuilder modelBuilder, ValueConverter converter) + { + var type = typeof(T); + foreach (var entityType in modelBuilder.Model.GetEntityTypes()) + { + foreach (var property in entityType.GetProperties()) + { + if (property.ClrType == type) + { + property.SetValueConverter(converter); + } + } + } + + return modelBuilder; + } + + /// <summary> + /// Specify the default <see cref="DateTimeKind"/>. + /// </summary> + /// <param name="modelBuilder">The model builder to extend.</param> + /// <param name="kind">The <see cref="DateTimeKind"/> to specify.</param> + public static void SetDefaultDateTimeKind(this ModelBuilder modelBuilder, DateTimeKind kind) + { + modelBuilder.UseValueConverterForType<DateTime>(new DateTimeKindValueConverter(kind)); + modelBuilder.UseValueConverterForType<DateTime?>(new DateTimeKindValueConverter(kind)); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs new file mode 100644 index 0000000000..8a510898bf --- /dev/null +++ b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs @@ -0,0 +1,21 @@ +using System; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Jellyfin.Server.Implementations.ValueConverters +{ + /// <summary> + /// ValueConverter to specify kind. + /// </summary> + public class DateTimeKindValueConverter : ValueConverter<DateTime, DateTime> + { + /// <summary> + /// Initializes a new instance of the <see cref="DateTimeKindValueConverter"/> class. + /// </summary> + /// <param name="kind">The kind to specify.</param> + /// <param name="mappingHints">The mapping hints.</param> + public DateTimeKindValueConverter(DateTimeKind kind, ConverterMappingHints mappingHints = null) + : base(v => v.ToUniversalTime(), v => DateTime.SpecifyKind(v, kind), mappingHints) + { + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs b/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs deleted file mode 100644 index 63b344a9d6..0000000000 --- a/MediaBrowser.Common/Json/Converters/JsonDateTimeIso8601Converter.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Globalization; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace MediaBrowser.Common.Json.Converters -{ - /// <summary> - /// Returns an ISO8601 formatted datetime. - /// </summary> - /// <remarks> - /// Used for legacy compatibility. - /// </remarks> - public class JsonDateTimeIso8601Converter : JsonConverter<DateTime> - { - /// <inheritdoc /> - public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => reader.GetDateTime(); - - /// <inheritdoc /> - public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) - => writer.WriteStringValue(value.ToString("O", CultureInfo.InvariantCulture)); - } -} diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 1aaf4a43bb..c5050a21db 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -43,7 +43,6 @@ namespace MediaBrowser.Common.Json options.Converters.Add(new JsonVersionConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new JsonNullableStructConverterFactory()); - options.Converters.Add(new JsonDateTimeIso8601Converter()); return options; } From c4423373b654966d964ca7b75e17d7fb09df8715 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 25 Nov 2020 08:47:05 -0700 Subject: [PATCH 0540/1930] Use proper Named HttpClient for MusicBrainz requests --- .../Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs index 93178d64a8..8951cb62e4 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs @@ -768,16 +768,7 @@ namespace MediaBrowser.Providers.Music _stopWatchMusicBrainz.Restart(); using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl); - - // MusicBrainz request a contact email address is supplied, as comment, in user agent field: - // https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting#User-Agent . - request.Headers.UserAgent.ParseAdd(string.Format( - CultureInfo.InvariantCulture, - "{0} ( {1} )", - _appHost.ApplicationUserAgent, - _appHost.ApplicationUserAgentAddress)); - - response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(request).ConfigureAwait(false); + response = await _httpClientFactory.CreateClient(NamedClient.MusicBrainz).SendAsync(request).ConfigureAwait(false); // We retry a finite number of times, and only whilst MB is indicating 503 (throttling). } From 8c8a71692e2f42e30f95e9ff38cc5442a0d56978 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Wed, 25 Nov 2020 23:40:31 +0100 Subject: [PATCH 0541/1930] Remove Hex class as the BCL has one now --- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- .../QuickConnect/QuickConnectManager.cs | 2 +- .../Updates/InstallationManager.cs | 2 +- Jellyfin.Api/Controllers/LiveTvController.cs | 5 +- .../Cryptography/PasswordHash.cs | 10 +- MediaBrowser.Common/Hex.cs | 94 ------------------- .../HexDecodeBenches.cs | 45 --------- .../HexEncodeBenches.cs | 32 ------- .../Jellyfin.Common.Benches.csproj | 16 ---- benches/Jellyfin.Common.Benches/Program.cs | 14 --- tests/Jellyfin.Common.Tests/HexTests.cs | 19 ---- .../PasswordHashTests.cs | 5 +- 12 files changed, 13 insertions(+), 233 deletions(-) delete mode 100644 MediaBrowser.Common/Hex.cs delete mode 100644 benches/Jellyfin.Common.Benches/HexDecodeBenches.cs delete mode 100644 benches/Jellyfin.Common.Benches/HexEncodeBenches.cs delete mode 100644 benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj delete mode 100644 benches/Jellyfin.Common.Benches/Program.cs delete mode 100644 tests/Jellyfin.Common.Tests/HexTests.cs diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 5d17ba1de9..8c44b244c3 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -647,7 +647,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>()); - string hashedPassword = Hex.Encode(hashedPasswordBytes); + string hashedPassword = Convert.ToHexString(hashedPasswordBytes); options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs index 140a675414..7bed06de36 100644 --- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs +++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs @@ -243,7 +243,7 @@ namespace Emby.Server.Implementations.QuickConnect Span<byte> bytes = stackalloc byte[length]; _rng.GetBytes(bytes); - return Hex.Encode(bytes); + return Convert.ToHexString(bytes); } /// <inheritdoc/> diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index f2c096b8af..ef346dd5d6 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -414,7 +414,7 @@ namespace Emby.Server.Implementations.Updates using var md5 = MD5.Create(); cancellationToken.ThrowIfCancellationRequested(); - var hash = Hex.Encode(md5.ComputeHash(stream)); + var hash = Convert.ToHexString(md5.ComputeHash(stream)); if (!string.Equals(package.Checksum, hash, StringComparison.OrdinalIgnoreCase)) { _logger.LogError( diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 410f3a3400..2c27601e94 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; @@ -17,7 +17,6 @@ using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LiveTvDtos; using Jellyfin.Data.Enums; -using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dto; @@ -1015,7 +1014,7 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(pw)) { using var sha = SHA1.Create(); - listingsProviderInfo.Password = Hex.Encode(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))); + listingsProviderInfo.Password = Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))); } return await _liveTvManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false); diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index 3e12536ec7..3e2eae1c8e 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -101,13 +101,13 @@ namespace MediaBrowser.Common.Cryptography // Check if the string also contains a salt if (splitted.Length - index == 2) { - salt = Hex.Decode(splitted[index++]); - hash = Hex.Decode(splitted[index++]); + salt = Convert.FromHexString(splitted[index++]); + hash = Convert.FromHexString(splitted[index++]); } else { salt = Array.Empty<byte>(); - hash = Hex.Decode(splitted[index++]); + hash = Convert.FromHexString(splitted[index++]); } return new PasswordHash(id, hash, salt, parameters); @@ -144,11 +144,11 @@ namespace MediaBrowser.Common.Cryptography if (_salt.Length != 0) { str.Append('$') - .Append(Hex.Encode(_salt, false)); + .Append(Convert.ToHexString(_salt)); } return str.Append('$') - .Append(Hex.Encode(_hash, false)).ToString(); + .Append(Convert.ToHexString(_hash)).ToString(); } } } diff --git a/MediaBrowser.Common/Hex.cs b/MediaBrowser.Common/Hex.cs deleted file mode 100644 index 559109f74f..0000000000 --- a/MediaBrowser.Common/Hex.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; - -namespace MediaBrowser.Common -{ - /// <summary> - /// Encoding and decoding hex strings. - /// </summary> - public static class Hex - { - internal const string HexCharsLower = "0123456789abcdef"; - internal const string HexCharsUpper = "0123456789ABCDEF"; - - internal const int LastHexSymbol = 0x66; // 102: f - - /// <summary> - /// Gets a map from an ASCII char to its hex value shifted, - /// e.g. <c>b</c> -> 11. 0xFF means it's not a hex symbol. - /// </summary> - internal static ReadOnlySpan<byte> HexLookup => new byte[] - { - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f - }; - - /// <summary> - /// Encodes each element of the specified bytes as its hexadecimal string representation. - /// </summary> - /// <param name="bytes">An array of bytes.</param> - /// <param name="lowercase"><c>true</c> to use lowercase hexadecimal characters; otherwise <c>false</c>.</param> - /// <returns><c>bytes</c> as a hex string.</returns> - public static string Encode(ReadOnlySpan<byte> bytes, bool lowercase = true) - { - var hexChars = lowercase ? HexCharsLower : HexCharsUpper; - - // TODO: use string.Create when it's supports spans - // Ref: https://github.com/dotnet/corefx/issues/29120 - char[] s = new char[bytes.Length * 2]; - int j = 0; - for (int i = 0; i < bytes.Length; i++) - { - s[j++] = hexChars[bytes[i] >> 4]; - s[j++] = hexChars[bytes[i] & 0x0f]; - } - - return new string(s); - } - - /// <summary> - /// Decodes a hex string into bytes. - /// </summary> - /// <param name="str">The <see cref="string" />.</param> - /// <returns>The decoded bytes.</returns> - public static byte[] Decode(ReadOnlySpan<char> str) - { - if (str.Length == 0) - { - return Array.Empty<byte>(); - } - - var unHex = HexLookup; - - int byteLen = str.Length / 2; - byte[] bytes = new byte[byteLen]; - int i = 0; - for (int j = 0; j < byteLen; j++) - { - byte a; - byte b; - if (str[i] > LastHexSymbol - || (a = unHex[str[i++]]) == 0xFF - || str[i] > LastHexSymbol - || (b = unHex[str[i++]]) == 0xFF) - { - ThrowArgumentException(nameof(str)); - break; // Unreachable - } - - bytes[j] = (byte)((a * 16) | b); - } - - return bytes; - } - - [DoesNotReturn] - private static void ThrowArgumentException(string paramName) - => throw new ArgumentException("Character is not a hex symbol.", paramName); - } -} diff --git a/benches/Jellyfin.Common.Benches/HexDecodeBenches.cs b/benches/Jellyfin.Common.Benches/HexDecodeBenches.cs deleted file mode 100644 index d9a107b696..0000000000 --- a/benches/Jellyfin.Common.Benches/HexDecodeBenches.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.Globalization; -using BenchmarkDotNet.Attributes; -using BenchmarkDotNet.Running; -using MediaBrowser.Common; - -namespace Jellyfin.Common.Benches -{ - [MemoryDiagnoser] - public class HexDecodeBenches - { - private string _data; - - [Params(0, 10, 100, 1000, 10000, 1000000)] - public int N { get; set; } - - [GlobalSetup] - public void GlobalSetup() - { - var bytes = new byte[N]; - new Random(42).NextBytes(bytes); - _data = Hex.Encode(bytes); - } - - [Benchmark] - public byte[] Decode() => Hex.Decode(_data); - - [Benchmark] - public byte[] DecodeSubString() => DecodeSubString(_data); - - private static byte[] DecodeSubString(string str) - { - byte[] bytes = new byte[str.Length / 2]; - for (int i = 0; i < str.Length; i += 2) - { - bytes[i / 2] = byte.Parse( - str.Substring(i, 2), - NumberStyles.HexNumber, - CultureInfo.InvariantCulture); - } - - return bytes; - } - } -} diff --git a/benches/Jellyfin.Common.Benches/HexEncodeBenches.cs b/benches/Jellyfin.Common.Benches/HexEncodeBenches.cs deleted file mode 100644 index 7abf93c510..0000000000 --- a/benches/Jellyfin.Common.Benches/HexEncodeBenches.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using BenchmarkDotNet.Attributes; -using BenchmarkDotNet.Running; -using MediaBrowser.Common; - -namespace Jellyfin.Common.Benches -{ - [MemoryDiagnoser] - public class HexEncodeBenches - { - private byte[] _data; - - [Params(0, 10, 100, 1000, 10000, 1000000)] - public int N { get; set; } - - [GlobalSetup] - public void GlobalSetup() - { - _data = new byte[N]; - new Random(42).NextBytes(_data); - } - - [Benchmark] - public string HexEncode() => Hex.Encode(_data); - - [Benchmark] - public string BitConverterToString() => BitConverter.ToString(_data); - - [Benchmark] - public string BitConverterToStringWithReplace() => BitConverter.ToString(_data).Replace("-", ""); - } -} diff --git a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj b/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj deleted file mode 100644 index c564e86e9e..0000000000 --- a/benches/Jellyfin.Common.Benches/Jellyfin.Common.Benches.csproj +++ /dev/null @@ -1,16 +0,0 @@ -<Project Sdk="Microsoft.NET.Sdk"> - - <PropertyGroup> - <OutputType>Exe</OutputType> - <TargetFramework>net5.0</TargetFramework> - </PropertyGroup> - - <ItemGroup> - <PackageReference Include="BenchmarkDotNet" Version="0.12.0" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" /> - </ItemGroup> - -</Project> diff --git a/benches/Jellyfin.Common.Benches/Program.cs b/benches/Jellyfin.Common.Benches/Program.cs deleted file mode 100644 index b218b0dc10..0000000000 --- a/benches/Jellyfin.Common.Benches/Program.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using BenchmarkDotNet.Running; - -namespace Jellyfin.Common.Benches -{ - public static class Program - { - public static void Main(string[] args) - { - _ = BenchmarkRunner.Run<HexEncodeBenches>(); - _ = BenchmarkRunner.Run<HexDecodeBenches>(); - } - } -} diff --git a/tests/Jellyfin.Common.Tests/HexTests.cs b/tests/Jellyfin.Common.Tests/HexTests.cs deleted file mode 100644 index 5b578d38cb..0000000000 --- a/tests/Jellyfin.Common.Tests/HexTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -using MediaBrowser.Common; -using Xunit; - -namespace Jellyfin.Common.Tests -{ - public class HexTests - { - [Theory] - [InlineData("")] - [InlineData("00")] - [InlineData("01")] - [InlineData("000102030405060708090a0b0c0d0e0f")] - [InlineData("0123456789abcdef")] - public void RoundTripTest(string data) - { - Assert.Equal(data, Hex.Encode(Hex.Decode(data))); - } - } -} diff --git a/tests/Jellyfin.Common.Tests/PasswordHashTests.cs b/tests/Jellyfin.Common.Tests/PasswordHashTests.cs index 46926f4f81..c4422bd105 100644 --- a/tests/Jellyfin.Common.Tests/PasswordHashTests.cs +++ b/tests/Jellyfin.Common.Tests/PasswordHashTests.cs @@ -1,3 +1,4 @@ +using System; using MediaBrowser.Common; using MediaBrowser.Common.Cryptography; using Xunit; @@ -16,8 +17,8 @@ namespace Jellyfin.Common.Tests { var pass = PasswordHash.Parse(passwordHash); Assert.Equal(id, pass.Id); - Assert.Equal(salt, Hex.Encode(pass.Salt, false)); - Assert.Equal(hash, Hex.Encode(pass.Hash, false)); + Assert.Equal(salt, Convert.ToHexString(pass.Salt)); + Assert.Equal(hash, Convert.ToHexString(pass.Hash)); } [Theory] From 0758d84a61808bc1410bfc32fab743d28484448a Mon Sep 17 00:00:00 2001 From: Matt Montgomery <33811686+ConfusedPolarBear@users.noreply.github.com> Date: Wed, 25 Nov 2020 16:54:16 -0600 Subject: [PATCH 0542/1930] Test query value --- Emby.Server.Implementations/Data/SqliteItemRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 7e01bd4b64..95ffa48f57 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -4517,17 +4517,17 @@ namespace Emby.Server.Implementations.Data } } - if (query.HasImdbId.HasValue) + if (query.HasImdbId.HasValue && query.HasImdbId.Value) { whereClauses.Add("ProviderIds like '%imdb=%'"); } - if (query.HasTmdbId.HasValue) + if (query.HasTmdbId.HasValue && query.HasTmdbId.Value) { whereClauses.Add("ProviderIds like '%tmdb=%'"); } - if (query.HasTvdbId.HasValue) + if (query.HasTvdbId.HasValue && query.HasTvdbId.Value) { whereClauses.Add("ProviderIds like '%tvdb=%'"); } From 38932fc7d1c6851b6a282e9723bea471ef494b96 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Thu, 26 Nov 2020 13:21:04 +0100 Subject: [PATCH 0543/1930] Schedules Direct requires the hex to be lowercase --- .../LiveTv/Listings/SchedulesDirect.cs | 4 +++- Jellyfin.Api/Controllers/LiveTvController.cs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 8c44b244c3..f181eb7a0b 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -647,7 +647,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>()); - string hashedPassword = Convert.ToHexString(hashedPasswordBytes); + // TODO: remove ToLower when Convert.ToHexString supports lowercase + // Schedules Direct requires the hex to be lowercase + string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant(); options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 2c27601e94..56d4b3933e 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1014,7 +1014,9 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(pw)) { using var sha = SHA1.Create(); - listingsProviderInfo.Password = Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))); + // TODO: remove ToLower when Convert.ToHexString supports lowercase + // Schedules Direct requires the hex to be lowercase + listingsProviderInfo.Password = Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))).ToLowerInvariant(); } return await _liveTvManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false); From ab6a4fac91fb9b102156e971457cb078e0bb3bee Mon Sep 17 00:00:00 2001 From: Rubikscraft <personal@rubikscraft.nl> Date: Thu, 26 Nov 2020 10:40:49 +0000 Subject: [PATCH 0544/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index e1e88cc9ba..b6672a554a 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -87,7 +87,7 @@ "UserOnlineFromDevice": "{0} heeft verbinding met {1}", "UserPasswordChangedWithName": "Wachtwoord voor {0} is gewijzigd", "UserPolicyUpdatedWithName": "Gebruikersbeleid gewijzigd voor {0}", - "UserStartedPlayingItemWithValues": "{0} heeft afspelen van {1} gestart op {2}", + "UserStartedPlayingItemWithValues": "{0} speelt {1} af op {2}", "UserStoppedPlayingItemWithValues": "{0} heeft afspelen van {1} gestopt op {2}", "ValueHasBeenAddedToLibrary": "{0} is toegevoegd aan je mediabibliotheek", "ValueSpecialEpisodeName": "Speciaal - {0}", @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Bibliotheek", "TasksMaintenanceCategory": "Onderhoud", "TaskCleanActivityLogDescription": "Verwijder activiteiten logs ouder dan de ingestelde tijd.", - "TaskCleanActivityLog": "Leeg activiteiten logboek" + "TaskCleanActivityLog": "Leeg activiteiten logboek", + "Undefined": "Niet gedefinieerd", + "Forced": "Geforceerd", + "Default": "Standaard" } From 536ac4c11cfff5349b973892f206fe5cfb0ae6f0 Mon Sep 17 00:00:00 2001 From: WWWesten <wwwesten@gmail.com> Date: Thu, 26 Nov 2020 18:03:29 +0000 Subject: [PATCH 0545/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index c0db2cf7f5..ca6172fce0 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -115,5 +115,8 @@ "TaskRefreshChapterImagesDescription": "Создаются эскизы для видео, которые содержат сцены.", "TaskCleanCacheDescription": "Удаляются файлы кэша, которые больше не нужны системе.", "TaskCleanActivityLogDescription": "Удаляет записи журнала активности старше установленного возраста.", - "TaskCleanActivityLog": "Очистить журнал активности" + "TaskCleanActivityLog": "Очистить журнал активности", + "Undefined": "Не определено", + "Forced": "Форсир-ые", + "Default": "По умолчанию" } From 81ca6cb47cb1df49196f9a961de4698fbc406ec1 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Thu, 26 Nov 2020 21:54:14 +0100 Subject: [PATCH 0546/1930] Clean up SchedulesDirect --- .../LiveTv/Listings/SchedulesDirect.cs | 85 +++++++------------ 1 file changed, 30 insertions(+), 55 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 5d17ba1de9..96bbd674c3 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; using System.Net; using System.Net.Http; @@ -19,7 +18,6 @@ using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; @@ -36,6 +34,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly IApplicationHost _appHost; private readonly ICryptoProvider _cryptoProvider; + private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>(); + private DateTime _lastErrorResponse; + public SchedulesDirect( ILogger<SchedulesDirect> logger, IJsonSerializer jsonSerializer, @@ -50,8 +51,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings _cryptoProvider = cryptoProvider; } - private string UserAgent => _appHost.ApplicationUserAgent; - /// <inheritdoc /> public string Name => "Schedules Direct"; @@ -307,7 +306,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings if (details.contentRating != null && details.contentRating.Count > 0) { - info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-"); + info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-", StringComparison.Ordinal) + .Replace("--", "-", StringComparison.Ordinal); var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" }; if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase)) @@ -450,7 +450,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms( ListingsProviderInfo info, - List<string> programIds, + IReadOnlyList<string> programIds, CancellationToken cancellationToken) { if (programIds.Count == 0) @@ -458,23 +458,21 @@ namespace Emby.Server.Implementations.LiveTv.Listings return new List<ScheduleDirect.ShowImages>(); } - var imageIdString = "["; - - foreach (var i in programIds) + StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13)); + foreach (ReadOnlySpan<char> i in programIds) { - var imageId = i.Substring(0, 10); - - if (!imageIdString.Contains(imageId, StringComparison.Ordinal)) - { - imageIdString += "\"" + imageId + "\","; - } + str.Append('"') + .Append(i.Slice(0, 10)) + .Append("\","); } - imageIdString = imageIdString.TrimEnd(',') + "]"; + // Remove last , + str.Length--; + str.Append(']'); using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs") { - Content = new StringContent(imageIdString, Encoding.UTF8, MediaTypeNames.Application.Json) + Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json) }; try @@ -539,9 +537,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings return lineups; } - private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>(); - private DateTime _lastErrorResponse; - private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken) { var username = info.Username; @@ -564,8 +559,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings return null; } - NameValuePair savedToken; - if (!_tokens.TryGetValue(username, out savedToken)) + if (!_tokens.TryGetValue(username, out NameValuePair savedToken)) { savedToken = new NameValuePair(); _tokens.TryAdd(username, savedToken); @@ -653,7 +647,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).ConfigureAwait(false); - if (root.message == "OK") + if (string.Equals(root.message, "OK", StringComparison.Ordinal)) { _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); return root.token; @@ -777,24 +771,28 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId); options.Headers.TryAddWithoutValidation("token", token); - var list = new List<ChannelInfo>(); - using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(stream).ConfigureAwait(false); _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); _logger.LogInformation("Mapping Stations to Channel"); - var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>(); + var allStations = root.stations ?? new List<ScheduleDirect.Station>(); - foreach (ScheduleDirect.Map map in root.map) + var map = root.map; + int len = map.Count; + var array = new List<ChannelInfo>(len); + for (int i = 0; i < len; i++) { - var channelNumber = GetChannelNumber(map); + var channelNumber = GetChannelNumber(map[i]); - var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase)); + var station = allStations.Find(item => string.Equals(item.stationID, map[i].stationID, StringComparison.OrdinalIgnoreCase)); if (station == null) { - station = new ScheduleDirect.Station { stationID = map.stationID }; + station = new ScheduleDirect.Station + { + stationID = map[i].stationID + }; } var channelInfo = new ChannelInfo @@ -810,32 +808,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings channelInfo.ImageUrl = station.logo.URL; } - list.Add(channelInfo); + array[i] = channelInfo; } - return list; - } - - private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName) - { - if (!string.IsNullOrWhiteSpace(channelName)) - { - channelName = NormalizeName(channelName); - - var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase)); - - if (result != null) - { - return result; - } - } - - if (!string.IsNullOrWhiteSpace(channelNumber)) - { - return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase)); - } - - return null; + return array; } private static string NormalizeName(string value) @@ -1044,7 +1020,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings } } - // public class Title { public string title120 { get; set; } From cc9e178d9a2e2a489d0353a98bb15900eceb2c4f Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Fri, 27 Nov 2020 16:08:44 +0800 Subject: [PATCH 0547/1930] remove a redundant 'hwaccel vaapi' string --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 3baa59caed..9c6bbb9169 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -494,7 +494,6 @@ namespace MediaBrowser.Controller.MediaEncoding .Append(encodingOptions.VaapiDevice) .Append(' ') .Append("-init_hw_device opencl=ocl@va ") - .Append("-hwaccel vaapi ") .Append("-hwaccel_device va ") .Append("-hwaccel_output_format vaapi ") .Append("-filter_hw_device ocl "); From c196ad3351e07d21ceef8f932129ab0e8d43a9b4 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Fri, 27 Nov 2020 10:25:43 +0100 Subject: [PATCH 0548/1930] Don't return first episodes in next up --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index ccd1446ddf..30a29a607d 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -146,23 +146,10 @@ namespace Emby.Server.Implementations.TV var allNextUp = seriesKeys .Select(i => GetNextUp(i, currentUser, dtoOptions)); - // allNextUp = allNextUp.OrderByDescending(i => i.Item1); - - // If viewing all next up for all series, remove first episodes - // But if that returns empty, keep those first episodes (avoid completely empty view) - var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId); - var anyFound = false; - return allNextUp .Where(i => { - if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue) - { - anyFound = true; - return true; - } - - if (!anyFound && i.Item1 == DateTime.MinValue) + if (i.Item1 != DateTime.MinValue) { return true; } From b26a5e9e2063b782139f6e61c002b134b3663bc4 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Fri, 27 Nov 2020 20:12:47 +0800 Subject: [PATCH 0549/1930] add NEO OpenCL runtime for Intel Tone mapping --- Dockerfile | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 963027b49c..9711084954 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,8 +27,15 @@ ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility" COPY --from=builder /jellyfin /jellyfin COPY --from=web-builder /dist /jellyfin/jellyfin-web + +# https://github.com/intel/compute-runtime/releases +ARG GMMLIB_VERSION=20.3.2 +ARG IGC_VERSION=1.0.5435 +ARG NEO_VERSION=20.46.18421 +ARG LEVEL_ZERO_VERSION=1.0.18421 + # Install dependencies: -# mesa-va-drivers: needed for AMD VAAPI +# mesa-va-drivers: needed for AMD VAAPI. Mesa >= 20.1 is required for HEVC transcoding. RUN apt-get update \ && apt-get install --no-install-recommends --no-install-suggests -y ca-certificates gnupg wget apt-transport-https \ && wget -O - https://repo.jellyfin.org/jellyfin_team.gpg.key | apt-key add - \ @@ -39,6 +46,20 @@ RUN apt-get update \ jellyfin-ffmpeg \ openssl \ locales \ +# Intel VAAPI Tone mapping dependencies: +# Prefer NEO to Beignet since the latter one doesn't support Comet Lake or newer for now. +# Do not use the intel-opencl-icd package from repo since they were not build with RELEASE_WITH_REGKEYS enabled. + && mkdir intel-compute-runtime \ + && cd intel-compute-runtime \ + && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-gmmlib_${GMMLIB_VERSION}_amd64.deb \ + && wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-${IGC_VERSION}/intel-igc-core_${IGC_VERSION}_amd64.deb \ + && wget https://github.com/intel/intel-graphics-compiler/releases/download/igc-${IGC_VERSION}/intel-igc-opencl_${IGC_VERSION}_amd64.deb \ + && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-opencl_${NEO_VERSION}_amd64.deb \ + && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-ocloc_${NEO_VERSION}_amd64.deb \ + && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-level-zero-gpu_${LEVEL_ZERO_VERSION}_amd64.deb \ + && dpkg -i *.deb \ + && cd .. \ + && rm -rf intel-compute-runtime \ && apt-get remove gnupg wget apt-transport-https -y \ && apt-get clean autoclean -y \ && apt-get autoremove -y \ From 0dda909a608ebaad05405d4565ac096b480f2462 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Fri, 27 Nov 2020 19:06:18 +0100 Subject: [PATCH 0550/1930] Fix suggestion --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 30a29a607d..a697c6476f 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -149,12 +149,7 @@ namespace Emby.Server.Implementations.TV return allNextUp .Where(i => { - if (i.Item1 != DateTime.MinValue) - { - return true; - } - - return false; + return i.Item1 != DateTime.MinValue; }) .Select(i => i.Item2()) .Where(i => i != null); From 185476c08ac942b942623362a8f9e917c2d8c3a0 Mon Sep 17 00:00:00 2001 From: Matt Montgomery <33811686+ConfusedPolarBear@users.noreply.github.com> Date: Fri, 27 Nov 2020 16:12:16 -0600 Subject: [PATCH 0551/1930] Add support for query negation --- .../Data/SqliteItemRepository.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 95ffa48f57..50c7a07d48 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -4517,19 +4517,19 @@ namespace Emby.Server.Implementations.Data } } - if (query.HasImdbId.HasValue && query.HasImdbId.Value) + if (query.HasImdbId.HasValue) { - whereClauses.Add("ProviderIds like '%imdb=%'"); + whereClauses.Add(GetProviderIdClause(query.HasImdbId.Value, "imdb")); } - if (query.HasTmdbId.HasValue && query.HasTmdbId.Value) + if (query.HasTmdbId.HasValue) { - whereClauses.Add("ProviderIds like '%tmdb=%'"); + whereClauses.Add(GetProviderIdClause(query.HasTmdbId.Value, "tmdb")); } - if (query.HasTvdbId.HasValue && query.HasTvdbId.Value) + if (query.HasTvdbId.HasValue) { - whereClauses.Add("ProviderIds like '%tvdb=%'"); + whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb")); } var includedItemByNameTypes = GetItemByNameTypesInQuery(query).SelectMany(MapIncludeItemTypes).ToList(); @@ -4769,6 +4769,21 @@ namespace Emby.Server.Implementations.Data return whereClauses; } + /// <summary> + /// Formats a where clause for the specified provider. + /// </summary> + /// <param name="includeResults">Whether or not to include items with this provider's ids.</param> + /// <param name="provider">Provider name.</param> + /// <returns>Formatted SQL clause.</returns> + private string GetProviderIdClause(bool includeResults, string provider) + { + return string.Format( + CultureInfo.InvariantCulture, + "ProviderIds {0} like '%{1}=%'", + includeResults ? string.Empty : "not", + provider); + } + private List<string> GetItemByNameTypesInQuery(InternalItemsQuery query) { var list = new List<string>(); From a59aeb12e07e7ee1f5453e94aefdc19a190f7d16 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 27 Nov 2020 23:04:13 +0000 Subject: [PATCH 0552/1930] Fixed SessionWebSocketListener.OnServerManagerWebSocketConnected. --- .../ActivityLogWebSocketListener.cs | 2 +- Jellyfin.Server/CoreAppHost.cs | 3 ++- .../Middleware/WebSocketHandlerMiddleware.cs | 13 ++++++++++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index ce54651166..288e03fcff 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Api.WebSocketListeners private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) { - SendData(true); + SendData(true).GetAwaiter().GetResult(); } } } diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 78f596a5c9..4b44537a59 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -82,10 +82,11 @@ namespace Jellyfin.Server ServiceCollection.AddSingleton<IUserManager, UserManager>(); ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); - ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, ActivityLogWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, ScheduledTasksWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, SessionInfoWebSocketListener>(); + // This one has to be last as DI will select it for parameterization. + ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); // TODO fix circular dependency on IWebSocketManager ServiceCollection.AddScoped(serviceProvider => new Lazy<IEnumerable<IWebSocketListener>>(serviceProvider.GetRequiredService<IEnumerable<IWebSocketListener>>)); diff --git a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs index b7a5d2b346..53f32bebd1 100644 --- a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs +++ b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs @@ -25,8 +25,19 @@ namespace Jellyfin.Server.Middleware /// </summary> /// <param name="httpContext">The current HTTP context.</param> /// <param name="webSocketManager">The WebSocket connection manager.</param> + /// <param name="websocketListener">Session manager instance.</param> /// <returns>The async task.</returns> - public async Task Invoke(HttpContext httpContext, IWebSocketManager webSocketManager) + public async Task Invoke( + HttpContext httpContext, + IWebSocketManager webSocketManager, +#pragma warning disable CA1801 +#pragma warning disable IDE0060 + // TODO: Workaround. see https://github.com/jellyfin/jellyfin/pull/3194 + // Do not remove this parameter. It uses DI to create a SessionWebSocketListener which is + // required for webSocketManager events. + IWebSocketListener websocketListener) +#pragma warning restore IDE0060 // Remove unused parameter +#pragma warning restore CA1801 { if (!httpContext.WebSockets.IsWebSocketRequest) { From 5cd5a7d4cebe134d8256d4a1b6eadff760fbb2a7 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sat, 28 Nov 2020 00:25:20 +0000 Subject: [PATCH 0553/1930] Removed Lazy implementation. --- .../HttpServer/WebSocketManager.cs | 31 +++++++++---------- .../Session/ISessionWebSocketListener.cs | 30 ++++++++++++++++++ .../Session/SessionWebSocketListener.cs | 27 ++++++---------- .../ActivityLogWebSocketListener.cs | 2 +- .../IActivityLogWebSocketListener.cs | 10 ++++++ .../IScheduledTasksWebSocketListener.cs | 10 ++++++ .../ISessionInfoWebSocketListener.cs | 10 ++++++ .../ScheduledTasksWebSocketListener.cs | 8 ++--- .../SessionInfoWebSocketListener.cs | 2 +- Jellyfin.Server/CoreAppHost.cs | 13 +++----- .../Middleware/WebSocketHandlerMiddleware.cs | 11 +------ .../Net/IWebSocketManager.cs | 5 --- 12 files changed, 95 insertions(+), 64 deletions(-) create mode 100644 Emby.Server.Implementations/Session/ISessionWebSocketListener.cs create mode 100644 Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs create mode 100644 Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs create mode 100644 Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 71ece80a75..5518fb95aa 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Threading.Tasks; -using Jellyfin.Data.Events; +using Emby.Server.Implementations.Session; +using Jellyfin.Api.WebSocketListeners; +using MediaBrowser.Controller; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -13,24 +15,21 @@ namespace Emby.Server.Implementations.HttpServer { public class WebSocketManager : IWebSocketManager { - private readonly Lazy<IEnumerable<IWebSocketListener>> _webSocketListeners; + private readonly IServerApplicationHost _appHost; private readonly ILogger<WebSocketManager> _logger; private readonly ILoggerFactory _loggerFactory; - private bool _disposed = false; public WebSocketManager( - Lazy<IEnumerable<IWebSocketListener>> webSocketListeners, + IServerApplicationHost appHost, ILogger<WebSocketManager> logger, ILoggerFactory loggerFactory) { - _webSocketListeners = webSocketListeners; + _appHost = appHost; _logger = logger; _loggerFactory = loggerFactory; } - public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; - /// <inheritdoc /> public async Task WebSocketRequestHandler(HttpContext context) { @@ -39,6 +38,8 @@ namespace Emby.Server.Implementations.HttpServer return; } + var listener = _appHost.Resolve<ISessionWebSocketListener>(); + try { _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress); @@ -54,7 +55,7 @@ namespace Emby.Server.Implementations.HttpServer OnReceive = ProcessWebSocketMessageReceived }; - WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); + listener?.ProcessWebSocketConnected(connection); await connection.ProcessAsync().ConfigureAwait(false); _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress); @@ -80,16 +81,12 @@ namespace Emby.Server.Implementations.HttpServer return Task.CompletedTask; } - IEnumerable<Task> GetTasks() - { - var listeners = _webSocketListeners.Value; - foreach (var x in listeners) - { - yield return x.ProcessMessageAsync(result); - } - } + Parallel.Invoke( + () => _appHost.Resolve<IActivityLogWebSocketListener>(), + () => _appHost.Resolve<IScheduledTasksWebSocketListener>(), + () => _appHost.Resolve<ISessionInfoWebSocketListener>()); - return Task.WhenAll(GetTasks()); + return Task.CompletedTask; } } } diff --git a/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs b/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs new file mode 100644 index 0000000000..9b0b28e6ee --- /dev/null +++ b/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs @@ -0,0 +1,30 @@ +namespace Emby.Server.Implementations.Session +{ + using System.Threading.Tasks; + using Jellyfin.Data.Events; + using MediaBrowser.Controller.Net; + + /// <summary> + /// Defines the <see cref="ISessionWebSocketListener" />. + /// </summary> + public interface ISessionWebSocketListener + { + /// <summary> + /// Runs processes due to a WebSocket connection event. + /// </summary> + /// <param name="websocketConnection">The <see cref="IWebSocketConnection"/> instance.</param> + void ProcessWebSocketConnected(IWebSocketConnection websocketConnection); + + /// <summary> + /// Disposes the object. + /// </summary> + void Dispose(); + + /// <summary> + /// Processes a message. + /// </summary> + /// <param name="message">The <see cref="WebSocketMessageInfo"/>.</param> + /// <returns>A <see cref="Task"/>.</returns> + Task ProcessMessageAsync(WebSocketMessageInfo message); + } +} diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index a5f8479537..8f81ee1948 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.Session /// <summary> /// Class SessionWebSocketListener. /// </summary> - public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable + public sealed class SessionWebSocketListener : ISessionWebSocketListener, IDisposable { /// <summary> /// The timeout in seconds after which a WebSocket is considered to be lost. @@ -45,15 +45,13 @@ namespace Emby.Server.Implementations.Session private readonly ILogger<SessionWebSocketListener> _logger; private readonly ILoggerFactory _loggerFactory; - private readonly IWebSocketManager _webSocketManager; - /// <summary> /// The KeepAlive cancellation token. /// </summary> private CancellationTokenSource _keepAliveCancellationToken; /// <summary> - /// Lock used for accesing the KeepAlive cancellation token. + /// Lock used for accessing the KeepAlive cancellation token. /// </summary> private readonly object _keepAliveLock = new object(); @@ -63,7 +61,7 @@ namespace Emby.Server.Implementations.Session private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>(); /// <summary> - /// Lock used for accesing the WebSockets watchlist. + /// Lock used for accessing the WebSockets watchlist. /// </summary> private readonly object _webSocketsLock = new object(); @@ -73,32 +71,28 @@ namespace Emby.Server.Implementations.Session /// <param name="logger">The logger.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="loggerFactory">The logger factory.</param> - /// <param name="webSocketManager">The HTTP server.</param> public SessionWebSocketListener( ILogger<SessionWebSocketListener> logger, ISessionManager sessionManager, - ILoggerFactory loggerFactory, - IWebSocketManager webSocketManager) + ILoggerFactory loggerFactory) { _logger = logger; _sessionManager = sessionManager; _loggerFactory = loggerFactory; - _webSocketManager = webSocketManager; - - webSocketManager.WebSocketConnected += OnServerManagerWebSocketConnected; } - private async void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e) + /// <inheritdoc/> + public async void ProcessWebSocketConnected(IWebSocketConnection websocketConnection) { - var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint.ToString()); + var session = GetSession(websocketConnection.QueryString, websocketConnection.RemoteEndPoint.ToString()); if (session != null) { - EnsureController(session, e.Argument); - await KeepAliveWebSocket(e.Argument).ConfigureAwait(false); + EnsureController(session, websocketConnection); + await KeepAliveWebSocket(websocketConnection).ConfigureAwait(false); } else { - _logger.LogWarning("Unable to determine session based on query string: {0}", e.Argument.QueryString); + _logger.LogWarning("Unable to determine session based on query string: {Querystring}", websocketConnection.QueryString); } } @@ -122,7 +116,6 @@ namespace Emby.Server.Implementations.Session /// <inheritdoc /> public void Dispose() { - _webSocketManager.WebSocketConnected -= OnServerManagerWebSocketConnected; StopKeepAlive(); } diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index 288e03fcff..3dc45b1459 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class SessionInfoWebSocketListener. /// </summary> - public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState> + public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState>, IActivityLogWebSocketListener { /// <summary> /// The _kernel. diff --git a/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs new file mode 100644 index 0000000000..b23022e71d --- /dev/null +++ b/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs @@ -0,0 +1,10 @@ +#pragma warning disable CA1040 // Avoid empty interfaces +namespace Jellyfin.Api.WebSocketListeners +{ + /// <summary> + /// Defines the <see cref="IActivityLogWebSocketListener" />. + /// </summary> + public interface IActivityLogWebSocketListener + { + } +} diff --git a/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs new file mode 100644 index 0000000000..425d61dfa4 --- /dev/null +++ b/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs @@ -0,0 +1,10 @@ +#pragma warning disable CA1040 // Avoid empty interfaces +namespace Jellyfin.Api.WebSocketListeners +{ + /// <summary> + /// Defines the <see cref="IScheduledTasksWebSocketListener" />. + /// </summary> + public interface IScheduledTasksWebSocketListener + { + } +} diff --git a/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs new file mode 100644 index 0000000000..33636dc06d --- /dev/null +++ b/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs @@ -0,0 +1,10 @@ +#pragma warning disable CA1040 // Avoid empty interfaces +namespace Jellyfin.Api.WebSocketListeners +{ + /// <summary> + /// Defines the <see cref="ISessionInfoWebSocketListener" />. + /// </summary> + public interface ISessionInfoWebSocketListener + { + } +} diff --git a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs index 94df23e569..eafa9c71f0 100644 --- a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class ScheduledTasksWebSocketListener. /// </summary> - public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState> + public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState>, IScheduledTasksWebSocketListener { /// <summary> /// Gets or sets the task manager. @@ -66,19 +66,19 @@ namespace Jellyfin.Api.WebSocketListeners private void OnTaskCompleted(object? sender, TaskCompletionEventArgs e) { - SendData(true); + SendData(true).GetAwaiter().GetResult(); e.Task.TaskProgress -= OnTaskProgress; } private void OnTaskExecuting(object? sender, GenericEventArgs<IScheduledTaskWorker> e) { - SendData(true); + SendData(true).GetAwaiter().GetResult(); e.Argument.TaskProgress += OnTaskProgress; } private void OnTaskProgress(object? sender, GenericEventArgs<double> e) { - SendData(false); + SendData(false).GetAwaiter().GetResult(); } } } diff --git a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs index d996ac69f9..be701be45e 100644 --- a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class SessionInfoWebSocketListener. /// </summary> - public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState> + public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState>, ISessionInfoWebSocketListener { private readonly ISessionManager _sessionManager; diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 4b44537a59..100f3619a6 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -11,7 +11,6 @@ using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; using Jellyfin.Server.Implementations.Users; -using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Drawing; @@ -82,14 +81,10 @@ namespace Jellyfin.Server ServiceCollection.AddSingleton<IUserManager, UserManager>(); ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); - ServiceCollection.AddScoped<IWebSocketListener, ActivityLogWebSocketListener>(); - ServiceCollection.AddScoped<IWebSocketListener, ScheduledTasksWebSocketListener>(); - ServiceCollection.AddScoped<IWebSocketListener, SessionInfoWebSocketListener>(); - // This one has to be last as DI will select it for parameterization. - ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); - - // TODO fix circular dependency on IWebSocketManager - ServiceCollection.AddScoped(serviceProvider => new Lazy<IEnumerable<IWebSocketListener>>(serviceProvider.GetRequiredService<IEnumerable<IWebSocketListener>>)); + ServiceCollection.AddScoped<IActivityLogWebSocketListener, ActivityLogWebSocketListener>(); + ServiceCollection.AddScoped<IScheduledTasksWebSocketListener, ScheduledTasksWebSocketListener>(); + ServiceCollection.AddScoped<ISessionInfoWebSocketListener, SessionInfoWebSocketListener>(); + ServiceCollection.AddScoped<ISessionWebSocketListener, SessionWebSocketListener>(); base.RegisterServices(); } diff --git a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs index 53f32bebd1..ba0abfbdd4 100644 --- a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs +++ b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs @@ -25,19 +25,10 @@ namespace Jellyfin.Server.Middleware /// </summary> /// <param name="httpContext">The current HTTP context.</param> /// <param name="webSocketManager">The WebSocket connection manager.</param> - /// <param name="websocketListener">Session manager instance.</param> /// <returns>The async task.</returns> public async Task Invoke( HttpContext httpContext, - IWebSocketManager webSocketManager, -#pragma warning disable CA1801 -#pragma warning disable IDE0060 - // TODO: Workaround. see https://github.com/jellyfin/jellyfin/pull/3194 - // Do not remove this parameter. It uses DI to create a SessionWebSocketListener which is - // required for webSocketManager events. - IWebSocketListener websocketListener) -#pragma warning restore IDE0060 // Remove unused parameter -#pragma warning restore CA1801 + IWebSocketManager webSocketManager) { if (!httpContext.WebSockets.IsWebSocketRequest) { diff --git a/MediaBrowser.Controller/Net/IWebSocketManager.cs b/MediaBrowser.Controller/Net/IWebSocketManager.cs index ce74173e70..d3f31de7c8 100644 --- a/MediaBrowser.Controller/Net/IWebSocketManager.cs +++ b/MediaBrowser.Controller/Net/IWebSocketManager.cs @@ -11,11 +11,6 @@ namespace MediaBrowser.Controller.Net /// </summary> public interface IWebSocketManager { - /// <summary> - /// Occurs when [web socket connected]. - /// </summary> - event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; - /// <summary> /// The HTTP request handler. /// </summary> From 8814d9c5eaf71dfaa1f7e9da5391a15f61fd275f Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 28 Nov 2020 09:03:45 +0800 Subject: [PATCH 0554/1930] Apply suggestions from code review Co-authored-by: artiume <siderite@gmail.com> --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 9711084954..41dd3d081e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -48,7 +48,7 @@ RUN apt-get update \ locales \ # Intel VAAPI Tone mapping dependencies: # Prefer NEO to Beignet since the latter one doesn't support Comet Lake or newer for now. -# Do not use the intel-opencl-icd package from repo since they were not build with RELEASE_WITH_REGKEYS enabled. +# Do not use the intel-opencl-icd package from repo since they will not build with RELEASE_WITH_REGKEYS enabled. && mkdir intel-compute-runtime \ && cd intel-compute-runtime \ && wget https://github.com/intel/compute-runtime/releases/download/${NEO_VERSION}/intel-gmmlib_${GMMLIB_VERSION}_amd64.deb \ From 1458797330ebb6db5f6ccabaa9521107d9b54457 Mon Sep 17 00:00:00 2001 From: conashinck <ck1090739@gl.ck.tp.edu.tw> Date: Sat, 28 Nov 2020 00:44:20 +0000 Subject: [PATCH 0555/1930] Translated using Weblate (Chinese (Traditional)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant/ --- Emby.Server.Implementations/Localization/Core/zh-TW.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index d2e3d77a3a..52d2ba27f2 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -114,5 +114,8 @@ "TasksApplicationCategory": "應用程式", "TasksMaintenanceCategory": "維護", "TaskCleanActivityLogDescription": "刪除超過所設時間的活動紀錄。", - "TaskCleanActivityLog": "清除活動紀錄" + "TaskCleanActivityLog": "清除活動紀錄", + "Undefined": "未定義的", + "Forced": "強制", + "Default": "預設" } From f1b3811ca7ac7858d19cbd51549fde9fca04bdb9 Mon Sep 17 00:00:00 2001 From: conashinck <ck1090739@gl.ck.tp.edu.tw> Date: Sat, 28 Nov 2020 01:37:43 +0000 Subject: [PATCH 0556/1930] Translated using Weblate (Chinese (Traditional)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant/ --- Emby.Server.Implementations/Localization/Core/zh-TW.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index 52d2ba27f2..6494c0b544 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -117,5 +117,5 @@ "TaskCleanActivityLog": "清除活動紀錄", "Undefined": "未定義的", "Forced": "強制", - "Default": "預設" + "Default": "原本" } From f9f0df88d5aa0aa8bc58cefb05960662057daa21 Mon Sep 17 00:00:00 2001 From: hawken <hawken@thehawken.org> Date: Sat, 28 Nov 2020 09:14:58 +0100 Subject: [PATCH 0557/1930] allow JsonGuidConverter to read null --- MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs index 54325a02b0..52e08d071a 100644 --- a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs @@ -11,7 +11,11 @@ namespace MediaBrowser.Common.Json.Converters { /// <inheritdoc /> public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => new Guid(reader.GetString()); + { + var guidStr = reader.GetString(); + + return guidStr == null ? Guid.Empty : new Guid(guidStr); + } /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) From 1a0d8aef80a066fdefec4d757d5dcba0dfe0a03c Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 28 Nov 2020 09:50:16 +0100 Subject: [PATCH 0558/1930] Revert "Removed Lazy implementation." --- .../HttpServer/WebSocketManager.cs | 31 ++++++++++--------- .../Session/ISessionWebSocketListener.cs | 30 ------------------ .../Session/SessionWebSocketListener.cs | 27 ++++++++++------ .../ActivityLogWebSocketListener.cs | 2 +- .../IActivityLogWebSocketListener.cs | 10 ------ .../IScheduledTasksWebSocketListener.cs | 10 ------ .../ISessionInfoWebSocketListener.cs | 10 ------ .../ScheduledTasksWebSocketListener.cs | 8 ++--- .../SessionInfoWebSocketListener.cs | 2 +- Jellyfin.Server/CoreAppHost.cs | 13 +++++--- .../Middleware/WebSocketHandlerMiddleware.cs | 11 ++++++- .../Net/IWebSocketManager.cs | 5 +++ 12 files changed, 64 insertions(+), 95 deletions(-) delete mode 100644 Emby.Server.Implementations/Session/ISessionWebSocketListener.cs delete mode 100644 Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs delete mode 100644 Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs delete mode 100644 Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 5518fb95aa..71ece80a75 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -4,9 +4,7 @@ using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Threading.Tasks; -using Emby.Server.Implementations.Session; -using Jellyfin.Api.WebSocketListeners; -using MediaBrowser.Controller; +using Jellyfin.Data.Events; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -15,21 +13,24 @@ namespace Emby.Server.Implementations.HttpServer { public class WebSocketManager : IWebSocketManager { - private readonly IServerApplicationHost _appHost; + private readonly Lazy<IEnumerable<IWebSocketListener>> _webSocketListeners; private readonly ILogger<WebSocketManager> _logger; private readonly ILoggerFactory _loggerFactory; + private bool _disposed = false; public WebSocketManager( - IServerApplicationHost appHost, + Lazy<IEnumerable<IWebSocketListener>> webSocketListeners, ILogger<WebSocketManager> logger, ILoggerFactory loggerFactory) { - _appHost = appHost; + _webSocketListeners = webSocketListeners; _logger = logger; _loggerFactory = loggerFactory; } + public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; + /// <inheritdoc /> public async Task WebSocketRequestHandler(HttpContext context) { @@ -38,8 +39,6 @@ namespace Emby.Server.Implementations.HttpServer return; } - var listener = _appHost.Resolve<ISessionWebSocketListener>(); - try { _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress); @@ -55,7 +54,7 @@ namespace Emby.Server.Implementations.HttpServer OnReceive = ProcessWebSocketMessageReceived }; - listener?.ProcessWebSocketConnected(connection); + WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); await connection.ProcessAsync().ConfigureAwait(false); _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress); @@ -81,12 +80,16 @@ namespace Emby.Server.Implementations.HttpServer return Task.CompletedTask; } - Parallel.Invoke( - () => _appHost.Resolve<IActivityLogWebSocketListener>(), - () => _appHost.Resolve<IScheduledTasksWebSocketListener>(), - () => _appHost.Resolve<ISessionInfoWebSocketListener>()); + IEnumerable<Task> GetTasks() + { + var listeners = _webSocketListeners.Value; + foreach (var x in listeners) + { + yield return x.ProcessMessageAsync(result); + } + } - return Task.CompletedTask; + return Task.WhenAll(GetTasks()); } } } diff --git a/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs b/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs deleted file mode 100644 index 9b0b28e6ee..0000000000 --- a/Emby.Server.Implementations/Session/ISessionWebSocketListener.cs +++ /dev/null @@ -1,30 +0,0 @@ -namespace Emby.Server.Implementations.Session -{ - using System.Threading.Tasks; - using Jellyfin.Data.Events; - using MediaBrowser.Controller.Net; - - /// <summary> - /// Defines the <see cref="ISessionWebSocketListener" />. - /// </summary> - public interface ISessionWebSocketListener - { - /// <summary> - /// Runs processes due to a WebSocket connection event. - /// </summary> - /// <param name="websocketConnection">The <see cref="IWebSocketConnection"/> instance.</param> - void ProcessWebSocketConnected(IWebSocketConnection websocketConnection); - - /// <summary> - /// Disposes the object. - /// </summary> - void Dispose(); - - /// <summary> - /// Processes a message. - /// </summary> - /// <param name="message">The <see cref="WebSocketMessageInfo"/>.</param> - /// <returns>A <see cref="Task"/>.</returns> - Task ProcessMessageAsync(WebSocketMessageInfo message); - } -} diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 8f81ee1948..a5f8479537 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.Session /// <summary> /// Class SessionWebSocketListener. /// </summary> - public sealed class SessionWebSocketListener : ISessionWebSocketListener, IDisposable + public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable { /// <summary> /// The timeout in seconds after which a WebSocket is considered to be lost. @@ -45,13 +45,15 @@ namespace Emby.Server.Implementations.Session private readonly ILogger<SessionWebSocketListener> _logger; private readonly ILoggerFactory _loggerFactory; + private readonly IWebSocketManager _webSocketManager; + /// <summary> /// The KeepAlive cancellation token. /// </summary> private CancellationTokenSource _keepAliveCancellationToken; /// <summary> - /// Lock used for accessing the KeepAlive cancellation token. + /// Lock used for accesing the KeepAlive cancellation token. /// </summary> private readonly object _keepAliveLock = new object(); @@ -61,7 +63,7 @@ namespace Emby.Server.Implementations.Session private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>(); /// <summary> - /// Lock used for accessing the WebSockets watchlist. + /// Lock used for accesing the WebSockets watchlist. /// </summary> private readonly object _webSocketsLock = new object(); @@ -71,28 +73,32 @@ namespace Emby.Server.Implementations.Session /// <param name="logger">The logger.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="loggerFactory">The logger factory.</param> + /// <param name="webSocketManager">The HTTP server.</param> public SessionWebSocketListener( ILogger<SessionWebSocketListener> logger, ISessionManager sessionManager, - ILoggerFactory loggerFactory) + ILoggerFactory loggerFactory, + IWebSocketManager webSocketManager) { _logger = logger; _sessionManager = sessionManager; _loggerFactory = loggerFactory; + _webSocketManager = webSocketManager; + + webSocketManager.WebSocketConnected += OnServerManagerWebSocketConnected; } - /// <inheritdoc/> - public async void ProcessWebSocketConnected(IWebSocketConnection websocketConnection) + private async void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e) { - var session = GetSession(websocketConnection.QueryString, websocketConnection.RemoteEndPoint.ToString()); + var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint.ToString()); if (session != null) { - EnsureController(session, websocketConnection); - await KeepAliveWebSocket(websocketConnection).ConfigureAwait(false); + EnsureController(session, e.Argument); + await KeepAliveWebSocket(e.Argument).ConfigureAwait(false); } else { - _logger.LogWarning("Unable to determine session based on query string: {Querystring}", websocketConnection.QueryString); + _logger.LogWarning("Unable to determine session based on query string: {0}", e.Argument.QueryString); } } @@ -116,6 +122,7 @@ namespace Emby.Server.Implementations.Session /// <inheritdoc /> public void Dispose() { + _webSocketManager.WebSocketConnected -= OnServerManagerWebSocketConnected; StopKeepAlive(); } diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index 3dc45b1459..288e03fcff 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class SessionInfoWebSocketListener. /// </summary> - public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState>, IActivityLogWebSocketListener + public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<ActivityLogEntry[], WebSocketListenerState> { /// <summary> /// The _kernel. diff --git a/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs deleted file mode 100644 index b23022e71d..0000000000 --- a/Jellyfin.Api/WebSocketListeners/IActivityLogWebSocketListener.cs +++ /dev/null @@ -1,10 +0,0 @@ -#pragma warning disable CA1040 // Avoid empty interfaces -namespace Jellyfin.Api.WebSocketListeners -{ - /// <summary> - /// Defines the <see cref="IActivityLogWebSocketListener" />. - /// </summary> - public interface IActivityLogWebSocketListener - { - } -} diff --git a/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs deleted file mode 100644 index 425d61dfa4..0000000000 --- a/Jellyfin.Api/WebSocketListeners/IScheduledTasksWebSocketListener.cs +++ /dev/null @@ -1,10 +0,0 @@ -#pragma warning disable CA1040 // Avoid empty interfaces -namespace Jellyfin.Api.WebSocketListeners -{ - /// <summary> - /// Defines the <see cref="IScheduledTasksWebSocketListener" />. - /// </summary> - public interface IScheduledTasksWebSocketListener - { - } -} diff --git a/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs deleted file mode 100644 index 33636dc06d..0000000000 --- a/Jellyfin.Api/WebSocketListeners/ISessionInfoWebSocketListener.cs +++ /dev/null @@ -1,10 +0,0 @@ -#pragma warning disable CA1040 // Avoid empty interfaces -namespace Jellyfin.Api.WebSocketListeners -{ - /// <summary> - /// Defines the <see cref="ISessionInfoWebSocketListener" />. - /// </summary> - public interface ISessionInfoWebSocketListener - { - } -} diff --git a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs index eafa9c71f0..94df23e569 100644 --- a/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ScheduledTasksWebSocketListener.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class ScheduledTasksWebSocketListener. /// </summary> - public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState>, IScheduledTasksWebSocketListener + public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<TaskInfo>, WebSocketListenerState> { /// <summary> /// Gets or sets the task manager. @@ -66,19 +66,19 @@ namespace Jellyfin.Api.WebSocketListeners private void OnTaskCompleted(object? sender, TaskCompletionEventArgs e) { - SendData(true).GetAwaiter().GetResult(); + SendData(true); e.Task.TaskProgress -= OnTaskProgress; } private void OnTaskExecuting(object? sender, GenericEventArgs<IScheduledTaskWorker> e) { - SendData(true).GetAwaiter().GetResult(); + SendData(true); e.Argument.TaskProgress += OnTaskProgress; } private void OnTaskProgress(object? sender, GenericEventArgs<double> e) { - SendData(false).GetAwaiter().GetResult(); + SendData(false); } } } diff --git a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs index be701be45e..d996ac69f9 100644 --- a/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/SessionInfoWebSocketListener.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Api.WebSocketListeners /// <summary> /// Class SessionInfoWebSocketListener. /// </summary> - public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState>, ISessionInfoWebSocketListener + public class SessionInfoWebSocketListener : BasePeriodicWebSocketListener<IEnumerable<SessionInfo>, WebSocketListenerState> { private readonly ISessionManager _sessionManager; diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 100f3619a6..4b44537a59 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -11,6 +11,7 @@ using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; using Jellyfin.Server.Implementations.Users; +using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Drawing; @@ -81,10 +82,14 @@ namespace Jellyfin.Server ServiceCollection.AddSingleton<IUserManager, UserManager>(); ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); - ServiceCollection.AddScoped<IActivityLogWebSocketListener, ActivityLogWebSocketListener>(); - ServiceCollection.AddScoped<IScheduledTasksWebSocketListener, ScheduledTasksWebSocketListener>(); - ServiceCollection.AddScoped<ISessionInfoWebSocketListener, SessionInfoWebSocketListener>(); - ServiceCollection.AddScoped<ISessionWebSocketListener, SessionWebSocketListener>(); + ServiceCollection.AddScoped<IWebSocketListener, ActivityLogWebSocketListener>(); + ServiceCollection.AddScoped<IWebSocketListener, ScheduledTasksWebSocketListener>(); + ServiceCollection.AddScoped<IWebSocketListener, SessionInfoWebSocketListener>(); + // This one has to be last as DI will select it for parameterization. + ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); + + // TODO fix circular dependency on IWebSocketManager + ServiceCollection.AddScoped(serviceProvider => new Lazy<IEnumerable<IWebSocketListener>>(serviceProvider.GetRequiredService<IEnumerable<IWebSocketListener>>)); base.RegisterServices(); } diff --git a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs index ba0abfbdd4..53f32bebd1 100644 --- a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs +++ b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs @@ -25,10 +25,19 @@ namespace Jellyfin.Server.Middleware /// </summary> /// <param name="httpContext">The current HTTP context.</param> /// <param name="webSocketManager">The WebSocket connection manager.</param> + /// <param name="websocketListener">Session manager instance.</param> /// <returns>The async task.</returns> public async Task Invoke( HttpContext httpContext, - IWebSocketManager webSocketManager) + IWebSocketManager webSocketManager, +#pragma warning disable CA1801 +#pragma warning disable IDE0060 + // TODO: Workaround. see https://github.com/jellyfin/jellyfin/pull/3194 + // Do not remove this parameter. It uses DI to create a SessionWebSocketListener which is + // required for webSocketManager events. + IWebSocketListener websocketListener) +#pragma warning restore IDE0060 // Remove unused parameter +#pragma warning restore CA1801 { if (!httpContext.WebSockets.IsWebSocketRequest) { diff --git a/MediaBrowser.Controller/Net/IWebSocketManager.cs b/MediaBrowser.Controller/Net/IWebSocketManager.cs index d3f31de7c8..ce74173e70 100644 --- a/MediaBrowser.Controller/Net/IWebSocketManager.cs +++ b/MediaBrowser.Controller/Net/IWebSocketManager.cs @@ -11,6 +11,11 @@ namespace MediaBrowser.Controller.Net /// </summary> public interface IWebSocketManager { + /// <summary> + /// Occurs when [web socket connected]. + /// </summary> + event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; + /// <summary> /// The HTTP request handler. /// </summary> From 3ae39d44da8816f0383c41848e4394f7e0bf96ac Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 28 Nov 2020 09:50:30 +0100 Subject: [PATCH 0559/1930] Revert "Fixed SessionWebSocketListener.OnServerManagerWebSocketConnected." --- .../ActivityLogWebSocketListener.cs | 2 +- Jellyfin.Server/CoreAppHost.cs | 3 +-- .../Middleware/WebSocketHandlerMiddleware.cs | 13 +------------ 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index 288e03fcff..ce54651166 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Api.WebSocketListeners private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) { - SendData(true).GetAwaiter().GetResult(); + SendData(true); } } } diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 4b44537a59..78f596a5c9 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -82,11 +82,10 @@ namespace Jellyfin.Server ServiceCollection.AddSingleton<IUserManager, UserManager>(); ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); + ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, ActivityLogWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, ScheduledTasksWebSocketListener>(); ServiceCollection.AddScoped<IWebSocketListener, SessionInfoWebSocketListener>(); - // This one has to be last as DI will select it for parameterization. - ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); // TODO fix circular dependency on IWebSocketManager ServiceCollection.AddScoped(serviceProvider => new Lazy<IEnumerable<IWebSocketListener>>(serviceProvider.GetRequiredService<IEnumerable<IWebSocketListener>>)); diff --git a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs index 53f32bebd1..b7a5d2b346 100644 --- a/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs +++ b/Jellyfin.Server/Middleware/WebSocketHandlerMiddleware.cs @@ -25,19 +25,8 @@ namespace Jellyfin.Server.Middleware /// </summary> /// <param name="httpContext">The current HTTP context.</param> /// <param name="webSocketManager">The WebSocket connection manager.</param> - /// <param name="websocketListener">Session manager instance.</param> /// <returns>The async task.</returns> - public async Task Invoke( - HttpContext httpContext, - IWebSocketManager webSocketManager, -#pragma warning disable CA1801 -#pragma warning disable IDE0060 - // TODO: Workaround. see https://github.com/jellyfin/jellyfin/pull/3194 - // Do not remove this parameter. It uses DI to create a SessionWebSocketListener which is - // required for webSocketManager events. - IWebSocketListener websocketListener) -#pragma warning restore IDE0060 // Remove unused parameter -#pragma warning restore CA1801 + public async Task Invoke(HttpContext httpContext, IWebSocketManager webSocketManager) { if (!httpContext.WebSockets.IsWebSocketRequest) { From 65e6211c035c2269584220f1a3dcc0bb37374e01 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 28 Nov 2020 11:21:53 +0100 Subject: [PATCH 0560/1930] Remove circular dependency between websocket listeners and manager --- .../HttpServer/WebSocketManager.cs | 41 ++++----- .../Session/SessionWebSocketListener.cs | 90 +++++++++---------- .../ActivityLogWebSocketListener.cs | 2 +- Jellyfin.Server/CoreAppHost.cs | 12 ++- .../Net/BasePeriodicWebSocketListener.cs | 2 + .../Net/IWebSocketListener.cs | 9 +- .../Net/IWebSocketManager.cs | 8 -- 7 files changed, 72 insertions(+), 92 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 71ece80a75..d6cf6233e4 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net.WebSockets; using System.Threading.Tasks; -using Jellyfin.Data.Events; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -13,32 +13,23 @@ namespace Emby.Server.Implementations.HttpServer { public class WebSocketManager : IWebSocketManager { - private readonly Lazy<IEnumerable<IWebSocketListener>> _webSocketListeners; + private readonly IWebSocketListener[] _webSocketListeners; private readonly ILogger<WebSocketManager> _logger; private readonly ILoggerFactory _loggerFactory; - private bool _disposed = false; - public WebSocketManager( - Lazy<IEnumerable<IWebSocketListener>> webSocketListeners, + IEnumerable<IWebSocketListener> webSocketListeners, ILogger<WebSocketManager> logger, ILoggerFactory loggerFactory) { - _webSocketListeners = webSocketListeners; + _webSocketListeners = webSocketListeners.ToArray(); _logger = logger; _loggerFactory = loggerFactory; } - public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; - /// <inheritdoc /> public async Task WebSocketRequestHandler(HttpContext context) { - if (_disposed) - { - return; - } - try { _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress); @@ -54,7 +45,13 @@ namespace Emby.Server.Implementations.HttpServer OnReceive = ProcessWebSocketMessageReceived }; - WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); + var tasks = new Task[_webSocketListeners.Length]; + for (var i = 0; i < _webSocketListeners.Length; ++i) + { + tasks[i] = _webSocketListeners[i].ProcessWebSocketConnectedAsync(connection); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); await connection.ProcessAsync().ConfigureAwait(false); _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress); @@ -75,21 +72,13 @@ namespace Emby.Server.Implementations.HttpServer /// <param name="result">The result.</param> private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result) { - if (_disposed) + var tasks = new Task[_webSocketListeners.Length]; + for (var i = 0; i < _webSocketListeners.Length; ++i) { - return Task.CompletedTask; + tasks[i] = _webSocketListeners[i].ProcessMessageAsync(result); } - IEnumerable<Task> GetTasks() - { - var listeners = _webSocketListeners.Value; - foreach (var x in listeners) - { - yield return x.ProcessMessageAsync(result); - } - } - - return Task.WhenAll(GetTasks()); + return Task.WhenAll(tasks); } } } diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index a5f8479537..169eaefd8b 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Data.Events; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Net; @@ -22,35 +21,17 @@ namespace Emby.Server.Implementations.Session /// <summary> /// The timeout in seconds after which a WebSocket is considered to be lost. /// </summary> - public const int WebSocketLostTimeout = 60; + private const int WebSocketLostTimeout = 60; /// <summary> /// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets. /// </summary> - public const float IntervalFactor = 0.2f; + private const float IntervalFactor = 0.2f; /// <summary> /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent. /// </summary> - public const float ForceKeepAliveFactor = 0.75f; - - /// <summary> - /// The _session manager. - /// </summary> - private readonly ISessionManager _sessionManager; - - /// <summary> - /// The _logger. - /// </summary> - private readonly ILogger<SessionWebSocketListener> _logger; - private readonly ILoggerFactory _loggerFactory; - - private readonly IWebSocketManager _webSocketManager; - - /// <summary> - /// The KeepAlive cancellation token. - /// </summary> - private CancellationTokenSource _keepAliveCancellationToken; + private const float ForceKeepAliveFactor = 0.75f; /// <summary> /// Lock used for accesing the KeepAlive cancellation token. @@ -63,42 +44,68 @@ namespace Emby.Server.Implementations.Session private readonly HashSet<IWebSocketConnection> _webSockets = new HashSet<IWebSocketConnection>(); /// <summary> - /// Lock used for accesing the WebSockets watchlist. + /// Lock used for accessing the WebSockets watchlist. /// </summary> private readonly object _webSocketsLock = new object(); + /// <summary> + /// The _session manager. + /// </summary> + private readonly ISessionManager _sessionManager; + + /// <summary> + /// The _logger. + /// </summary> + private readonly ILogger<SessionWebSocketListener> _logger; + private readonly ILoggerFactory _loggerFactory; + + /// <summary> + /// The KeepAlive cancellation token. + /// </summary> + private CancellationTokenSource _keepAliveCancellationToken; + /// <summary> /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class. /// </summary> /// <param name="logger">The logger.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="loggerFactory">The logger factory.</param> - /// <param name="webSocketManager">The HTTP server.</param> public SessionWebSocketListener( ILogger<SessionWebSocketListener> logger, ISessionManager sessionManager, - ILoggerFactory loggerFactory, - IWebSocketManager webSocketManager) + ILoggerFactory loggerFactory) { _logger = logger; _sessionManager = sessionManager; _loggerFactory = loggerFactory; - _webSocketManager = webSocketManager; - - webSocketManager.WebSocketConnected += OnServerManagerWebSocketConnected; } - private async void OnServerManagerWebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e) + /// <inheritdoc /> + public void Dispose() { - var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint.ToString()); + StopKeepAlive(); + } + + /// <summary> + /// Processes the message. + /// </summary> + /// <param name="message">The message.</param> + /// <returns>Task.</returns> + public Task ProcessMessageAsync(WebSocketMessageInfo message) + => Task.CompletedTask; + + /// <inheritdoc /> + public async Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection) + { + var session = GetSession(connection.QueryString, connection.RemoteEndPoint.ToString()); if (session != null) { - EnsureController(session, e.Argument); - await KeepAliveWebSocket(e.Argument).ConfigureAwait(false); + EnsureController(session, connection); + await KeepAliveWebSocket(connection).ConfigureAwait(false); } else { - _logger.LogWarning("Unable to determine session based on query string: {0}", e.Argument.QueryString); + _logger.LogWarning("Unable to determine session based on query string: {0}", connection.QueryString); } } @@ -119,21 +126,6 @@ namespace Emby.Server.Implementations.Session return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint); } - /// <inheritdoc /> - public void Dispose() - { - _webSocketManager.WebSocketConnected -= OnServerManagerWebSocketConnected; - StopKeepAlive(); - } - - /// <summary> - /// Processes the message. - /// </summary> - /// <param name="message">The message.</param> - /// <returns>Task.</returns> - public Task ProcessMessageAsync(WebSocketMessageInfo message) - => Task.CompletedTask; - private void EnsureController(SessionInfo session, IWebSocketConnection connection) { var controllerInfo = session.EnsureController<WebSocketController>( diff --git a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs index ce54651166..288e03fcff 100644 --- a/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs +++ b/Jellyfin.Api/WebSocketListeners/ActivityLogWebSocketListener.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Api.WebSocketListeners private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) { - SendData(true); + SendData(true).GetAwaiter().GetResult(); } } } diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index 78f596a5c9..b76aa5e141 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -82,13 +82,11 @@ namespace Jellyfin.Server ServiceCollection.AddSingleton<IUserManager, UserManager>(); ServiceCollection.AddSingleton<IDisplayPreferencesManager, DisplayPreferencesManager>(); - ServiceCollection.AddScoped<IWebSocketListener, SessionWebSocketListener>(); - ServiceCollection.AddScoped<IWebSocketListener, ActivityLogWebSocketListener>(); - ServiceCollection.AddScoped<IWebSocketListener, ScheduledTasksWebSocketListener>(); - ServiceCollection.AddScoped<IWebSocketListener, SessionInfoWebSocketListener>(); - - // TODO fix circular dependency on IWebSocketManager - ServiceCollection.AddScoped(serviceProvider => new Lazy<IEnumerable<IWebSocketListener>>(serviceProvider.GetRequiredService<IEnumerable<IWebSocketListener>>)); + // TODO search the assemblies instead of adding them manually? + ServiceCollection.AddSingleton<IWebSocketListener, SessionWebSocketListener>(); + ServiceCollection.AddSingleton<IWebSocketListener, ActivityLogWebSocketListener>(); + ServiceCollection.AddSingleton<IWebSocketListener, ScheduledTasksWebSocketListener>(); + ServiceCollection.AddSingleton<IWebSocketListener, SessionInfoWebSocketListener>(); base.RegisterServices(); } diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index 28227603b2..bbcfe77753 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -92,6 +92,8 @@ namespace MediaBrowser.Controller.Net return Task.CompletedTask; } + public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection) => Task.CompletedTask; + /// <summary> /// Starts sending messages over a web socket. /// </summary> diff --git a/MediaBrowser.Controller/Net/IWebSocketListener.cs b/MediaBrowser.Controller/Net/IWebSocketListener.cs index 7250a57b0a..f1a75d5180 100644 --- a/MediaBrowser.Controller/Net/IWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/IWebSocketListener.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; namespace MediaBrowser.Controller.Net { /// <summary> - ///This is an interface for listening to messages coming through a web socket connection. + /// Interface for listening to messages coming through a web socket connection. /// </summary> public interface IWebSocketListener { @@ -13,5 +13,12 @@ namespace MediaBrowser.Controller.Net /// <param name="message">The message.</param> /// <returns>Task.</returns> Task ProcessMessageAsync(WebSocketMessageInfo message); + + /// <summary> + /// Processes a new web socket connection. + /// </summary> + /// <param name="connection">An instance of the <see cref="IWebSocketConnection"/> interface.</param> + /// <returns>Task.</returns> + Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection); } } diff --git a/MediaBrowser.Controller/Net/IWebSocketManager.cs b/MediaBrowser.Controller/Net/IWebSocketManager.cs index ce74173e70..bb0ae83bea 100644 --- a/MediaBrowser.Controller/Net/IWebSocketManager.cs +++ b/MediaBrowser.Controller/Net/IWebSocketManager.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Threading.Tasks; -using Jellyfin.Data.Events; using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller.Net @@ -11,11 +8,6 @@ namespace MediaBrowser.Controller.Net /// </summary> public interface IWebSocketManager { - /// <summary> - /// Occurs when [web socket connected]. - /// </summary> - event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected; - /// <summary> /// The HTTP request handler. /// </summary> From ba78ad5424842e4b11bc04336f52a0ef81f42147 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 28 Nov 2020 11:24:52 +0100 Subject: [PATCH 0561/1930] Add missing inheritdoc --- MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index bbcfe77753..163a9c8f86 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -92,6 +92,7 @@ namespace MediaBrowser.Controller.Net return Task.CompletedTask; } + /// <inheritdoc /> public Task ProcessWebSocketConnectedAsync(IWebSocketConnection connection) => Task.CompletedTask; /// <summary> From d19edefbcd020e58031c8bf1101bf20328257303 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 28 Nov 2020 20:55:09 +0800 Subject: [PATCH 0562/1930] fix image extraction --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 5f60c09ae7..2a979e857e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -553,12 +553,18 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; - var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase); // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. - var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty; + var enableThumbnail = useIFrame && !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase); + if (string.IsNullOrEmpty(vf)) + { + vf = enableThumbnail ? "-vf thumbnail=24" : string.Empty; + } + else + { + vf += enableThumbnail ? ",thumbnail=24" : string.Empty; + } - var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {5} -v quiet -vframes 1 {2}{4} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail, threads) : - string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); + var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); From 53c91c2c145535f40f391f1b8d986078f10e3428 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 28 Nov 2020 21:14:55 +0800 Subject: [PATCH 0563/1930] Apply suggestions from code review Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 2a979e857e..f8a704efdf 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -554,7 +554,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. - var enableThumbnail = useIFrame && !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase); + var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(vf)) { vf = enableThumbnail ? "-vf thumbnail=24" : string.Empty; From c60714e36518ab1ea3a2a5b64999d5fb7462460c Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sat, 28 Nov 2020 14:19:24 +0100 Subject: [PATCH 0564/1930] Move query parameters to request body in SyncPlay --- .../SyncPlay/GroupController.cs | 7 +- .../SyncPlay/SyncPlayManager.cs | 11 +- .../Controllers/SyncPlayController.cs | 148 +++++++++--------- .../SyncPlay/IGroupController.cs | 7 +- .../SyncPlay/ISyncPlayManager.cs | 5 +- .../PlaybackRequests/PlayGroupRequest.cs | 2 +- .../PlaybackRequests/QueueGroupRequest.cs | 2 +- .../RemoveFromPlaylistGroupRequest.cs | 2 +- .../SyncPlay/JoinGroupRequest.cs | 25 --- .../SyncPlay/NewGroupRequest.cs | 23 --- .../RequestBodies/BufferRequestBody.cs | 42 +++++ .../RequestBodies/IgnoreWaitRequestBody.cs | 14 ++ .../RequestBodies/JoinGroupRequestBody.cs | 16 ++ .../MovePlaylistItemRequestBody.cs | 28 ++++ .../RequestBodies/NewGroupRequestBody.cs | 22 +++ .../RequestBodies/NextTrackRequestBody.cs | 22 +++ .../SyncPlay/RequestBodies/PingRequestBody.cs | 14 ++ .../SyncPlay/RequestBodies/PlayRequestBody.cs | 37 +++++ .../RequestBodies/PreviousTrackRequestBody.cs | 22 +++ .../RequestBodies/QueueRequestBody.cs | 31 ++++ .../RequestBodies/ReadyRequestBody.cs | 42 +++++ .../RemoveFromPlaylistRequestBody.cs | 25 +++ .../SyncPlay/RequestBodies/SeekRequestBody.cs | 14 ++ .../SetPlaylistItemRequestBody.cs | 22 +++ .../RequestBodies/SetRepeatModeRequestBody.cs | 14 ++ .../SetShuffleModeRequestBody.cs | 14 ++ 26 files changed, 475 insertions(+), 136 deletions(-) delete mode 100644 MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs delete mode 100644 MediaBrowser.Model/SyncPlay/NewGroupRequest.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs create mode 100644 MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 31df8404b4..612fba5048 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -13,6 +13,7 @@ using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.SyncPlay.GroupStates; using MediaBrowser.Controller.SyncPlay.Queue; using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay @@ -256,7 +257,7 @@ namespace Emby.Server.Implementations.SyncPlay public bool IsGroupEmpty() => _participants.Count == 0; /// <inheritdoc /> - public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) + public void CreateGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken) { GroupName = request.GroupName; AddSession(session); @@ -291,7 +292,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) + public void SessionJoin(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken) { AddSession(session); @@ -307,7 +308,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) + public void SessionRestore(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken) { var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index be94c39825..5a0d619269 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -1,12 +1,12 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay @@ -94,7 +94,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) + public void NewGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken) { // TODO: create abstract class for GroupRequests to avoid explicit request type here. if (!IsRequestValid(session, GroupRequestType.NewGroup, request)) @@ -124,7 +124,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken) + public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequestBody request, CancellationToken cancellationToken) { // TODO: create abstract class for GroupRequests to avoid explicit request type here. if (!IsRequestValid(session, GroupRequestType.JoinGroup, request)) @@ -304,7 +304,10 @@ namespace Emby.Server.Implementations.SyncPlay return; } - var request = new JoinGroupRequest(groupId); + var request = new JoinGroupRequestBody() + { + GroupId = groupId + }; JoinGroup(session, groupId, request, CancellationToken.None); } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 530cce1ea7..e8c9a09568 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -9,6 +9,7 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -44,34 +45,32 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Create a new SyncPlay group. /// </summary> - /// <param name="groupName">The name of the new group.</param> + /// <param name="requestData">The settings of the new group.</param> /// <response code="204">New group created.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("New")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayCreateGroup( - [FromQuery, Required] string groupName) + [FromBody, Required] NewGroupRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var newGroupRequest = new NewGroupRequest(groupName); - _syncPlayManager.NewGroup(currentSession, newGroupRequest, CancellationToken.None); + _syncPlayManager.NewGroup(currentSession, requestData, CancellationToken.None); return NoContent(); } /// <summary> /// Join an existing SyncPlay group. /// </summary> - /// <param name="groupId">The sync play group id.</param> + /// <param name="requestData">The group to join.</param> /// <response code="204">Group join successful.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Join")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayJoinGroup( - [FromQuery, Required] Guid groupId) + [FromBody, Required] JoinGroupRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var joinRequest = new JoinGroupRequest(groupId); - _syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None); + _syncPlayManager.JoinGroup(currentSession, requestData.GroupId, requestData, CancellationToken.None); return NoContent(); } @@ -105,20 +104,19 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request play in SyncPlay group. /// </summary> - /// <param name="playingQueue">The playing queue. Item ids in the playing queue, comma delimited.</param> - /// <param name="playingItemPosition">The playing item position from the queue.</param> - /// <param name="startPositionTicks">The start position ticks.</param> + /// <param name="requestData">The new playlist to play in the group.</param> /// <response code="204">Play request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Play")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPlay( - [FromQuery, Required] Guid[] playingQueue, - [FromQuery, Required] int playingItemPosition, - [FromQuery, Required] long startPositionTicks) + [FromBody, Required] PlayRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PlayGroupRequest(playingQueue, playingItemPosition, startPositionTicks); + var syncPlayRequest = new PlayGroupRequest( + requestData.PlayingQueue, + requestData.PlayingItemPosition, + requestData.StartPositionTicks); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -126,16 +124,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to change playlist item in SyncPlay group. /// </summary> - /// <param name="playlistItemId">The playlist id of the item.</param> + /// <param name="requestData">The new item to play.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetPlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetPlaylistItem( - [FromQuery, Required] string playlistItemId) + [FromBody, Required] SetPlaylistItemRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetPlaylistItemGroupRequest(playlistItemId); + var syncPlayRequest = new SetPlaylistItemGroupRequest(requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -143,16 +141,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to remove items from the playlist in SyncPlay group. /// </summary> - /// <param name="playlistItemIds">The playlist ids of the items to remove.</param> + /// <param name="requestData">The items to remove.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("RemoveFromPlaylist")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayRemoveFromPlaylist( - [FromQuery, Required] string[] playlistItemIds) + [FromBody, Required] RemoveFromPlaylistRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new RemoveFromPlaylistGroupRequest(playlistItemIds); + var syncPlayRequest = new RemoveFromPlaylistGroupRequest(requestData.PlaylistItemIds); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -160,18 +158,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to move an item in the playlist in SyncPlay group. /// </summary> - /// <param name="playlistItemId">The playlist id of the item to move.</param> - /// <param name="newIndex">The new position.</param> + /// <param name="requestData">The new position for the item.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("MovePlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayMovePlaylistItem( - [FromQuery, Required] string playlistItemId, - [FromQuery, Required] int newIndex) + [FromBody, Required] MovePlaylistItemRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new MovePlaylistItemGroupRequest(playlistItemId, newIndex); + var syncPlayRequest = new MovePlaylistItemGroupRequest(requestData.PlaylistItemId, requestData.NewIndex); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -179,18 +175,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to queue items to the playlist of a SyncPlay group. /// </summary> - /// <param name="itemIds">The items to add.</param> - /// <param name="mode">The mode in which to enqueue the items.</param> + /// <param name="requestData">The items to add.</param> /// <response code="204">Queue update request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayQueue( - [FromQuery, Required] Guid[] itemIds, - [FromQuery, Required] GroupQueueMode mode) + [FromBody, Required] QueueRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new QueueGroupRequest(itemIds, mode); + var syncPlayRequest = new QueueGroupRequest(requestData.ItemIds, requestData.Mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -243,50 +237,58 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request seek in SyncPlay group. /// </summary> - /// <param name="positionTicks">The playback position in ticks.</param> + /// <param name="requestData">The new playback position.</param> /// <response code="204">Seek request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Seek")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySeek( - [FromQuery, Required] long positionTicks) + [FromBody, Required] SeekRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SeekGroupRequest(positionTicks); + var syncPlayRequest = new SeekGroupRequest(requestData.PositionTicks); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } /// <summary> - /// Request group wait in SyncPlay group while buffering. + /// Notify SyncPlay group that member is buffering. /// </summary> - /// <param name="when">When the request has been made by the client.</param> - /// <param name="positionTicks">The playback position in ticks.</param> - /// <param name="isPlaying">Whether the client's playback is playing or not.</param> - /// <param name="playlistItemId">The playlist item id.</param> - /// <param name="bufferingDone">Whether the buffering is done.</param> - /// <response code="204">Buffering request sent to all group members.</response> + /// <param name="requestData">The player status.</param> + /// <response code="204">Group state update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Buffering")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayBuffering( - [FromQuery, Required] DateTime when, - [FromQuery, Required] long positionTicks, - [FromQuery, Required] bool isPlaying, - [FromQuery, Required] string playlistItemId, - [FromQuery, Required] bool bufferingDone) + [FromBody, Required] BufferRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - IGroupPlaybackRequest syncPlayRequest; - if (!bufferingDone) - { - syncPlayRequest = new BufferGroupRequest(when, positionTicks, isPlaying, playlistItemId); - } - else - { - syncPlayRequest = new ReadyGroupRequest(when, positionTicks, isPlaying, playlistItemId); - } + var syncPlayRequest = new BufferGroupRequest( + requestData.When, + requestData.PositionTicks, + requestData.IsPlaying, + requestData.PlaylistItemId); + _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); + return NoContent(); + } + /// <summary> + /// Notify SyncPlay group that member is ready for playback. + /// </summary> + /// <param name="requestData">The player status.</param> + /// <response code="204">Group state update sent to all group members.</response> + /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> + [HttpPost("Ready")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult SyncPlayReady( + [FromBody, Required] ReadyRequestBody requestData) + { + var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); + var syncPlayRequest = new ReadyGroupRequest( + requestData.When, + requestData.PositionTicks, + requestData.IsPlaying, + requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -294,16 +296,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request SyncPlay group to ignore member during group-wait. /// </summary> - /// <param name="ignoreWait">Whether to ignore the member.</param> + /// <param name="requestData">The settings to set.</param> /// <response code="204">Member state updated.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetIgnoreWait")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetIgnoreWait( - [FromQuery, Required] bool ignoreWait) + [FromBody, Required] IgnoreWaitRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new IgnoreWaitGroupRequest(ignoreWait); + var syncPlayRequest = new IgnoreWaitGroupRequest(requestData.IgnoreWait); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -311,16 +313,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request next track in SyncPlay group. /// </summary> - /// <param name="playlistItemId">The playing item id.</param> + /// <param name="requestData">The current track information.</param> /// <response code="204">Next track request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("NextTrack")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayNextTrack( - [FromQuery, Required] string playlistItemId) + [FromBody, Required] NextTrackRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new NextTrackGroupRequest(playlistItemId); + var syncPlayRequest = new NextTrackGroupRequest(requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -328,16 +330,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request previous track in SyncPlay group. /// </summary> - /// <param name="playlistItemId">The playing item id.</param> + /// <param name="requestData">The current track information.</param> /// <response code="204">Previous track request sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("PreviousTrack")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPreviousTrack( - [FromQuery, Required] string playlistItemId) + [FromBody, Required] PreviousTrackRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PreviousTrackGroupRequest(playlistItemId); + var syncPlayRequest = new PreviousTrackGroupRequest(requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -345,16 +347,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to set repeat mode in SyncPlay group. /// </summary> - /// <param name="mode">The repeat mode.</param> + /// <param name="requestData">The new repeat mode.</param> /// <response code="204">Play queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetRepeatMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetRepeatMode( - [FromQuery, Required] GroupRepeatMode mode) + [FromBody, Required] SetRepeatModeRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetRepeatModeGroupRequest(mode); + var syncPlayRequest = new SetRepeatModeGroupRequest(requestData.Mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -362,16 +364,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request to set shuffle mode in SyncPlay group. /// </summary> - /// <param name="mode">The shuffle mode.</param> + /// <param name="requestData">The new shuffle mode.</param> /// <response code="204">Play queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetShuffleMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetShuffleMode( - [FromQuery, Required] GroupShuffleMode mode) + [FromBody, Required] SetShuffleModeRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new SetShuffleModeGroupRequest(mode); + var syncPlayRequest = new SetShuffleModeGroupRequest(requestData.Mode); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -379,16 +381,16 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Update session ping. /// </summary> - /// <param name="ping">The ping.</param> + /// <param name="requestData">The new ping.</param> /// <response code="204">Ping updated.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Ping")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPing( - [FromQuery, Required] double ping) + [FromBody, Required] PingRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PingGroupRequest(Convert.ToInt64(ping)); + var syncPlayRequest = new PingGroupRequest(requestData.Ping); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } diff --git a/MediaBrowser.Controller/SyncPlay/IGroupController.cs b/MediaBrowser.Controller/SyncPlay/IGroupController.cs index aa8bb9eaea..5bcc3e2ca3 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupController.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupController.cs @@ -4,6 +4,7 @@ using Jellyfin.Data.Entities; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.Queue; using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Model.SyncPlay.RequestBodies; namespace MediaBrowser.Controller.SyncPlay { @@ -36,7 +37,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); + void CreateGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken); /// <summary> /// Adds the session to the group. @@ -44,7 +45,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); + void SessionJoin(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken); /// <summary> /// Restores the state of a session that already joined the group. @@ -52,7 +53,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); + void SessionRestore(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken); /// <summary> /// Removes the session from the group. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index a980016827..26fcb009ca 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; +using MediaBrowser.Model.SyncPlay.RequestBodies; namespace MediaBrowser.Controller.SyncPlay { @@ -17,7 +18,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session that's creating the group.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); + void NewGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken); /// <summary> /// Adds the session to a group. @@ -26,7 +27,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="groupId">The group identifier.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken); + void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequestBody request, CancellationToken cancellationToken); /// <summary> /// Removes the session from a group. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index 7d27f61518..dbe2987357 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="playingQueue">The playing queue.</param> /// <param name="playingItemPosition">The playing item position.</param> /// <param name="startPositionTicks">The start position ticks.</param> - public PlayGroupRequest(Guid[] playingQueue, int playingItemPosition, long startPositionTicks) + public PlayGroupRequest(IReadOnlyList<Guid> playingQueue, int playingItemPosition, long startPositionTicks) { PlayingQueue = playingQueue ?? Array.Empty<Guid>(); PlayingItemPosition = playingItemPosition; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index 106daecc8c..d6247ddd6d 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// </summary> /// <param name="items">The items to add to the queue.</param> /// <param name="mode">The enqueue mode.</param> - public QueueGroupRequest(Guid[] items, GroupQueueMode mode) + public QueueGroupRequest(IReadOnlyList<Guid> items, GroupQueueMode mode) { ItemIds = items ?? Array.Empty<Guid>(); Mode = mode; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index 1e892d8196..dc7ba8465c 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Initializes a new instance of the <see cref="RemoveFromPlaylistGroupRequest"/> class. /// </summary> /// <param name="items">The playlist ids of the items to remove.</param> - public RemoveFromPlaylistGroupRequest(string[] items) + public RemoveFromPlaylistGroupRequest(IReadOnlyList<string> items) { PlaylistItemIds = items ?? Array.Empty<string>(); } diff --git a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs b/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs deleted file mode 100644 index 7402c4ce29..0000000000 --- a/MediaBrowser.Model/SyncPlay/JoinGroupRequest.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace MediaBrowser.Model.SyncPlay -{ - /// <summary> - /// Class JoinGroupRequest. - /// </summary> - public class JoinGroupRequest - { - /// <summary> - /// Initializes a new instance of the <see cref="JoinGroupRequest"/> class. - /// </summary> - /// <param name="groupId">The identifier of the group to join.</param> - public JoinGroupRequest(Guid groupId) - { - GroupId = groupId; - } - - /// <summary> - /// Gets the group identifier. - /// </summary> - /// <value>The identifier of the group to join.</value> - public Guid GroupId { get; } - } -} diff --git a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs b/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs deleted file mode 100644 index ba4bd3ef1c..0000000000 --- a/MediaBrowser.Model/SyncPlay/NewGroupRequest.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace MediaBrowser.Model.SyncPlay -{ - /// <summary> - /// Class NewGroupRequest. - /// </summary> - public class NewGroupRequest - { - /// <summary> - /// Initializes a new instance of the <see cref="NewGroupRequest"/> class. - /// </summary> - /// <param name="groupName">The name of the new group.</param> - public NewGroupRequest(string groupName) - { - GroupName = groupName; - } - - /// <summary> - /// Gets the group name. - /// </summary> - /// <value>The name of the new group.</value> - public string GroupName { get; } - } -} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs new file mode 100644 index 0000000000..09ca712e51 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs @@ -0,0 +1,42 @@ +using System; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class BufferRequestBody. + /// </summary> + public class BufferRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="BufferRequestBody"/> class. + /// </summary> + public BufferRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets when the request has been made by the client. + /// </summary> + /// <value>The date of the request.</value> + public DateTime When { get; set; } + + /// <summary> + /// Gets or sets the position ticks. + /// </summary> + /// <value>The position ticks.</value> + public long PositionTicks { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the client playback is unpaused. + /// </summary> + /// <value>The client playback status.</value> + public bool IsPlaying { get; set; } + + /// <summary> + /// Gets or sets the playlist item identifier of the playing item. + /// </summary> + /// <value>The playlist item identifier.</value> + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs new file mode 100644 index 0000000000..22407e88ed --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs @@ -0,0 +1,14 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class IgnoreWaitRequestBody. + /// </summary> + public class IgnoreWaitRequestBody + { + /// <summary> + /// Gets or sets a value indicating whether the client should be ignored. + /// </summary> + /// <value>The client group-wait status.</value> + public bool IgnoreWait { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs new file mode 100644 index 0000000000..2cec7bdc21 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs @@ -0,0 +1,16 @@ +using System; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class JoinGroupRequestBody. + /// </summary> + public class JoinGroupRequestBody + { + /// <summary> + /// Gets or sets the group identifier. + /// </summary> + /// <value>The identifier of the group to join.</value> + public Guid GroupId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs new file mode 100644 index 0000000000..d18eb68ffe --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs @@ -0,0 +1,28 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class MovePlaylistItemRequestBody. + /// </summary> + public class MovePlaylistItemRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="MovePlaylistItemRequestBody"/> class. + /// </summary> + public MovePlaylistItemRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets the playlist identifier of the item. + /// </summary> + /// <value>The playlist identifier of the item.</value> + public string PlaylistItemId { get; set; } + + /// <summary> + /// Gets or sets the new position. + /// </summary> + /// <value>The new position.</value> + public int NewIndex { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs new file mode 100644 index 0000000000..1a85d276b9 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs @@ -0,0 +1,22 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class NewGroupRequestBody. + /// </summary> + public class NewGroupRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="NewGroupRequestBody"/> class. + /// </summary> + public NewGroupRequestBody() + { + GroupName = string.Empty; + } + + /// <summary> + /// Gets or sets the group name. + /// </summary> + /// <value>The name of the new group.</value> + public string GroupName { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs new file mode 100644 index 0000000000..1d8d135cbb --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs @@ -0,0 +1,22 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class NextTrackRequestBody. + /// </summary> + public class NextTrackRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="NextTrackRequestBody"/> class. + /// </summary> + public NextTrackRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets the playing item identifier. + /// </summary> + /// <value>The playing item identifier.</value> + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs new file mode 100644 index 0000000000..f08015bc46 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs @@ -0,0 +1,14 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class PingRequestBody. + /// </summary> + public class PingRequestBody + { + /// <summary> + /// Gets or sets the ping time. + /// </summary> + /// <value>The ping time.</value> + public long Ping { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs new file mode 100644 index 0000000000..97ec95c624 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class PlayRequestBody. + /// </summary> + public class PlayRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="PlayRequestBody"/> class. + /// </summary> + public PlayRequestBody() + { + PlayingQueue = Array.Empty<Guid>(); + } + + /// <summary> + /// Gets or sets the playing queue. + /// </summary> + /// <value>The playing queue.</value> + public IReadOnlyList<Guid> PlayingQueue { get; set; } + + /// <summary> + /// Gets or sets the position of the playing item in the queue. + /// </summary> + /// <value>The playing item position.</value> + public int PlayingItemPosition { get; set; } + + /// <summary> + /// Gets or sets the start position ticks. + /// </summary> + /// <value>The start position ticks.</value> + public long StartPositionTicks { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs new file mode 100644 index 0000000000..95ebeeb908 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs @@ -0,0 +1,22 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class PreviousTrackRequestBody. + /// </summary> + public class PreviousTrackRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="PreviousTrackRequestBody"/> class. + /// </summary> + public PreviousTrackRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets the playing item identifier. + /// </summary> + /// <value>The playing item identifier.</value> + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs new file mode 100644 index 0000000000..1afc61dd46 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class QueueRequestBody. + /// </summary> + public class QueueRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="QueueRequestBody"/> class. + /// </summary> + public QueueRequestBody() + { + ItemIds = Array.Empty<Guid>(); + } + + /// <summary> + /// Gets or sets the items to enqueue. + /// </summary> + /// <value>The items to enqueue.</value> + public IReadOnlyList<Guid> ItemIds { get; set; } + + /// <summary> + /// Gets or sets the mode in which to add the new items. + /// </summary> + /// <value>The enqueue mode.</value> + public GroupQueueMode Mode { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs new file mode 100644 index 0000000000..359186e781 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs @@ -0,0 +1,42 @@ +using System; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class ReadyRequest. + /// </summary> + public class ReadyRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="ReadyRequestBody"/> class. + /// </summary> + public ReadyRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets when the request has been made by the client. + /// </summary> + /// <value>The date of the request.</value> + public DateTime When { get; set; } + + /// <summary> + /// Gets or sets the position ticks. + /// </summary> + /// <value>The position ticks.</value> + public long PositionTicks { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the client playback is unpaused. + /// </summary> + /// <value>The client playback status.</value> + public bool IsPlaying { get; set; } + + /// <summary> + /// Gets or sets the playlist item identifier of the playing item. + /// </summary> + /// <value>The playlist item identifier.</value> + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs new file mode 100644 index 0000000000..a2b617cd03 --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class RemoveFromPlaylistRequestBody. + /// </summary> + public class RemoveFromPlaylistRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="RemoveFromPlaylistRequestBody"/> class. + /// </summary> + public RemoveFromPlaylistRequestBody() + { + PlaylistItemIds = Array.Empty<string>(); + } + + /// <summary> + /// Gets or sets the playlist identifiers ot the items. + /// </summary> + /// <value>The playlist identifiers ot the items.</value> + public IReadOnlyList<string> PlaylistItemIds { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs new file mode 100644 index 0000000000..689183bb6a --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs @@ -0,0 +1,14 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class SeekRequestBody. + /// </summary> + public class SeekRequestBody + { + /// <summary> + /// Gets or sets the position ticks. + /// </summary> + /// <value>The position ticks.</value> + public long PositionTicks { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs new file mode 100644 index 0000000000..abe66c479e --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs @@ -0,0 +1,22 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class SetPlaylistItemRequestBody. + /// </summary> + public class SetPlaylistItemRequestBody + { + /// <summary> + /// Initializes a new instance of the <see cref="SetPlaylistItemRequestBody"/> class. + /// </summary> + public SetPlaylistItemRequestBody() + { + PlaylistItemId = string.Empty; + } + + /// <summary> + /// Gets or sets the playlist identifier of the playing item. + /// </summary> + /// <value>The playlist identifier of the playing item.</value> + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs new file mode 100644 index 0000000000..6de5415cae --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs @@ -0,0 +1,14 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class SetRepeatModeRequestBody. + /// </summary> + public class SetRepeatModeRequestBody + { + /// <summary> + /// Gets or sets the repeat mode. + /// </summary> + /// <value>The repeat mode.</value> + public GroupRepeatMode Mode { get; set; } + } +} diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs new file mode 100644 index 0000000000..867cb938dc --- /dev/null +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs @@ -0,0 +1,14 @@ +namespace MediaBrowser.Model.SyncPlay.RequestBodies +{ + /// <summary> + /// Class SetShuffleModeRequestBody. + /// </summary> + public class SetShuffleModeRequestBody + { + /// <summary> + /// Gets or sets the shuffle mode. + /// </summary> + /// <value>The shuffle mode.</value> + public GroupShuffleMode Mode { get; set; } + } +} From d72f3498bf2c53be0dfb900feba58d84efbffde0 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 28 Nov 2020 21:27:55 +0800 Subject: [PATCH 0565/1930] fix ci --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index f8a704efdf..cb162f0d46 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -554,7 +554,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. - var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparer.OrdinalIgnoreCase); + var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); if (string.IsNullOrEmpty(vf)) { vf = enableThumbnail ? "-vf thumbnail=24" : string.Empty; From 0c6efe6317d1682ba71b751686360124eda41de9 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 28 Nov 2020 22:32:54 +0800 Subject: [PATCH 0566/1930] Apply suggestions from code review Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- .../Encoder/MediaEncoder.cs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index cb162f0d46..8d83096fb5 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -555,13 +555,16 @@ namespace MediaBrowser.MediaEncoding.Encoder // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); - if (string.IsNullOrEmpty(vf)) + if (enableThumbnail) { - vf = enableThumbnail ? "-vf thumbnail=24" : string.Empty; - } - else - { - vf += enableThumbnail ? ",thumbnail=24" : string.Empty; + if (string.IsNullOrEmpty(vf)) + { + vf = "-vf thumbnail=24"; + } + else + { + vf += ",thumbnail=24"; + } } var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); From cab78f40b3018e52234c2b1b871889866e3134b2 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 28 Nov 2020 14:44:14 +0000 Subject: [PATCH 0567/1930] [Fix] Possible null reference. (#4585) Fix possible null reference. --- MediaBrowser.Common/Plugins/LocalPlugin.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 7927c663d4..c97e75a3b2 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -1,11 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; namespace MediaBrowser.Common.Plugins { /// <summary> - /// Local plugin struct. + /// Local plugin class. /// </summary> public class LocalPlugin : IEquatable<LocalPlugin> { @@ -106,6 +106,12 @@ namespace MediaBrowser.Common.Plugins /// <inheritdoc /> public bool Equals(LocalPlugin other) { + // Do not use == or != for comparison as this class overrides the operators. + if (object.ReferenceEquals(other, null)) + { + return false; + } + return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && Id.Equals(other.Id); } From 8b0ef119c39a9eb7cef57d59aec4699c2587b8eb Mon Sep 17 00:00:00 2001 From: dkanada <dkanada@users.noreply.github.com> Date: Sat, 28 Nov 2020 23:55:56 +0900 Subject: [PATCH 0568/1930] remove deprecated flag to disable music plugins --- .../Plugins/AudioDb/AlbumImageProvider.cs | 2 +- .../Plugins/AudioDb/AlbumProvider.cs | 7 ------- .../Plugins/AudioDb/ArtistImageProvider.cs | 2 +- .../Plugins/AudioDb/ArtistProvider.cs | 7 ------- .../AudioDb/Configuration/PluginConfiguration.cs | 2 -- .../Plugins/AudioDb/Configuration/config.html | 14 ++++---------- .../Plugins/MusicBrainz/ArtistProvider.cs | 12 ------------ .../Configuration/PluginConfiguration.cs | 2 -- .../MusicBrainz/Configuration/config.html | 16 +++++----------- .../MusicBrainz/MusicBrainzAlbumProvider.cs | 12 ------------ 10 files changed, 11 insertions(+), 65 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index e3a1decb88..293087da7a 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -103,6 +103,6 @@ namespace MediaBrowser.Providers.Plugins.AudioDb /// <inheritdoc /> public bool Supports(BaseItem item) - => Plugin.Instance.Configuration.Enable && item is MusicAlbum; + => item is MusicAlbum; } } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 6536b303fe..97bba10baa 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -56,13 +56,6 @@ namespace MediaBrowser.Providers.Plugins.AudioDb public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken) { var result = new MetadataResult<MusicAlbum>(); - - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return result; - } - var id = info.GetReleaseGroupId(); if (!string.IsNullOrWhiteSpace(id)) diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index 54851c4d07..d250acfa84 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -144,6 +144,6 @@ namespace MediaBrowser.Providers.Plugins.AudioDb /// <inheritdoc /> public bool Supports(BaseItem item) - => Plugin.Instance.Configuration.Enable && item is MusicArtist; + => item is MusicArtist; } } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 85c92fa7b9..a2a03e1f9a 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -57,13 +57,6 @@ namespace MediaBrowser.Providers.Plugins.AudioDb public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken) { var result = new MetadataResult<MusicArtist>(); - - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return result; - } - var id = info.GetMusicBrainzArtistId(); if (!string.IsNullOrWhiteSpace(id)) diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs index 9657a290fc..664474dcdd 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/PluginConfiguration.cs @@ -6,8 +6,6 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { public class PluginConfiguration : BasePluginConfiguration { - public bool Enable { get; set; } - public bool ReplaceAlbumName { get; set; } } } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html index 82f26a8f26..eab252005f 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html +++ b/MediaBrowser.Providers/Plugins/AudioDb/Configuration/config.html @@ -8,10 +8,6 @@ <div data-role="content"> <div class="content-primary"> <form class="configForm"> - <label class="checkboxContainer"> - <input is="emby-checkbox" type="checkbox" id="enable" /> - <span>Enable this provider for metadata searches on artists and albums.</span> - </label> <label class="checkboxContainer"> <input is="emby-checkbox" type="checkbox" id="replaceAlbumName" /> <span>When an album is found during a metadata search, replace the name with the value on the server.</span> @@ -32,9 +28,8 @@ .addEventListener('pageshow', function () { Dashboard.showLoadingMsg(); ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) { - document.querySelector('#enable').checked = config.Enable; document.querySelector('#replaceAlbumName').checked = config.ReplaceAlbumName; - + Dashboard.hideLoadingMsg(); }); }); @@ -42,14 +37,13 @@ document.querySelector('.configForm') .addEventListener('submit', function (e) { Dashboard.showLoadingMsg(); - + ApiClient.getPluginConfiguration(PluginConfig.pluginId).then(function (config) { - config.Enable = document.querySelector('#enable').checked; config.ReplaceAlbumName = document.querySelector('#replaceAlbumName').checked; - + ApiClient.updatePluginConfiguration(PluginConfig.pluginId, config).then(Dashboard.processPluginConfigurationUpdateResult); }); - + e.preventDefault(); return false; }); diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs index dc755b600b..ce93924026 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs @@ -25,12 +25,6 @@ namespace MediaBrowser.Providers.Music /// <inheritdoc /> public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken) { - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return Enumerable.Empty<RemoteSearchResult>(); - } - var musicBrainzId = searchInfo.GetMusicBrainzArtistId(); if (!string.IsNullOrWhiteSpace(musicBrainzId)) @@ -236,12 +230,6 @@ namespace MediaBrowser.Providers.Music Item = new MusicArtist() }; - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return result; - } - var musicBrainzId = id.GetMusicBrainzArtistId(); if (string.IsNullOrWhiteSpace(musicBrainzId)) diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs index 980da9a010..0cec9e359c 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/PluginConfiguration.cs @@ -43,8 +43,6 @@ namespace MediaBrowser.Providers.Plugins.MusicBrainz } } - public bool Enable { get; set; } - public bool ReplaceArtistName { get; set; } } } diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html index 1945e6cb49..6f1296bb77 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Configuration/config.html @@ -16,10 +16,6 @@ <input is="emby-input" type="number" id="rateLimit" pattern="[0-9]*" required min="0" max="10000" label="Rate Limit" /> <div class="fieldDescription">Span of time between requests in milliseconds. The official server is limited to one request every two seconds.</div> </div> - <label class="checkboxContainer"> - <input is="emby-checkbox" type="checkbox" id="enable" /> - <span>Enable this provider for metadata searches on artists and albums.</span> - </label> <label class="checkboxContainer"> <input is="emby-checkbox" type="checkbox" id="replaceArtistName" /> <span>When an artist is found during a metadata search, replace the artist name with the value on the server.</span> @@ -46,7 +42,7 @@ bubbles: true, cancelable: false })); - + var rateLimit = document.querySelector('#rateLimit'); rateLimit.value = config.RateLimit; rateLimit.dispatchEvent(new Event('change', { @@ -54,26 +50,24 @@ cancelable: false })); - document.querySelector('#enable').checked = config.Enable; document.querySelector('#replaceArtistName').checked = config.ReplaceArtistName; Dashboard.hideLoadingMsg(); }); }); - + document.querySelector('.musicBrainzConfigForm') .addEventListener('submit', function (e) { Dashboard.showLoadingMsg(); - + ApiClient.getPluginConfiguration(MusicBrainzPluginConfig.uniquePluginId).then(function (config) { config.Server = document.querySelector('#server').value; config.RateLimit = document.querySelector('#rateLimit').value; - config.Enable = document.querySelector('#enable').checked; config.ReplaceArtistName = document.querySelector('#replaceArtistName').checked; - + ApiClient.updatePluginConfiguration(MusicBrainzPluginConfig.uniquePluginId, config).then(Dashboard.processPluginConfigurationUpdateResult); }); - + e.preventDefault(); return false; }); diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs index 8951cb62e4..ef7933b1a6 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs @@ -78,12 +78,6 @@ namespace MediaBrowser.Providers.Music /// <inheritdoc /> public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken) { - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return Enumerable.Empty<RemoteSearchResult>(); - } - var releaseId = searchInfo.GetReleaseId(); var releaseGroupId = searchInfo.GetReleaseGroupId(); @@ -194,12 +188,6 @@ namespace MediaBrowser.Providers.Music Item = new MusicAlbum() }; - // TODO maybe remove when artist metadata can be disabled - if (!Plugin.Instance.Configuration.Enable) - { - return result; - } - // If we have a release group Id but not a release Id... if (string.IsNullOrWhiteSpace(releaseId) && !string.IsNullOrWhiteSpace(releaseGroupId)) { From 78ea8ef99e68eb606c96399895b224e91db15163 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Sat, 28 Nov 2020 16:03:02 +0100 Subject: [PATCH 0569/1930] Create common interface for SyncPlay requests --- .../SyncPlay/GroupController.cs | 12 ++-- .../SyncPlay/SyncPlayManager.cs | 69 +++++++------------ .../Controllers/SyncPlayController.cs | 13 ++-- .../GroupStates/AbstractGroupState.cs | 4 +- .../SyncPlay/IGroupController.cs | 11 +-- .../SyncPlay/IGroupPlaybackRequest.cs | 4 +- .../SyncPlay/ISyncPlayManager.cs | 12 ++-- .../SyncPlay/ISyncPlayRequest.cs | 16 +++++ .../AbstractPlaybackRequest.cs | 29 ++++++++ .../PlaybackRequests/BufferGroupRequest.cs | 6 +- .../IgnoreWaitGroupRequest.cs | 6 +- .../MovePlaylistItemGroupRequest.cs | 6 +- .../PlaybackRequests/NextTrackGroupRequest.cs | 6 +- .../PlaybackRequests/PauseGroupRequest.cs | 6 +- .../PlaybackRequests/PingGroupRequest.cs | 6 +- .../PlaybackRequests/PlayGroupRequest.cs | 6 +- .../PreviousTrackGroupRequest.cs | 6 +- .../PlaybackRequests/QueueGroupRequest.cs | 6 +- .../PlaybackRequests/ReadyGroupRequest.cs | 6 +- .../RemoveFromPlaylistGroupRequest.cs | 6 +- .../PlaybackRequests/SeekGroupRequest.cs | 6 +- .../SetPlaylistItemGroupRequest.cs | 6 +- .../SetRepeatModeGroupRequest.cs | 6 +- .../SetShuffleModeGroupRequest.cs | 6 +- .../PlaybackRequests/StopGroupRequest.cs | 6 +- .../PlaybackRequests/UnpauseGroupRequest.cs | 6 +- .../SyncPlay/Requests/JoinGroupRequest.cs | 29 ++++++++ .../SyncPlay/Requests/LeaveGroupRequest.cs | 13 ++++ .../SyncPlay/Requests/ListGroupsRequest.cs | 13 ++++ .../SyncPlay/Requests/NewGroupRequest.cs | 28 ++++++++ .../{GroupRequestType.cs => RequestType.cs} | 4 +- 31 files changed, 238 insertions(+), 121 deletions(-) create mode 100644 MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs create mode 100644 MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs rename MediaBrowser.Model/SyncPlay/{GroupRequestType.cs => RequestType.cs} (91%) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index 612fba5048..dc262f1cfc 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -12,8 +12,8 @@ using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.SyncPlay.GroupStates; using MediaBrowser.Controller.SyncPlay.Queue; +using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay @@ -257,7 +257,7 @@ namespace Emby.Server.Implementations.SyncPlay public bool IsGroupEmpty() => _participants.Count == 0; /// <inheritdoc /> - public void CreateGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken) + public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { GroupName = request.GroupName; AddSession(session); @@ -292,7 +292,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SessionJoin(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken) + public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { AddSession(session); @@ -308,7 +308,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SessionRestore(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken) + public void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); @@ -322,7 +322,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void SessionLeave(SessionInfo session, CancellationToken cancellationToken) + public void SessionLeave(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { _state.SessionLeaving(this, _state.Type, session, cancellationToken); @@ -343,7 +343,7 @@ namespace Emby.Server.Implementations.SyncPlay // The server's job is to maintain a consistent state for clients to reference // and notify clients of state changes. The actual syncing of media playback // happens client side. Clients are aware of the server's time and use it to sync. - _logger.LogInformation("Session {SessionId} requested {RequestType} in group {GroupId} that is {StateType}.", session.Id, request.Type, GroupId.ToString(), _state.Type); + _logger.LogInformation("Session {SessionId} requested {RequestType} in group {GroupId} that is {StateType}.", session.Id, request.Action, GroupId.ToString(), _state.Type); request.Apply(this, _state, session, cancellationToken); } diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 5a0d619269..fbd3c3cfb2 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -5,8 +5,8 @@ using Jellyfin.Data.Enums; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; +using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay @@ -94,10 +94,9 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void NewGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken) + public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { - // TODO: create abstract class for GroupRequests to avoid explicit request type here. - if (!IsRequestValid(session, GroupRequestType.NewGroup, request)) + if (!IsRequestValid(session, request)) { return; } @@ -111,7 +110,8 @@ namespace Emby.Server.Implementations.SyncPlay { if (IsSessionInGroup(session)) { - LeaveGroup(session, cancellationToken); + var leaveGroupRequest = new LeaveGroupRequest(); + LeaveGroup(session, leaveGroupRequest, cancellationToken); } var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager); @@ -124,10 +124,9 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequestBody request, CancellationToken cancellationToken) + public void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { - // TODO: create abstract class for GroupRequests to avoid explicit request type here. - if (!IsRequestValid(session, GroupRequestType.JoinGroup, request)) + if (!IsRequestValid(session, request)) { return; } @@ -137,11 +136,11 @@ namespace Emby.Server.Implementations.SyncPlay // Locking required to access list of groups. lock (_groupsLock) { - _groups.TryGetValue(groupId, out IGroupController group); + _groups.TryGetValue(request.GroupId, out IGroupController group); if (group == null) { - _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, groupId); + _logger.LogWarning("Session {SessionId} tried to join group {GroupId} that does not exist.", session.Id, request.GroupId); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.GroupDoesNotExist, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); @@ -165,13 +164,14 @@ namespace Emby.Server.Implementations.SyncPlay if (IsSessionInGroup(session)) { - if (FindJoinedGroupId(session).Equals(groupId)) + if (FindJoinedGroupId(session).Equals(request.GroupId)) { group.SessionRestore(session, request, cancellationToken); return; } - LeaveGroup(session, cancellationToken); + var leaveGroupRequest = new LeaveGroupRequest(); + LeaveGroup(session, leaveGroupRequest, cancellationToken); } AddSessionToGroup(session, group); @@ -182,10 +182,9 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken) + public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { - // TODO: create abstract class for GroupRequests to avoid explicit request type here. - if (!IsRequestValid(session, GroupRequestType.LeaveGroup)) + if (!IsRequestValid(session, request)) { return; } @@ -210,7 +209,7 @@ namespace Emby.Server.Implementations.SyncPlay lock (group) { RemoveSessionFromGroup(session, group); - group.SessionLeave(session, cancellationToken); + group.SessionLeave(session, request, cancellationToken); if (group.IsGroupEmpty()) { @@ -223,10 +222,9 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public List<GroupInfoDto> ListGroups(SessionInfo session) + public List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request) { - // TODO: create abstract class for GroupRequests to avoid explicit request type here. - if (!IsRequestValid(session, GroupRequestType.ListGroups)) + if (!IsRequestValid(session, request)) { return new List<GroupInfoDto>(); } @@ -256,8 +254,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { - // TODO: create abstract class for GroupRequests to avoid explicit request type here. - if (!IsRequestValid(session, GroupRequestType.Playback, request)) + if (!IsRequestValid(session, request)) { return; } @@ -304,11 +301,8 @@ namespace Emby.Server.Implementations.SyncPlay return; } - var request = new JoinGroupRequestBody() - { - GroupId = groupId - }; - JoinGroup(session, groupId, request, CancellationToken.None); + var request = new JoinGroupRequest(groupId); + JoinGroup(session, request, CancellationToken.None); } /// <summary> @@ -409,13 +403,11 @@ namespace Emby.Server.Implementations.SyncPlay /// Checks if a given session is allowed to make a given request. /// </summary> /// <param name="session">The session.</param> - /// <param name="requestType">The request type.</param> /// <param name="request">The request.</param> - /// <param name="checkRequest">Whether to check if request is null.</param> - /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns> - private bool IsRequestValid<T>(SessionInfo session, GroupRequestType requestType, T request, bool checkRequest = true) + /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session or request is null.</returns> + private bool IsRequestValid(SessionInfo session, ISyncPlayRequest request) { - if (session == null || (request == null && checkRequest)) + if (session == null || (request == null)) { return false; } @@ -424,7 +416,7 @@ namespace Emby.Server.Implementations.SyncPlay if (user.SyncPlayAccess == SyncPlayAccess.None) { - _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, requestType); + _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, request.Type); // TODO: rename to a more generic error. Next PR will fix this. var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty); @@ -432,7 +424,7 @@ namespace Emby.Server.Implementations.SyncPlay return false; } - if (requestType.Equals(GroupRequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) + if (request.Type.Equals(RequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) { _logger.LogWarning("Session {SessionId} does not have permission to create groups.", session.Id); @@ -443,16 +435,5 @@ namespace Emby.Server.Implementations.SyncPlay return true; } - - /// <summary> - /// Checks if a given session is allowed to make a given type of request. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="requestType">The request type.</param> - /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session is null.</returns> - private bool IsRequestValid(SessionInfo session, GroupRequestType requestType) - { - return IsRequestValid(session, requestType, session, false); - } } } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index e8c9a09568..ed5ea3c8a7 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -8,6 +8,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; +using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.AspNetCore.Authorization; @@ -54,7 +55,8 @@ namespace Jellyfin.Api.Controllers [FromBody, Required] NewGroupRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - _syncPlayManager.NewGroup(currentSession, requestData, CancellationToken.None); + var syncPlayRequest = new NewGroupRequest(requestData.GroupName); + _syncPlayManager.NewGroup(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -70,7 +72,8 @@ namespace Jellyfin.Api.Controllers [FromBody, Required] JoinGroupRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - _syncPlayManager.JoinGroup(currentSession, requestData.GroupId, requestData, CancellationToken.None); + var syncPlayRequest = new JoinGroupRequest(requestData.GroupId); + _syncPlayManager.JoinGroup(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -84,7 +87,8 @@ namespace Jellyfin.Api.Controllers public ActionResult SyncPlayLeaveGroup() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - _syncPlayManager.LeaveGroup(currentSession, CancellationToken.None); + var syncPlayRequest = new LeaveGroupRequest(); + _syncPlayManager.LeaveGroup(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } @@ -98,7 +102,8 @@ namespace Jellyfin.Api.Controllers public ActionResult<IEnumerable<GroupInfoDto>> SyncPlayGetGroups() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - return Ok(_syncPlayManager.ListGroups(currentSession)); + var syncPlayRequest = new ListGroupsRequest(); + return Ok(_syncPlayManager.ListGroups(currentSession, syncPlayRequest)); } /// <summary> diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index 057488d6b4..0b15e3ae4a 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -209,14 +209,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates protected void SendGroupStateUpdate(IGroupStateContext context, IGroupPlaybackRequest reason, SessionInfo session, CancellationToken cancellationToken) { // Notify relevant state change event. - var stateUpdate = new GroupStateUpdate(Type, reason.Type); + var stateUpdate = new GroupStateUpdate(Type, reason.Action); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.StateUpdate, stateUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); } private void UnhandledRequest(IGroupPlaybackRequest request) { - _logger.LogWarning("Unhandled request of type {RequestType} in {StateType} state.", request.Type, Type); + _logger.LogWarning("Unhandled request of type {RequestType} in {StateType} state.", request.Action, Type); } } } diff --git a/MediaBrowser.Controller/SyncPlay/IGroupController.cs b/MediaBrowser.Controller/SyncPlay/IGroupController.cs index 5bcc3e2ca3..07f9659dd1 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupController.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupController.cs @@ -3,8 +3,8 @@ using System.Threading; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.Queue; +using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Model.SyncPlay.RequestBodies; namespace MediaBrowser.Controller.SyncPlay { @@ -37,7 +37,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void CreateGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken); + void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Adds the session to the group. @@ -45,7 +45,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionJoin(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken); + void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Restores the state of a session that already joined the group. @@ -53,14 +53,15 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionRestore(SessionInfo session, JoinGroupRequestBody request, CancellationToken cancellationToken); + void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Removes the session from the group. /// </summary> /// <param name="session">The session.</param> + /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void SessionLeave(SessionInfo session, CancellationToken cancellationToken); + void SessionLeave(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Handles the requested action by the session. diff --git a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs index 3b195e98ca..201f29952f 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs @@ -7,13 +7,13 @@ namespace MediaBrowser.Controller.SyncPlay /// <summary> /// Interface IGroupPlaybackRequest. /// </summary> - public interface IGroupPlaybackRequest + public interface IGroupPlaybackRequest : ISyncPlayRequest { /// <summary> /// Gets the playback request type. /// </summary> /// <returns>The playback request type.</returns> - PlaybackRequestType Type { get; } + PlaybackRequestType Action { get; } /// <summary> /// Applies the request to a group. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 26fcb009ca..146e4351df 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Threading; using MediaBrowser.Controller.Session; +using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; using MediaBrowser.Model.SyncPlay.RequestBodies; @@ -18,30 +19,31 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="session">The session that's creating the group.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void NewGroup(SessionInfo session, NewGroupRequestBody request, CancellationToken cancellationToken); + void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Adds the session to a group. /// </summary> /// <param name="session">The session.</param> - /// <param name="groupId">The group identifier.</param> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequestBody request, CancellationToken cancellationToken); + void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Removes the session from a group. /// </summary> /// <param name="session">The session.</param> + /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> - void LeaveGroup(SessionInfo session, CancellationToken cancellationToken); + void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken); /// <summary> /// Gets list of available groups for a session. /// </summary> /// <param name="session">The session.</param> + /// <param name="request">The request.</param> /// <returns>The list of available groups.</returns> - List<GroupInfoDto> ListGroups(SessionInfo session); + List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request); /// <summary> /// Handle a request by a session in a group. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs new file mode 100644 index 0000000000..bf19817732 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayRequest.cs @@ -0,0 +1,16 @@ +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay +{ + /// <summary> + /// Interface ISyncPlayRequest. + /// </summary> + public interface ISyncPlayRequest + { + /// <summary> + /// Gets the request type. + /// </summary> + /// <returns>The request type.</returns> + RequestType Type { get; } + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs new file mode 100644 index 0000000000..4090f65b9c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs @@ -0,0 +1,29 @@ +using System.Threading; +using MediaBrowser.Controller.Session; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests +{ + /// <summary> + /// Class AbstractPlaybackRequest. + /// </summary> + public abstract class AbstractPlaybackRequest : IGroupPlaybackRequest + { + /// <summary> + /// Initializes a new instance of the <see cref="AbstractPlaybackRequest"/> class. + /// </summary> + protected AbstractPlaybackRequest() + { + // Do nothing. + } + + /// <inheritdoc /> + public RequestType Type { get; } = RequestType.Playback; + + /// <inheritdoc /> + public abstract PlaybackRequestType Action { get; } + + /// <inheritdoc /> + public abstract void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index a12ab96b77..2981dbbdd6 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -8,7 +8,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class BufferGroupRequest. /// </summary> - public class BufferGroupRequest : IGroupPlaybackRequest + public class BufferGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="BufferGroupRequest"/> class. @@ -50,10 +50,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Buffer; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Buffer; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs index 25034cb10b..a375895ad0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class IgnoreWaitGroupRequest. /// </summary> - public class IgnoreWaitGroupRequest : IGroupPlaybackRequest + public class IgnoreWaitGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="IgnoreWaitGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public bool IgnoreWait { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.IgnoreWait; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.IgnoreWait; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index a12eff8b84..efca4ed3ef 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class MovePlaylistItemGroupRequest. /// </summary> - public class MovePlaylistItemGroupRequest : IGroupPlaybackRequest + public class MovePlaylistItemGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="MovePlaylistItemGroupRequest"/> class. @@ -33,10 +33,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public int NewIndex { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.MovePlaylistItem; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.MovePlaylistItem; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs index f87bbc556d..73b7d0908b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class NextTrackGroupRequest. /// </summary> - public class NextTrackGroupRequest : IGroupPlaybackRequest + public class NextTrackGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="NextTrackGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.NextTrack; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.NextTrack; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs index 0dcd1423fd..8ce2b1fc80 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs @@ -7,13 +7,13 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class PauseGroupRequest. /// </summary> - public class PauseGroupRequest : IGroupPlaybackRequest + public class PauseGroupRequest : AbstractPlaybackRequest { /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Pause; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Pause; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs index 2528bb3e70..19c940cdf8 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class PingGroupRequest. /// </summary> - public class PingGroupRequest : IGroupPlaybackRequest + public class PingGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="PingGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public long Ping { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Ping; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Ping; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index dbe2987357..88e0ebad2b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class PlayGroupRequest. /// </summary> - public class PlayGroupRequest : IGroupPlaybackRequest + public class PlayGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="PlayGroupRequest"/> class. @@ -43,10 +43,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public long StartPositionTicks { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Play; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Play; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs index 206fef3312..4c70beb0ef 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class PreviousTrackGroupRequest. /// </summary> - public class PreviousTrackGroupRequest : IGroupPlaybackRequest + public class PreviousTrackGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="PreviousTrackGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.PreviousTrack; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.PreviousTrack; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index d6247ddd6d..ba5e3e2327 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class QueueGroupRequest. /// </summary> - public class QueueGroupRequest : IGroupPlaybackRequest + public class QueueGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="QueueGroupRequest"/> class. @@ -35,10 +35,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public GroupQueueMode Mode { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Queue; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Queue; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index a2b3553cee..b09db4ba80 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -8,7 +8,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class ReadyGroupRequest. /// </summary> - public class ReadyGroupRequest : IGroupPlaybackRequest + public class ReadyGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="ReadyGroupRequest"/> class. @@ -50,10 +50,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Ready; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Ready; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index dc7ba8465c..dac1914aa7 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class RemoveFromPlaylistGroupRequest. /// </summary> - public class RemoveFromPlaylistGroupRequest : IGroupPlaybackRequest + public class RemoveFromPlaylistGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="RemoveFromPlaylistGroupRequest"/> class. @@ -27,10 +27,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public IReadOnlyList<string> PlaylistItemIds { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.RemoveFromPlaylist; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.RemoveFromPlaylist; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs index f7bfc19788..41e28467c0 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class SeekGroupRequest. /// </summary> - public class SeekGroupRequest : IGroupPlaybackRequest + public class SeekGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="SeekGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public long PositionTicks { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Seek; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Seek; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index 2ca33c1ccf..58fed3fa07 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class SetPlaylistItemGroupRequest. /// </summary> - public class SetPlaylistItemGroupRequest : IGroupPlaybackRequest + public class SetPlaylistItemGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="SetPlaylistItemGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.SetPlaylistItem; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetPlaylistItem; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs index cd4505e4d0..6a5ec1d117 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class SetRepeatModeGroupRequest. /// </summary> - public class SetRepeatModeGroupRequest : IGroupPlaybackRequest + public class SetRepeatModeGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="SetRepeatModeGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public GroupRepeatMode Mode { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.SetRepeatMode; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetRepeatMode; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs index 4530a34c02..fe007c8d89 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class SetShuffleModeGroupRequest. /// </summary> - public class SetShuffleModeGroupRequest : IGroupPlaybackRequest + public class SetShuffleModeGroupRequest : AbstractPlaybackRequest { /// <summary> /// Initializes a new instance of the <see cref="SetShuffleModeGroupRequest"/> class. @@ -25,10 +25,10 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public GroupShuffleMode Mode { get; } /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.SetShuffleMode; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetShuffleMode; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs index ec01cd1105..c42e229d1f 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs @@ -7,13 +7,13 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class StopGroupRequest. /// </summary> - public class StopGroupRequest : IGroupPlaybackRequest + public class StopGroupRequest : AbstractPlaybackRequest { /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Stop; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Stop; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs index bdf4fd4767..b4c1744e95 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs @@ -7,13 +7,13 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <summary> /// Class UnpauseGroupRequest. /// </summary> - public class UnpauseGroupRequest : IGroupPlaybackRequest + public class UnpauseGroupRequest : AbstractPlaybackRequest { /// <inheritdoc /> - public PlaybackRequestType Type { get; } = PlaybackRequestType.Unpause; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.Unpause; /// <inheritdoc /> - public void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) + public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { state.HandleRequest(context, state.Type, this, session, cancellationToken); } diff --git a/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs new file mode 100644 index 0000000000..38c9e8e20c --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/Requests/JoinGroupRequest.cs @@ -0,0 +1,29 @@ +using System; +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay.Requests +{ + /// <summary> + /// Class JoinGroupRequest. + /// </summary> + public class JoinGroupRequest : ISyncPlayRequest + { + /// <summary> + /// Initializes a new instance of the <see cref="JoinGroupRequest"/> class. + /// </summary> + /// <param name="groupId">The identifier of the group to join.</param> + public JoinGroupRequest(Guid groupId) + { + GroupId = groupId; + } + + /// <summary> + /// Gets the group identifier. + /// </summary> + /// <value>The identifier of the group to join.</value> + public Guid GroupId { get; } + + /// <inheritdoc /> + public RequestType Type { get; } = RequestType.JoinGroup; + } +} diff --git a/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs new file mode 100644 index 0000000000..545778264f --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/Requests/LeaveGroupRequest.cs @@ -0,0 +1,13 @@ +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay.Requests +{ + /// <summary> + /// Class LeaveGroupRequest. + /// </summary> + public class LeaveGroupRequest : ISyncPlayRequest + { + /// <inheritdoc /> + public RequestType Type { get; } = RequestType.LeaveGroup; + } +} diff --git a/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs new file mode 100644 index 0000000000..4a234fdab5 --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/Requests/ListGroupsRequest.cs @@ -0,0 +1,13 @@ +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay.Requests +{ + /// <summary> + /// Class ListGroupsRequest. + /// </summary> + public class ListGroupsRequest : ISyncPlayRequest + { + /// <inheritdoc /> + public RequestType Type { get; } = RequestType.ListGroups; + } +} diff --git a/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs new file mode 100644 index 0000000000..1321f0de8e --- /dev/null +++ b/MediaBrowser.Controller/SyncPlay/Requests/NewGroupRequest.cs @@ -0,0 +1,28 @@ +using MediaBrowser.Model.SyncPlay; + +namespace MediaBrowser.Controller.SyncPlay.Requests +{ + /// <summary> + /// Class NewGroupRequest. + /// </summary> + public class NewGroupRequest : ISyncPlayRequest + { + /// <summary> + /// Initializes a new instance of the <see cref="NewGroupRequest"/> class. + /// </summary> + /// <param name="groupName">The name of the new group.</param> + public NewGroupRequest(string groupName) + { + GroupName = groupName; + } + + /// <summary> + /// Gets the group name. + /// </summary> + /// <value>The name of the new group.</value> + public string GroupName { get; } + + /// <inheritdoc /> + public RequestType Type { get; } = RequestType.NewGroup; + } +} diff --git a/MediaBrowser.Model/SyncPlay/GroupRequestType.cs b/MediaBrowser.Model/SyncPlay/RequestType.cs similarity index 91% rename from MediaBrowser.Model/SyncPlay/GroupRequestType.cs rename to MediaBrowser.Model/SyncPlay/RequestType.cs index 75c0712364..a6e397dcd6 100644 --- a/MediaBrowser.Model/SyncPlay/GroupRequestType.cs +++ b/MediaBrowser.Model/SyncPlay/RequestType.cs @@ -1,9 +1,9 @@ namespace MediaBrowser.Model.SyncPlay { /// <summary> - /// Enum GroupRequestType. + /// Enum RequestType. /// </summary> - public enum GroupRequestType + public enum RequestType { /// <summary> /// A user is requesting to create a new group. From 10be618ec3d7f10848ac01f69e3508930849bb99 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 28 Nov 2020 16:33:57 +0100 Subject: [PATCH 0570/1930] Add more tests for JsonGuidConverter --- .../Json/JsonGuidConverterTests.cs | 48 +++++++++++++------ 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs index d9e66d6774..3c94db4913 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs @@ -5,28 +5,48 @@ using Xunit; namespace Jellyfin.Common.Tests.Extensions { - public static class JsonGuidConverterTests + public class JsonGuidConverterTests { - [Fact] - public static void Deserialize_Valid_Success() - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new JsonGuidConverter()); - Guid value = JsonSerializer.Deserialize<Guid>(@"""a852a27afe324084ae66db579ee3ee18""", options); - Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value); + private readonly JsonSerializerOptions _options; - value = JsonSerializer.Deserialize<Guid>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", options); + public JsonGuidConverterTests() + { + _options = new JsonSerializerOptions(); + _options.Converters.Add(new JsonGuidConverter()); + } + + [Fact] + public void Deserialize_Valid_Success() + { + Guid value = JsonSerializer.Deserialize<Guid>(@"""a852a27afe324084ae66db579ee3ee18""", _options); + Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value); + } + + [Fact] + public void Deserialize_ValidDashed_Success() + { + Guid value = JsonSerializer.Deserialize<Guid>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", _options); Assert.Equal(new Guid("e9b2dcaa-529c-426e-9433-5e9981f27f2e"), value); } [Fact] - public static void Roundtrip_Valid_Success() + public void Roundtrip_Valid_Success() { - var options = new JsonSerializerOptions(); - options.Converters.Add(new JsonGuidConverter()); Guid guid = new Guid("a852a27afe324084ae66db579ee3ee18"); - string value = JsonSerializer.Serialize(guid, options); - Assert.Equal(guid, JsonSerializer.Deserialize<Guid>(value, options)); + string value = JsonSerializer.Serialize(guid, _options); + Assert.Equal(guid, JsonSerializer.Deserialize<Guid>(value, _options)); + } + + [Fact] + public void Deserialize_Null_EmptyGuid() + { + Assert.Equal(Guid.Empty, JsonSerializer.Deserialize<Guid>("null", _options)); + } + + [Fact] + public void Serialize_EmptyGuid_Null() + { + Assert.Equal("null", JsonSerializer.Serialize(Guid.Empty, _options)); } } } From e52e1918c559eb143c40123b5afd00ab269cbbbc Mon Sep 17 00:00:00 2001 From: No Available <tympanix@gmail.com> Date: Sat, 28 Nov 2020 18:28:08 +0000 Subject: [PATCH 0571/1930] Translated using Weblate (Danish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/da/ --- Emby.Server.Implementations/Localization/Core/da.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/da.json b/Emby.Server.Implementations/Localization/Core/da.json index b29ad94eff..4ee4eb989f 100644 --- a/Emby.Server.Implementations/Localization/Core/da.json +++ b/Emby.Server.Implementations/Localization/Core/da.json @@ -113,5 +113,10 @@ "TaskCleanTranscodeDescription": "Fjern transcode filer som er mere end en dag gammel.", "TaskCleanTranscode": "Rengør Transcode Mappen", "TaskRefreshPeople": "Genopfrisk Personer", - "TaskRefreshPeopleDescription": "Opdatere metadata for skuespillere og instruktører i dit bibliotek." + "TaskRefreshPeopleDescription": "Opdatere metadata for skuespillere og instruktører i dit bibliotek.", + "TaskCleanActivityLogDescription": "Sletter linjer i aktivitetsloggen ældre end den konfigureret alder.", + "TaskCleanActivityLog": "Ryd Aktivitetslog", + "Undefined": "Udefineret", + "Forced": "Tvunget", + "Default": "Standard" } From 304bbfd66d4ce5cb22f2b26d1b6d8be4569e3abe Mon Sep 17 00:00:00 2001 From: Telmo Duarte <matcheryt@gmail.com> Date: Sat, 28 Nov 2020 21:42:58 +0000 Subject: [PATCH 0572/1930] Translated using Weblate (Portuguese (Portugal)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt_PT/ --- Emby.Server.Implementations/Localization/Core/pt-PT.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt-PT.json b/Emby.Server.Implementations/Localization/Core/pt-PT.json index 90a4941c56..8c41edf963 100644 --- a/Emby.Server.Implementations/Localization/Core/pt-PT.json +++ b/Emby.Server.Implementations/Localization/Core/pt-PT.json @@ -113,5 +113,10 @@ "TasksChannelsCategory": "Canais da Internet", "TasksApplicationCategory": "Aplicação", "TasksLibraryCategory": "Biblioteca", - "TasksMaintenanceCategory": "Manutenção" + "TasksMaintenanceCategory": "Manutenção", + "TaskCleanActivityLogDescription": "Apaga as entradas do registo de atividade anteriores à data configurada.", + "TaskCleanActivityLog": "Limpar registo de atividade", + "Undefined": "Indefinido", + "Forced": "Forçado", + "Default": "Padrão" } From e936d0872bf4dd58c73ea38afc99d1e0d4e33538 Mon Sep 17 00:00:00 2001 From: Telmo Duarte <matcheryt@gmail.com> Date: Sat, 28 Nov 2020 21:40:07 +0000 Subject: [PATCH 0573/1930] Translated using Weblate (Portuguese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt/ --- Emby.Server.Implementations/Localization/Core/pt.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt.json b/Emby.Server.Implementations/Localization/Core/pt.json index 2079940cd1..c2ad260dfd 100644 --- a/Emby.Server.Implementations/Localization/Core/pt.json +++ b/Emby.Server.Implementations/Localization/Core/pt.json @@ -112,5 +112,9 @@ "TaskUpdatePluginsDescription": "Download e instala as atualizações para plug-ins configurados para atualização automática.", "TaskRefreshPeopleDescription": "Atualiza os metadados para atores e diretores na tua biblioteca de media.", "TaskRefreshPeople": "Atualizar pessoas", - "TaskRefreshLibraryDescription": "Pesquisa a tua biblioteca de media por novos ficheiros e atualiza os metadados." + "TaskRefreshLibraryDescription": "Pesquisa a tua biblioteca de media por novos ficheiros e atualiza os metadados.", + "TaskCleanActivityLog": "Limpar registo de atividade", + "Undefined": "Indefinido", + "Forced": "Forçado", + "Default": "Predefinição" } From 4a67267e1ef0c4bfff56825979643d8363c5768a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 28 Nov 2020 23:44:19 +0000 Subject: [PATCH 0574/1930] Update DlnaEventManager.cs Set notificationType --- Emby.Dlna/Eventing/DlnaEventManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs index b6e45c50ea..da4ef350a2 100644 --- a/Emby.Dlna/Eventing/DlnaEventManager.cs +++ b/Emby.Dlna/Eventing/DlnaEventManager.cs @@ -72,7 +72,8 @@ namespace Emby.Dlna.Eventing Id = id, CallbackUrl = callbackUrl, SubscriptionTime = DateTime.UtcNow, - TimeoutSeconds = timeout + TimeoutSeconds = timeout, + NoticationType = notificationType }); return GetEventSubscriptionResponse(id, requestedTimeoutString, timeout); From a8ceb7e20bf08b48012567597b7805aadcec0e6c Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 28 Nov 2020 23:45:26 +0000 Subject: [PATCH 0575/1930] Update DlnaEventManager.cs --- Emby.Dlna/Eventing/DlnaEventManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs index da4ef350a2..ff81e83b5e 100644 --- a/Emby.Dlna/Eventing/DlnaEventManager.cs +++ b/Emby.Dlna/Eventing/DlnaEventManager.cs @@ -73,7 +73,7 @@ namespace Emby.Dlna.Eventing CallbackUrl = callbackUrl, SubscriptionTime = DateTime.UtcNow, TimeoutSeconds = timeout, - NoticationType = notificationType + NotificationType = notificationType }); return GetEventSubscriptionResponse(id, requestedTimeoutString, timeout); From bb16174936dca01812d3dc92e6728847bf994b20 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 29 Nov 2020 13:12:41 +0800 Subject: [PATCH 0576/1930] increase the default image extraction timeout --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 8d83096fb5..753da46a69 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -36,7 +36,7 @@ namespace MediaBrowser.MediaEncoding.Encoder /// <summary> /// The default image extraction timeout in milliseconds. /// </summary> - internal const int DefaultImageExtractionTimeout = 5000; + internal const int DefaultImageExtractionTimeout = 10000; /// <summary> /// The us culture. From c2c06ae15b9d35ad587920a2a4994cf6f3381d5a Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 29 Nov 2020 13:20:55 +0800 Subject: [PATCH 0577/1930] fix image extraction --- .../Encoder/MediaEncoder.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 5f60c09ae7..753da46a69 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -36,7 +36,7 @@ namespace MediaBrowser.MediaEncoding.Encoder /// <summary> /// The default image extraction timeout in milliseconds. /// </summary> - internal const int DefaultImageExtractionTimeout = 5000; + internal const int DefaultImageExtractionTimeout = 10000; /// <summary> /// The us culture. @@ -553,12 +553,21 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; - var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase); // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. - var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty; + var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); + if (enableThumbnail) + { + if (string.IsNullOrEmpty(vf)) + { + vf = "-vf thumbnail=24"; + } + else + { + vf += ",thumbnail=24"; + } + } - var args = useIFrame ? string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {5} -v quiet -vframes 1 {2}{4} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail, threads) : - string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); + var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1); var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1); From 3e9cf98c30277e09f7b8a6c8ecb603e9ea10774a Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 29 Nov 2020 13:22:42 +0800 Subject: [PATCH 0578/1930] add hdr tone mapping to image extraction --- .../Encoder/MediaEncoder.cs | 58 +++++++++++++++++-- 1 file changed, 52 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 753da46a69..be63a18e4a 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -34,9 +34,14 @@ namespace MediaBrowser.MediaEncoding.Encoder public class MediaEncoder : IMediaEncoder, IDisposable { /// <summary> - /// The default image extraction timeout in milliseconds. + /// The default SDR image extraction timeout in milliseconds. /// </summary> - internal const int DefaultImageExtractionTimeout = 10000; + internal const int DefaultSdrImageExtractionTimeout = 10000; + + /// <summary> + /// The default HDR image extraction timeout in milliseconds. + /// </summary> + internal const int DefaultHdrImageExtractionTimeout = 20000; /// <summary> /// The us culture. @@ -495,9 +500,36 @@ namespace MediaBrowser.MediaEncoding.Encoder } else { + // The failure of HDR extraction usually occurs when using custom ffmpeg that does not contain the zscale filter. try { - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, true, cancellationToken).ConfigureAwait(false); + } + catch (ArgumentException) + { + throw; + } + catch (Exception ex) + { + _logger.LogError(ex, "I-frame or HDR image extraction failed, will attempt with I-frame extraction disabled. Input: {Arguments}", inputArgument); + } + + try + { + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, true, cancellationToken).ConfigureAwait(false); + } + catch (ArgumentException) + { + throw; + } + catch (Exception ex) + { + _logger.LogError(ex, "HDR image extraction failed, will fallback to SDR image extraction. Input: {Arguments}", inputArgument); + } + + try + { + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, false, cancellationToken).ConfigureAwait(false); } catch (ArgumentException) { @@ -509,10 +541,10 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, cancellationToken).ConfigureAwait(false); + return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, false, cancellationToken).ConfigureAwait(false); } - private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, CancellationToken cancellationToken) + private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, bool allowTonemap, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(inputPath)) { @@ -553,6 +585,20 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; + var enableHdrExtraction = allowTonemap && videoStream != null && !string.IsNullOrEmpty(videoStream.VideoRange) && string.Equals(videoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase); + if (enableHdrExtraction) + { + string tonemapFilters = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p"; + if (string.IsNullOrEmpty(vf)) + { + vf = "-vf " + tonemapFilters; + } + else + { + vf += "," + tonemapFilters; + } + } + // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); if (enableThumbnail) @@ -635,7 +681,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var timeoutMs = _configurationManager.Configuration.ImageExtractionTimeoutMs; if (timeoutMs <= 0) { - timeoutMs = DefaultImageExtractionTimeout; + timeoutMs = enableHdrExtraction ? DefaultHdrImageExtractionTimeout : DefaultSdrImageExtractionTimeout; } ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMilliseconds(timeoutMs)).ConfigureAwait(false); From 92118c2129ec8175665e65dcd78c1400fbe60c80 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sun, 29 Nov 2020 22:46:26 +0800 Subject: [PATCH 0579/1930] allow to extract music bitrate info from formatInfo --- MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 97d61441cf..27bd693e33 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -778,7 +778,11 @@ namespace MediaBrowser.MediaEncoding.Probing } } - if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.BitRate) && stream.Type == MediaStreamType.Video) + // The bitrate info of FLAC musics and some videos is included in formatInfo. + if (bitrate == 0 + && formatInfo != null + && !string.IsNullOrEmpty(formatInfo.BitRate) + && (stream.Type == MediaStreamType.Video || stream.Type == MediaStreamType.Audio)) { // If the stream info doesn't have a bitrate get the value from the media format info if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, _usCulture, out var value)) From 7561eda0f0c931d6b47f8d4c65443bc4455d9830 Mon Sep 17 00:00:00 2001 From: Enes <biganes@gmail.com> Date: Sun, 29 Nov 2020 20:51:40 +0000 Subject: [PATCH 0580/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 54d3a65f0d..10b5f81be1 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -12,7 +12,7 @@ "DeviceOfflineWithName": "{0} bağlantısı kesildi", "DeviceOnlineWithName": "{0} bağlı", "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu", - "Favorites": "Favoriler", + "Favorites": "Favorilerim", "Folders": "Klasörler", "Genres": "Türler", "HeaderAlbumArtists": "Albüm Sanatçıları", From 21893b6abe3fae6df9cdda9b5f186dbe851847a7 Mon Sep 17 00:00:00 2001 From: TF <thomasframe@rocketmail.com> Date: Sun, 29 Nov 2020 21:44:52 +0000 Subject: [PATCH 0581/1930] Translated using Weblate (Portuguese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt/ --- Emby.Server.Implementations/Localization/Core/pt.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt.json b/Emby.Server.Implementations/Localization/Core/pt.json index c2ad260dfd..f1a78b2d32 100644 --- a/Emby.Server.Implementations/Localization/Core/pt.json +++ b/Emby.Server.Implementations/Localization/Core/pt.json @@ -116,5 +116,6 @@ "TaskCleanActivityLog": "Limpar registo de atividade", "Undefined": "Indefinido", "Forced": "Forçado", - "Default": "Predefinição" + "Default": "Predefinição", + "TaskCleanActivityLogDescription": "Apaga itens no registro com idade acima do que é configurado." } From 2375bd69e44d6a898af6d2786822f969203bafec Mon Sep 17 00:00:00 2001 From: Enes <biganes@gmail.com> Date: Sun, 29 Nov 2020 22:49:35 +0000 Subject: [PATCH 0582/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 10b5f81be1..885663eed8 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -115,5 +115,7 @@ "TaskRefreshChapterImages": "Bölüm Resimlerini Çıkar", "TaskCleanCacheDescription": "Sistem tarafından artık ihtiyaç duyulmayan önbellek dosyalarını siler.", "TaskCleanActivityLog": "İşlem Günlüğünü Temizle", - "TaskCleanActivityLogDescription": "Belirtilen sureden daha eski etkinlik log kayıtları silindi." + "TaskCleanActivityLogDescription": "Belirtilen sureden daha eski etkinlik log kayıtları silindi.", + "Undefined": "Bilinmeyen", + "Default": "Varsayılan" } From b57ace7888db78a655a00a277e7eb5c4a4eba294 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 30 Nov 2020 10:03:42 +0100 Subject: [PATCH 0583/1930] Address requested changes from review --- .../SyncPlay/GroupController.cs | 20 +---- .../SyncPlay/SyncPlayManager.cs | 75 ++++++++++++------- 2 files changed, 48 insertions(+), 47 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/GroupController.cs index dc262f1cfc..16acae99e8 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/GroupController.cs @@ -188,19 +188,6 @@ namespace Emby.Server.Implementations.SyncPlay }; } - /// <summary> - /// Checks if a given user can access a given item, that is, the user has access to a folder where the item is stored. - /// </summary> - /// <param name="user">The user.</param> - /// <param name="item">The item.</param> - /// <returns><c>true</c> if the user can access the item, <c>false</c> otherwise.</returns> - private bool HasAccessToItem(User user, BaseItem item) - { - var collections = _libraryManager.GetCollectionFolders(item) - .Select(folder => folder.Id.ToString("N", CultureInfo.InvariantCulture)); - return collections.Intersect(user.GetPreference(PreferenceKind.EnabledFolders)).Any(); - } - /// <summary> /// Checks if a given user can access all items of a given queue, that is, /// the user has the required minimum parental access and has access to all required folders. @@ -219,12 +206,7 @@ namespace Emby.Server.Implementations.SyncPlay foreach (var itemId in queue) { var item = _libraryManager.GetItemById(itemId); - if (user.MaxParentalAgeRating.HasValue && item.InheritedParentalRatingValue > user.MaxParentalAgeRating) - { - return false; - } - - if (!user.HasPermission(PermissionKind.EnableAllFolders) && !HasAccessToItem(user, item)) + if (!item.IsVisibleStandalone(user)) { return false; } diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index fbd3c3cfb2..7e1f24f8c2 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -56,11 +56,17 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// Lock used for accessing any group. /// </summary> + /// <remarks> + /// Always lock before <see cref="_mapsLock"/> and before locking on any <see cref="IGroupController"/>. + /// </remarks> private readonly object _groupsLock = new object(); /// <summary> /// Lock used for accessing the session-to-group map. /// </summary> + /// <remarks> + /// Always lock after <see cref="_groupsLock"/> and before locking on any <see cref="IGroupController"/>. + /// </remarks> private readonly object _mapsLock = new object(); private bool _disposed = false; @@ -259,7 +265,12 @@ namespace Emby.Server.Implementations.SyncPlay return; } - var group = FindJoinedGroup(session); + IGroupController group; + lock (_mapsLock) + { + group = FindJoinedGroup(session); + } + if (group == null) { _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); @@ -295,7 +306,12 @@ namespace Emby.Server.Implementations.SyncPlay { var session = e.SessionInfo; - Guid groupId = FindJoinedGroupId(session); + Guid groupId = Guid.Empty; + lock (_mapsLock) + { + groupId = FindJoinedGroupId(session); + } + if (groupId.Equals(Guid.Empty)) { return; @@ -308,33 +324,36 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// Checks if a given session has joined a group. /// </summary> + /// <remarks> + /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. + /// </remarks> /// <param name="session">The session.</param> /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns> private bool IsSessionInGroup(SessionInfo session) { - lock (_mapsLock) - { - return _sessionToGroupMap.ContainsKey(session.Id); - } + return _sessionToGroupMap.ContainsKey(session.Id); } /// <summary> /// Gets the group joined by the given session, if any. /// </summary> + /// <remarks> + /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. + /// </remarks> /// <param name="session">The session.</param> /// <returns>The group.</returns> private IGroupController FindJoinedGroup(SessionInfo session) { - lock (_mapsLock) - { - _sessionToGroupMap.TryGetValue(session.Id, out var group); - return group; - } + _sessionToGroupMap.TryGetValue(session.Id, out var group); + return group; } /// <summary> /// Gets the group identifier joined by the given session, if any. /// </summary> + /// <remarks> + /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. + /// </remarks> /// <param name="session">The session.</param> /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns> private Guid FindJoinedGroupId(SessionInfo session) @@ -345,6 +364,9 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// Maps a session to a group. /// </summary> + /// <remarks> + /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. + /// </remarks> /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> @@ -355,20 +377,20 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Session is null!"); } - lock (_mapsLock) + if (IsSessionInGroup(session)) { - if (IsSessionInGroup(session)) - { - throw new InvalidOperationException("Session in other group already!"); - } - - _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); + throw new InvalidOperationException("Session in other group already!"); } + + _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); } /// <summary> /// Unmaps a session from a group. /// </summary> + /// <remarks> + /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. + /// </remarks> /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> @@ -384,18 +406,15 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Group is null!"); } - lock (_mapsLock) + if (!IsSessionInGroup(session)) { - if (!IsSessionInGroup(session)) - { - throw new InvalidOperationException("Session not in any group!"); - } + throw new InvalidOperationException("Session not in any group!"); + } - _sessionToGroupMap.Remove(session.Id, out var tempGroup); - if (!tempGroup.GroupId.Equals(group.GroupId)) - { - throw new InvalidOperationException("Session was in wrong group!"); - } + _sessionToGroupMap.Remove(session.Id, out var tempGroup); + if (!tempGroup.GroupId.Equals(group.GroupId)) + { + throw new InvalidOperationException("Session was in wrong group!"); } } From ea592d0256f68437d9a3ddd7406001d927f4337a Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Mon, 30 Nov 2020 18:36:11 +0800 Subject: [PATCH 0584/1930] fix trascodeReasons report --- Jellyfin.Api/Controllers/AudioController.cs | 12 +++---- .../Controllers/DynamicHlsController.cs | 36 +++++++++---------- .../Controllers/VideoHlsController.cs | 6 ++-- Jellyfin.Api/Controllers/VideosController.cs | 12 +++---- 4 files changed, 33 insertions(+), 33 deletions(-) diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs index c22979495d..616fe5b91f 100644 --- a/Jellyfin.Api/Controllers/AudioController.cs +++ b/Jellyfin.Api/Controllers/AudioController.cs @@ -78,7 +78,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -134,7 +134,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext? context, @@ -186,7 +186,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context ?? EncodingContext.Static, @@ -243,7 +243,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -299,7 +299,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext? context, @@ -351,7 +351,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context ?? EncodingContext.Static, diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index eff5bd54ad..6e85737d26 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -160,7 +160,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -216,7 +216,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -268,7 +268,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -326,7 +326,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -383,7 +383,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -435,7 +435,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -492,7 +492,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -546,7 +546,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -598,7 +598,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -656,7 +656,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -711,7 +711,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -763,7 +763,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -823,7 +823,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -881,7 +881,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -933,7 +933,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -994,7 +994,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -1053,7 +1053,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -1105,7 +1105,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 2ac16de6b9..7e743ee0c7 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -153,7 +153,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -211,7 +211,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -266,7 +266,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 8e17b843a6..d8bc9df1f5 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -320,7 +320,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -376,7 +376,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -430,7 +430,7 @@ namespace Jellyfin.Api.Controllers EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, - TranscodeReasons = transcodingReasons, + TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context, @@ -576,7 +576,7 @@ namespace Jellyfin.Api.Controllers /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param> /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264. If omitted the server will auto-select using the url's extension. Options: h265, h264, mpeg4, theora, vpx, wmv.</param> /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param> - /// <param name="transcodingReasons">Optional. The transcoding reason.</param> + /// <param name="transcodeReasons">Optional. The transcoding reason.</param> /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream will be used.</param> /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream will be used.</param> /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param> @@ -632,7 +632,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableMpegtsM2TsMode, [FromQuery] string? videoCodec, [FromQuery] string? subtitleCodec, - [FromQuery] string? transcodingReasons, + [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, [FromQuery] EncodingContext context, @@ -683,7 +683,7 @@ namespace Jellyfin.Api.Controllers enableMpegtsM2TsMode, videoCodec, subtitleCodec, - transcodingReasons, + transcodeReasons, audioStreamIndex, videoStreamIndex, context, From 21a2dec5b22b0b585a805ef79e005fc5a89762af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 12:00:45 +0000 Subject: [PATCH 0585/1930] Bump ServiceStack.Text.Core from 5.10.0 to 5.10.2 Bumps [ServiceStack.Text.Core](https://github.com/ServiceStack/ServiceStack.Text) from 5.10.0 to 5.10.2. - [Release notes](https://github.com/ServiceStack/ServiceStack.Text/releases) - [Commits](https://github.com/ServiceStack/ServiceStack.Text/compare/v5.10...v5.10.2) Signed-off-by: dependabot[bot] <support@github.com> --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index dab4ec5a69..21fa828560 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -37,7 +37,7 @@ <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> <PackageReference Include="Mono.Nat" Version="3.0.1" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.0" /> - <PackageReference Include="ServiceStack.Text.Core" Version="5.10.0" /> + <PackageReference Include="ServiceStack.Text.Core" Version="5.10.2" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="2.1.0" /> <PackageReference Include="DotNet.Glob" Version="3.1.0" /> From 44edd4b1a2b4ed41e56dda95b744120ac1a773af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 12:01:00 +0000 Subject: [PATCH 0586/1930] Bump Moq from 4.15.1 to 4.15.2 Bumps [Moq](https://github.com/moq/moq4) from 4.15.1 to 4.15.2. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/master/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/commits/v4.15.2) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 14eed30e03..7c552ec060 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,7 +22,7 @@ <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> - <PackageReference Include="Moq" Version="4.15.1" /> + <PackageReference Include="Moq" Version="4.15.2" /> </ItemGroup> <!-- Code Analyzers --> diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index 703d43210b..48b0b4c7d6 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -17,7 +17,7 @@ <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> - <PackageReference Include="Moq" Version="4.14.5" /> + <PackageReference Include="Moq" Version="4.15.2" /> </ItemGroup> <!-- Code Analyzers--> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 547f80ed96..fffbc6212a 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -17,7 +17,7 @@ <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> - <PackageReference Include="Moq" Version="4.15.1" /> + <PackageReference Include="Moq" Version="4.15.2" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> From d13611f7dae43f31620db3093b997b18f3453a3f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 15:06:21 +0000 Subject: [PATCH 0587/1930] Bump prometheus-net.DotNetRuntime from 3.4.0 to 3.4.1 Bumps [prometheus-net.DotNetRuntime](https://github.com/djluck/prometheus-net.DotNetRuntime) from 3.4.0 to 3.4.1. - [Release notes](https://github.com/djluck/prometheus-net.DotNetRuntime/releases) - [Commits](https://github.com/djluck/prometheus-net.DotNetRuntime/compare/3.4.0...3.4.1) Signed-off-by: dependabot[bot] <support@github.com> --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 21fa828560..91c4648c62 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -36,7 +36,7 @@ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> <PackageReference Include="Mono.Nat" Version="3.0.1" /> - <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.0" /> + <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.1" /> <PackageReference Include="ServiceStack.Text.Core" Version="5.10.2" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="2.1.0" /> From d2d71ac3a17716bceed13855261e015cdc46ed42 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 30 Nov 2020 08:47:52 -0700 Subject: [PATCH 0588/1930] Fix OpenApi generation for BlurHash --- .../ApiServiceCollectionExtensions.cs | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 6cb88c9f73..e5b9620f78 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -285,20 +285,17 @@ namespace Jellyfin.Server.Extensions private static void AddSwaggerTypeMappings(this SwaggerGenOptions options) { /* - * TODO remove when System.Text.Json supports non-string keys. - * Used in Jellyfin.Api.Controller.GetChannels. + * TODO remove when System.Text.Json properly supports non-string keys. + * Used in BaseItemDto.ImageBlurHashes */ options.MapType<Dictionary<ImageType, string>>(() => new OpenApiSchema { Type = "object", - Properties = typeof(ImageType).GetEnumNames().ToDictionary( - name => name, - name => new OpenApiSchema - { - Type = "string", - Format = "string" - }) + AdditionalProperties = new OpenApiSchema + { + Type = "string" + } }); /* @@ -312,16 +309,10 @@ namespace Jellyfin.Server.Extensions name => name, name => new OpenApiSchema { - Type = "object", Properties = new Dictionary<string, OpenApiSchema> + Type = "object", + AdditionalProperties = new OpenApiSchema { - { - "string", - new OpenApiSchema - { - Type = "string", - Format = "string" - } - } + Type = "string" } }) }); From d734deb6c1afeb5505783a424f3cbf16391ac082 Mon Sep 17 00:00:00 2001 From: xnick <christoulakisnick@gmail.com> Date: Mon, 30 Nov 2020 15:39:37 +0000 Subject: [PATCH 0589/1930] Translated using Weblate (Greek) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/el/ --- Emby.Server.Implementations/Localization/Core/el.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/el.json b/Emby.Server.Implementations/Localization/Core/el.json index dcf3311cd2..23d45b4737 100644 --- a/Emby.Server.Implementations/Localization/Core/el.json +++ b/Emby.Server.Implementations/Localization/Core/el.json @@ -114,7 +114,7 @@ "TaskUpdatePluginsDescription": "Κατεβάζει και εγκαθιστά ενημερώσεις για τις προσθήκες που έχουν ρυθμιστεί για αυτόματη ενημέρωση.", "TaskUpdatePlugins": "Ενημέρωση Προσθηκών", "TaskRefreshPeopleDescription": "Ενημερώνει μεταδεδομένα για ηθοποιούς και σκηνοθέτες στην βιβλιοθήκη των πολυμέσων σας.", - "TaskCleanActivityLogDescription": "Διαγράφει καταχωρήσεις απο το αρχείο καταγραφής δραστηριοτήτων παλαιότερες από την ηλικία που έχει διαμορφωθεί.", + "TaskCleanActivityLogDescription": "Διαγράφει καταχωρήσεις απο το αρχείο καταγραφής παλαιότερες από την επιλεγμένη ηλικία.", "TaskCleanActivityLog": "Καθαρό Αρχείο Καταγραφής Δραστηριοτήτων", "Undefined": "Απροσδιόριστο", "Forced": "Εξαναγκασμένο", From 6536c81226d5348f587119aa46635b32cc7a807e Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Tue, 1 Dec 2020 10:53:56 +0800 Subject: [PATCH 0590/1930] do not extract audio stream bitrate info for videos from formatInfo --- MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 27bd693e33..bd026bce15 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -782,7 +782,7 @@ namespace MediaBrowser.MediaEncoding.Probing if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.BitRate) - && (stream.Type == MediaStreamType.Video || stream.Type == MediaStreamType.Audio)) + && (stream.Type == MediaStreamType.Video || (isAudio && stream.Type == MediaStreamType.Audio))) { // If the stream info doesn't have a bitrate get the value from the media format info if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, _usCulture, out var value)) From 21a67a66d250cdb8569cc85398d8378c88b52013 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Tue, 1 Dec 2020 13:55:52 +0100 Subject: [PATCH 0591/1930] Prevent GetUpNext from returning episodes in progress --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a697c6476f..a079d76ef0 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -192,7 +192,7 @@ namespace Emby.Server.Implementations.TV Func<Episode> getEpisode = () => { - return _libraryManager.GetItemList(new InternalItemsQuery(user) + var nextEpsiode = _libraryManager.GetItemList(new InternalItemsQuery(user) { AncestorWithPresentationUniqueKey = null, SeriesPresentationUniqueKey = seriesKey, @@ -205,6 +205,15 @@ namespace Emby.Server.Implementations.TV MinSortName = lastWatchedEpisode?.SortName, DtoOptions = dtoOptions }).Cast<Episode>().FirstOrDefault(); + + var userData = _userDataManager.GetUserData(user, nextEpsiode); + + if (userData.PlaybackPositionTicks > 0) + { + return null; + } + + return nextEpsiode; }; if (lastWatchedEpisode != null) From 38b3b4f8672373c8e1ac2e509d759fe07d179146 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 06:32:46 -0700 Subject: [PATCH 0592/1930] Provide NoResult instead of Fail in CustomAuthenticationHandler --- Jellyfin.Api/Auth/CustomAuthenticationHandler.cs | 10 ++++++++-- .../Auth/CustomAuthenticationHandlerTests.cs | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index 27a1f61be0..f98d5c11ae 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; @@ -7,6 +8,7 @@ using Jellyfin.Data.Enums; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -18,6 +20,7 @@ namespace Jellyfin.Api.Auth public class CustomAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> { private readonly IAuthService _authService; + private readonly ILogger<CustomAuthenticationHandler> _logger; /// <summary> /// Initializes a new instance of the <see cref="CustomAuthenticationHandler" /> class. @@ -35,6 +38,7 @@ namespace Jellyfin.Api.Auth ISystemClock clock) : base(options, logger, encoder, clock) { _authService = authService; + _logger = logger.CreateLogger<CustomAuthenticationHandler>(); } /// <inheritdoc /> @@ -70,11 +74,13 @@ namespace Jellyfin.Api.Auth } catch (AuthenticationException ex) { - return Task.FromResult(AuthenticateResult.Fail(ex)); + _logger.LogDebug(ex, "Error authenticating with {Handler}", nameof(CustomAuthenticationHandler)); + return Task.FromResult(AuthenticateResult.NoResult()); } catch (SecurityException ex) { - return Task.FromResult(AuthenticateResult.Fail(ex)); + _logger.LogDebug(ex, "Error authenticating with {Handler}", nameof(CustomAuthenticationHandler)); + return Task.FromResult(AuthenticateResult.NoResult()); } } } diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index 90c4916668..ee20cc5738 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -69,7 +69,7 @@ namespace Jellyfin.Api.Tests.Auth } [Fact] - public async Task HandleAuthenticateAsyncShouldFailOnAuthenticationException() + public async Task HandleAuthenticateAsyncShouldProvideNoResultOnAuthenticationException() { var errorMessage = _fixture.Create<string>(); @@ -81,7 +81,7 @@ namespace Jellyfin.Api.Tests.Auth var authenticateResult = await _sut.AuthenticateAsync(); Assert.False(authenticateResult.Succeeded); - Assert.Equal(errorMessage, authenticateResult.Failure?.Message); + Assert.True(authenticateResult.None); } [Fact] From f6a38e63401a85ccb3d038a6a50825ddcaf84298 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Tue, 1 Dec 2020 15:12:55 +0100 Subject: [PATCH 0593/1930] Add tests for GetUuid --- Emby.Dlna/PlayTo/PlayToManager.cs | 26 ++++++++++----- Emby.Dlna/Properties/AssemblyInfo.cs | 2 ++ MediaBrowser.sln | 9 ++++- tests/Jellyfin.Dlna.Tests/GetUuidTests.cs | 17 ++++++++++ .../Jellyfin.Dlna.Tests.csproj | 33 +++++++++++++++++++ 5 files changed, 78 insertions(+), 9 deletions(-) create mode 100644 tests/Jellyfin.Dlna.Tests/GetUuidTests.cs create mode 100644 tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index 854b6a1a2b..cb183ce71e 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -3,13 +3,11 @@ using System; using System.Globalization; using System.Linq; -using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; @@ -130,24 +128,36 @@ namespace Emby.Dlna.PlayTo } } - private static string GetUuid(string usn) + internal static string GetUuid(string usn) { const string UuidStr = "uuid:"; const string UuidColonStr = "::"; var index = usn.IndexOf(UuidStr, StringComparison.OrdinalIgnoreCase); - if (index != -1) + if (index == -1) { - return usn.Substring(index + UuidStr.Length); + return usn.GetMD5().ToString("N", CultureInfo.InvariantCulture); } - index = usn.IndexOf(UuidColonStr, StringComparison.OrdinalIgnoreCase); + ReadOnlySpan<char> tmp = usn.AsSpan()[(index + UuidStr.Length)..]; + + index = tmp.IndexOf(UuidColonStr, StringComparison.OrdinalIgnoreCase); if (index != -1) { - usn = usn.Substring(0, index + UuidColonStr.Length); + tmp = tmp[..index]; } - return usn.GetMD5().ToString("N", CultureInfo.InvariantCulture); + index = tmp.IndexOf('{'); + if (index != -1) + { + int endIndex = tmp.IndexOf('}'); + if (endIndex != -1) + { + tmp = tmp[(index + 1)..endIndex]; + } + } + + return tmp.ToString(); } private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken) diff --git a/Emby.Dlna/Properties/AssemblyInfo.cs b/Emby.Dlna/Properties/AssemblyInfo.cs index a2c1e0db8b..606ffcf4fd 100644 --- a/Emby.Dlna/Properties/AssemblyInfo.cs +++ b/Emby.Dlna/Properties/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Resources; +using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information @@ -13,6 +14,7 @@ using System.Resources; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] +[assembly: InternalsVisibleTo("Jellyfin.Dlna.Tests")] // Version information for an assembly consists of the following four values: // diff --git a/MediaBrowser.sln b/MediaBrowser.sln index cb204137bd..5a807372d7 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,4 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -70,6 +70,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\NetworkTesting\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -188,6 +190,10 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU + {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -200,6 +206,7 @@ Global {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs b/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs new file mode 100644 index 0000000000..7655e3f7ce --- /dev/null +++ b/tests/Jellyfin.Dlna.Tests/GetUuidTests.cs @@ -0,0 +1,17 @@ +using Emby.Dlna.PlayTo; +using Xunit; + +namespace Jellyfin.Dlna.Tests +{ + public static class GetUuidTests + { + [Theory] + [InlineData("uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::urn:schemas-upnp-org:device:WANDevice:1", "fc4ec57e-b051-11db-88f8-0060085db3f6")] + [InlineData("uuid:IGD{8c80f73f-4ba0-45fa-835d-042505d052be}000000000000", "8c80f73f-4ba0-45fa-835d-042505d052be")] + [InlineData("uuid:IGD{8c80f73f-4ba0-45fa-835d-042505d052be}000000000000::urn:schemas-upnp-org:device:InternetGatewayDevice:1", "8c80f73f-4ba0-45fa-835d-042505d052be")] + [InlineData("uuid:00000000-0000-0000-0000-000000000000::upnp:rootdevice", "00000000-0000-0000-0000-000000000000")] + [InlineData("uuid:fc4ec57e-b051-11db-88f8-0060085db3f6", "fc4ec57e-b051-11db-88f8-0060085db3f6")] + public static void GetUuid_Valid_Success(string usn, string uuid) + => Assert.Equal(uuid, PlayToManager.GetUuid(usn)); + } +} diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj new file mode 100644 index 0000000000..f91db6744a --- /dev/null +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -0,0 +1,33 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net5.0</TargetFramework> + <IsPackable>false</IsPackable> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="xunit" Version="2.4.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> + <PackageReference Include="coverlet.collector" Version="1.3.0" /> + </ItemGroup> + + <!-- Code Analyzers --> + <ItemGroup Condition=" '$(Configuration)' == 'Debug' "> + <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" /> + <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" /> + <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="../../Emby.Dlna/Emby.Dlna.csproj" /> + </ItemGroup> + + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> + <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + +</Project> From f660969e6c5bd3fc8b3898277e1f8d23d557816e Mon Sep 17 00:00:00 2001 From: 4d1m <silviu.dimulete@gmail.com> Date: Tue, 1 Dec 2020 14:44:11 +0000 Subject: [PATCH 0594/1930] Translated using Weblate (Romanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ro/ --- Emby.Server.Implementations/Localization/Core/ro.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ro.json b/Emby.Server.Implementations/Localization/Core/ro.json index 5e4022292e..510aac11c6 100644 --- a/Emby.Server.Implementations/Localization/Core/ro.json +++ b/Emby.Server.Implementations/Localization/Core/ro.json @@ -114,5 +114,8 @@ "TasksLibraryCategory": "Librărie", "TasksMaintenanceCategory": "Mentenanță", "TaskCleanActivityLogDescription": "Șterge intrările din jurnalul de activitate mai vechi de data configurată.", - "TaskCleanActivityLog": "Curăță Jurnalul de Activitate" + "TaskCleanActivityLog": "Curăță Jurnalul de Activitate", + "Undefined": "Nedefinit", + "Forced": "Forțat", + "Default": "Implicit" } From b32c75fee5cb6b8d46fc3cbe93a1cdfb3a594783 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 09:57:13 -0700 Subject: [PATCH 0595/1930] Fix MusicBrainz request Accept header. --- Jellyfin.Server/Startup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 4ffcb940ff..f144dd12e5 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -81,7 +81,7 @@ namespace Jellyfin.Server { c.DefaultRequestHeaders.UserAgent.Add(productHeader); c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue($"({_serverApplicationHost.ApplicationUserAgentAddress})")); - c.DefaultRequestHeaders.Accept.Add(acceptJsonHeader); + c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader); c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); From c083b29e292c72b65929ea05639e3b5a8a401037 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 11:07:41 -0700 Subject: [PATCH 0596/1930] Use Guid as API parameter type where possible --- .../Channels/ChannelManager.cs | 12 ++++----- .../Library/LibraryManager.cs | 15 +++++++++++ .../Library/SearchEngine.cs | 4 +-- .../TV/TVSeriesManager.cs | 6 ++--- Jellyfin.Api/Controllers/ArtistsController.cs | 25 +++++++++---------- .../Controllers/ChannelsController.cs | 2 +- Jellyfin.Api/Controllers/FilterController.cs | 24 +++++++++--------- Jellyfin.Api/Controllers/GenresController.cs | 8 +++--- Jellyfin.Api/Controllers/ItemsController.cs | 14 +++++------ Jellyfin.Api/Controllers/LibraryController.cs | 2 +- Jellyfin.Api/Controllers/MoviesController.cs | 4 +-- .../Controllers/MusicGenresController.cs | 8 +++--- Jellyfin.Api/Controllers/PackageController.cs | 8 +++--- Jellyfin.Api/Controllers/PersonsController.cs | 4 +-- Jellyfin.Api/Controllers/SearchController.cs | 2 +- Jellyfin.Api/Controllers/StudiosController.cs | 8 +++--- .../Controllers/TrailersController.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 22 ++++++++-------- Jellyfin.Api/Controllers/YearsController.cs | 6 ++--- .../Channels/IChannelManager.cs | 2 +- .../Library/ILibraryManager.cs | 2 ++ MediaBrowser.Model/Querying/NextUpQuery.cs | 2 +- MediaBrowser.Model/Search/SearchQuery.cs | 2 +- 23 files changed, 99 insertions(+), 85 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 3d97a6ca8d..b8692f0e50 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -538,20 +538,20 @@ namespace Emby.Server.Implementations.Channels return _libraryManager.GetItemIds( new InternalItemsQuery { - IncludeItemTypes = new[] { nameof(Channel) }, - OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) } - }).Select(i => GetChannelFeatures(i.ToString("N", CultureInfo.InvariantCulture))).ToArray(); + IncludeItemTypes = new[] {nameof(Channel)}, + OrderBy = new[] {(ItemSortBy.SortName, SortOrder.Ascending)} + }).Select(i => GetChannelFeatures(i)).ToArray(); } /// <inheritdoc /> - public ChannelFeatures GetChannelFeatures(string id) + public ChannelFeatures GetChannelFeatures(Guid? id) { - if (string.IsNullOrEmpty(id)) + if (!id.HasValue) { throw new ArgumentNullException(nameof(id)); } - var channel = GetChannel(id); + var channel = GetChannel(id.Value); var channelProvider = GetChannelProvider(channel); return GetChannelFeaturesDto(channel, channelProvider, channelProvider.GetChannelFeatures()); diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 013781258e..0c1018499a 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2474,6 +2474,21 @@ namespace Emby.Server.Implementations.Library return RootFolder; } + + public BaseItem GetParentItem(Guid? parentId, Guid? userId) + { + if (parentId.HasValue) + { + return GetItemById(parentId.Value); + } + + if (userId.HasValue && userId != Guid.Empty) + { + return GetUserRootFolder(); + } + + return RootFolder; + } /// <inheritdoc /> public bool IsVideoFile(string path) diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index c850e3a082..6cb683854d 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -156,8 +156,8 @@ namespace Emby.Server.Implementations.Library ExcludeItemTypes = excludeItemTypes.ToArray(), IncludeItemTypes = includeItemTypes.ToArray(), Limit = query.Limit, - IncludeItemsByName = string.IsNullOrEmpty(query.ParentId), - ParentId = string.IsNullOrEmpty(query.ParentId) ? Guid.Empty : new Guid(query.ParentId), + IncludeItemsByName = query.ParentId.HasValue, + ParentId = query.ParentId ?? Guid.Empty, OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }, Recursive = true, diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a697c6476f..04c55125e4 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -56,13 +56,11 @@ namespace Emby.Server.Implementations.TV return GetResult(GetNextUpEpisodes(request, user, new[] { presentationUniqueKey }, dtoOptions), request); } - var parentIdGuid = string.IsNullOrEmpty(request.ParentId) ? (Guid?)null : new Guid(request.ParentId); - BaseItem[] parents; - if (parentIdGuid.HasValue) + if (request.ParentId.HasValue) { - var parent = _libraryManager.GetItemById(parentIdGuid.Value); + var parent = _libraryManager.GetItemById(request.ParentId.Value); if (parent != null) { diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index c65dc86201..cdac009d4b 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -3,7 +3,6 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; @@ -87,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -124,11 +123,11 @@ namespace Jellyfin.Api.Controllers if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); } else { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } var query = new InternalItemsQuery(user) @@ -157,15 +156,15 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount }; - if (!string.IsNullOrWhiteSpace(parentId)) + if (parentId.HasValue) { if (parentItem is Folder) { - query.AncestorIds = new[] { new Guid(parentId) }; + query.AncestorIds = new[] { parentId.Value }; } else { - query.ItemIds = new[] { new Guid(parentId) }; + query.ItemIds = new[] { parentId.Value }; } } @@ -291,7 +290,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -328,11 +327,11 @@ namespace Jellyfin.Api.Controllers if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); } else { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } var query = new InternalItemsQuery(user) @@ -361,15 +360,15 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount }; - if (!string.IsNullOrWhiteSpace(parentId)) + if (parentId.HasValue) { if (parentItem is Folder) { - query.AncestorIds = new[] { new Guid(parentId) }; + query.AncestorIds = new[] { parentId.Value }; } else { - query.ItemIds = new[] { new Guid(parentId) }; + query.ItemIds = new[] { parentId.Value }; } } diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index c4dc44cc36..b70c76e807 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -92,7 +92,7 @@ namespace Jellyfin.Api.Controllers /// <response code="200">Channel features returned.</response> /// <returns>An <see cref="OkResult"/> containing the channel features.</returns> [HttpGet("{channelId}/Features")] - public ActionResult<ChannelFeatures> GetChannelFeatures([FromRoute, Required] string channelId) + public ActionResult<ChannelFeatures> GetChannelFeatures([FromRoute, Required] Guid channelId) { return _channelManager.GetChannelFeatures(channelId); } diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 31cb9e2736..7b3111cffc 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -50,13 +50,13 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryFiltersLegacy> GetQueryFiltersLegacy( [FromQuery] Guid? userId, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes) { - var parentItem = string.IsNullOrEmpty(parentId) - ? null - : _libraryManager.GetItemById(parentId); + var parentItem = parentId.HasValue + ? _libraryManager.GetItemById(parentId.Value) + : null; var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) @@ -71,11 +71,11 @@ namespace Jellyfin.Api.Controllers parentItem = null; } - var item = string.IsNullOrEmpty(parentId) - ? user == null + var item = parentId.HasValue + ? parentItem + : user == null ? _libraryManager.RootFolder - : _libraryManager.GetUserRootFolder() - : parentItem; + : _libraryManager.GetUserRootFolder(); var query = new InternalItemsQuery { @@ -140,7 +140,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<QueryFilters> GetQueryFilters( [FromQuery] Guid? userId, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery] bool? isAiring, [FromQuery] bool? isMovie, @@ -150,9 +150,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isSeries, [FromQuery] bool? recursive) { - var parentItem = string.IsNullOrEmpty(parentId) - ? null - : _libraryManager.GetItemById(parentId); + var parentItem = parentId.HasValue + ? _libraryManager.GetItemById(parentId.Value) + : null; var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index d2b41e0a8d..b6755ed5e5 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -72,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -109,15 +109,15 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount }; - if (!string.IsNullOrWhiteSpace(parentId)) + if (parentId.HasValue) { if (parentItem is Folder) { - query.AncestorIds = new[] { new Guid(parentId) }; + query.AncestorIds = new[] { parentId.Value }; } else { - query.ItemIds = new[] { new Guid(parentId) }; + query.ItemIds = new[] { parentId.Value }; } } diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index b0979fbcf7..a05c0f534a 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -176,7 +176,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? recursive, [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -241,9 +241,9 @@ namespace Jellyfin.Api.Controllers BaseItem? item = null; QueryResult<BaseItem> result; - if (!string.IsNullOrEmpty(parentId)) + if (parentId.HasValue) { - item = _libraryManager.GetItemById(parentId); + item = _libraryManager.GetItemById(parentId.Value); } item ??= _libraryManager.GetUserRootFolder(); @@ -343,7 +343,7 @@ namespace Jellyfin.Api.Controllers ItemIds = ids, MinCommunityRating = minCommunityRating, MinCriticRating = minCriticRating, - ParentId = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId), + ParentId = parentId ?? Guid.Empty, ParentIndexNumber = parentIndexNumber, EnableTotalRecordCount = enableTotalRecordCount, ExcludeItemIds = excludeItemIds, @@ -615,7 +615,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? recursive, [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -773,7 +773,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery] bool? enableUserData, @@ -785,7 +785,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableImages = true) { var user = _userManager.GetUserById(userId); - var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); + var parentIdGuid = parentId ?? Guid.Empty; var dtoOptions = new DtoOptions { Fields = fields } .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 3ff77e8e01..184843b397 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -362,7 +362,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] - public ActionResult DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] ids) + public ActionResult DeleteItems([FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids) { if (ids.Length == 0) { diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index 75dfd4e68b..4d788ad7d3 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -65,7 +65,7 @@ namespace Jellyfin.Api.Controllers [HttpGet("Recommendations")] public ActionResult<IEnumerable<RecommendationDto>> GetMovieRecommendations( [FromQuery] Guid? userId, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] int categoryLimit = 5, [FromQuery] int itemLimit = 8) @@ -78,7 +78,7 @@ namespace Jellyfin.Api.Controllers var categories = new List<RecommendationDto>(); - var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); + var parentIdGuid = parentId ?? Guid.Empty; var query = new InternalItemsQuery(user) { diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index e7d0a61c58..2608a9cd09 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -72,7 +72,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -109,15 +109,15 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount }; - if (!string.IsNullOrWhiteSpace(parentId)) + if (parentId.HasValue) { if (parentItem is Folder) { - query.AncestorIds = new[] { new Guid(parentId) }; + query.AncestorIds = new[] { parentId.Value }; } else { - query.ItemIds = new[] { new Guid(parentId) }; + query.ItemIds = new[] { parentId.Value }; } } diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 83b3597665..6295dfc05d 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -45,13 +45,13 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public async Task<ActionResult<PackageInfo>> GetPackageInfo( [FromRoute, Required] string name, - [FromQuery] string? assemblyGuid) + [FromQuery] Guid? assemblyGuid) { var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); var result = _installationManager.FilterPackages( packages, name, - string.IsNullOrEmpty(assemblyGuid) ? default : Guid.Parse(assemblyGuid)) + assemblyGuid ?? default) .FirstOrDefault(); if (result == null) @@ -92,7 +92,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] public async Task<ActionResult> InstallPackage( [FromRoute, Required] string name, - [FromQuery] string? assemblyGuid, + [FromQuery] Guid? assemblyGuid, [FromQuery] string? version, [FromQuery] string? repositoryUrl) { @@ -106,7 +106,7 @@ namespace Jellyfin.Api.Controllers var package = _installationManager.GetCompatibleVersions( packages, name, - string.IsNullOrEmpty(assemblyGuid) ? Guid.Empty : Guid.Parse(assemblyGuid), + assemblyGuid ?? Guid.Empty, specificVersion: string.IsNullOrEmpty(version) ? null : Version.Parse(version)) .FirstOrDefault(); diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index aaad36551c..17e631197c 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -79,7 +79,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludePersonTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes, - [FromQuery] string? appearsInItemId, + [FromQuery] Guid? appearsInItemId, [FromQuery] Guid? userId, [FromQuery] bool? enableImages = true) { @@ -102,7 +102,7 @@ namespace Jellyfin.Api.Controllers NameContains = searchTerm, User = user, IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite, - AppearsInItemId = string.IsNullOrEmpty(appearsInItemId) ? Guid.Empty : Guid.Parse(appearsInItemId), + AppearsInItemId = appearsInItemId ?? Guid.Empty, Limit = limit ?? 0 }); diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs index 076fe58f11..08255ff8f6 100644 --- a/Jellyfin.Api/Controllers/SearchController.cs +++ b/Jellyfin.Api/Controllers/SearchController.cs @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery] bool? isMovie, [FromQuery] bool? isSeries, [FromQuery] bool? isNews, diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index 5090bf1dee..bb54c59f69 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -71,7 +71,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? searchTerm, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -109,15 +109,15 @@ namespace Jellyfin.Api.Controllers EnableTotalRecordCount = enableTotalRecordCount }; - if (!string.IsNullOrWhiteSpace(parentId)) + if (parentId.HasValue) { if (parentItem is Folder) { - query.AncestorIds = new[] { new Guid(parentId) }; + query.AncestorIds = new[] { parentId.Value }; } else { - query.ItemIds = new[] { new Guid(parentId) }; + query.ItemIds = new[] { parentId.Value }; } } diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 5b71fed5a0..8e9ece14f8 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -145,7 +145,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? recursive, [FromQuery] string? searchTerm, [FromQuery] string? sortOrder, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 57b056f50b..03fd1846d7 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -76,7 +76,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] string? seriesId, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -132,7 +132,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery] bool? enableImges, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -144,7 +144,7 @@ namespace Jellyfin.Api.Controllers var minPremiereDate = DateTime.Now.Date.ToUniversalTime().AddDays(-1); - var parentIdGuid = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId); + var parentIdGuid = parentId ?? Guid.Empty; var options = new DtoOptions { Fields = fields } .AddClientFields(Request) @@ -194,14 +194,14 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult<QueryResult<BaseItemDto>> GetEpisodes( - [FromRoute, Required] string seriesId, + [FromRoute, Required] Guid seriesId, [FromQuery] Guid? userId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] int? season, - [FromQuery] string? seasonId, + [FromQuery] Guid? seasonId, [FromQuery] bool? isMissing, [FromQuery] string? adjacentTo, - [FromQuery] string? startItemId, + [FromQuery] Guid? startItemId, [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] bool? enableImages, @@ -220,9 +220,9 @@ namespace Jellyfin.Api.Controllers .AddClientFields(Request) .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes!); - if (!string.IsNullOrWhiteSpace(seasonId)) // Season id was supplied. Get episodes by season id. + if (seasonId.HasValue) // Season id was supplied. Get episodes by season id. { - var item = _libraryManager.GetItemById(new Guid(seasonId)); + var item = _libraryManager.GetItemById(seasonId.Value); if (!(item is Season seasonItem)) { return NotFound("No season exists with Id " + seasonId); @@ -264,10 +264,10 @@ namespace Jellyfin.Api.Controllers .ToList(); } - if (!string.IsNullOrWhiteSpace(startItemId)) + if (startItemId.HasValue) { episodes = episodes - .SkipWhile(i => !string.Equals(i.Id.ToString("N", CultureInfo.InvariantCulture), startItemId, StringComparison.OrdinalIgnoreCase)) + .SkipWhile(i => startItemId.Value.Equals(i.Id)) .ToList(); } @@ -316,7 +316,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult<QueryResult<BaseItemDto>> GetSeasons( - [FromRoute, Required] string seriesId, + [FromRoute, Required] Guid seriesId, [FromQuery] Guid? userId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery] bool? isSpecialSeason, diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index ec7c3de97f..686162bd14 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -71,7 +71,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? startIndex, [FromQuery] int? limit, [FromQuery] string? sortOrder, - [FromQuery] string? parentId, + [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, @@ -94,11 +94,11 @@ namespace Jellyfin.Api.Controllers if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.GetUserRootFolder() : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); } else { - parentItem = string.IsNullOrEmpty(parentId) ? _libraryManager.RootFolder : _libraryManager.GetItemById(parentId); + parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } IList<BaseItem> items; diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs index 9a9d22d33d..ddae7dbd3e 100644 --- a/MediaBrowser.Controller/Channels/IChannelManager.cs +++ b/MediaBrowser.Controller/Channels/IChannelManager.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.Channels /// </summary> /// <param name="id">The identifier.</param> /// <returns>ChannelFeatures.</returns> - ChannelFeatures GetChannelFeatures(string id); + ChannelFeatures GetChannelFeatures(Guid? id); /// <summary> /// Gets all channel features. diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 601ca35360..24b101694d 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -574,5 +574,7 @@ namespace MediaBrowser.Controller.Library void RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason); BaseItem GetParentItem(string parentId, Guid? userId); + + BaseItem GetParentItem(Guid? parentId, Guid? userId); } } diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index ee13ffc168..4ad336d333 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -18,7 +18,7 @@ namespace MediaBrowser.Model.Querying /// Gets or sets the parent identifier. /// </summary> /// <value>The parent identifier.</value> - public string ParentId { get; set; } + public Guid? ParentId { get; set; } /// <summary> /// Gets or sets the series id. diff --git a/MediaBrowser.Model/Search/SearchQuery.cs b/MediaBrowser.Model/Search/SearchQuery.cs index 01ad319a43..ce60062cd3 100644 --- a/MediaBrowser.Model/Search/SearchQuery.cs +++ b/MediaBrowser.Model/Search/SearchQuery.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Model.Search public string[] ExcludeItemTypes { get; set; } - public string ParentId { get; set; } + public Guid? ParentId { get; set; } public bool? IsMovie { get; set; } From 821ad7999207faf273204500c8c1dcb73f9c3c83 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 11:09:01 -0700 Subject: [PATCH 0597/1930] fix spacing --- Emby.Server.Implementations/Channels/ChannelManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index b8692f0e50..57684a4298 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -538,8 +538,8 @@ namespace Emby.Server.Implementations.Channels return _libraryManager.GetItemIds( new InternalItemsQuery { - IncludeItemTypes = new[] {nameof(Channel)}, - OrderBy = new[] {(ItemSortBy.SortName, SortOrder.Ascending)} + IncludeItemTypes = new[] { nameof(Channel) }, + OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) } }).Select(i => GetChannelFeatures(i)).ToArray(); } From 2055d49701a641726a8574460a3e1db6958d693b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 11:10:56 -0700 Subject: [PATCH 0598/1930] fix inverted condition --- Emby.Server.Implementations/Library/SearchEngine.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 6cb683854d..1d9529dff4 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations.Library ExcludeItemTypes = excludeItemTypes.ToArray(), IncludeItemTypes = includeItemTypes.ToArray(), Limit = query.Limit, - IncludeItemsByName = query.ParentId.HasValue, + IncludeItemsByName = !query.ParentId.HasValue, ParentId = query.ParentId ?? Guid.Empty, OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }, Recursive = true, From 7ba9ba4780d9ce3a17ff8218d45e46638407e3c7 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Tue, 1 Dec 2020 19:26:51 +0100 Subject: [PATCH 0599/1930] Fix typo --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a079d76ef0..35fc12d554 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -192,7 +192,7 @@ namespace Emby.Server.Implementations.TV Func<Episode> getEpisode = () => { - var nextEpsiode = _libraryManager.GetItemList(new InternalItemsQuery(user) + var nextEpisode = _libraryManager.GetItemList(new InternalItemsQuery(user) { AncestorWithPresentationUniqueKey = null, SeriesPresentationUniqueKey = seriesKey, @@ -206,14 +206,14 @@ namespace Emby.Server.Implementations.TV DtoOptions = dtoOptions }).Cast<Episode>().FirstOrDefault(); - var userData = _userDataManager.GetUserData(user, nextEpsiode); + var userData = _userDataManager.GetUserData(user, nextEpisode); if (userData.PlaybackPositionTicks > 0) { return null; } - return nextEpsiode; + return nextEpisode; }; if (lastWatchedEpisode != null) From 371092cf62f423fe62eb72f6c3d450966dc49b7d Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Tue, 1 Dec 2020 19:33:18 +0100 Subject: [PATCH 0600/1930] Fix possible nullref --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 35fc12d554..4dff8e252d 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -206,11 +206,13 @@ namespace Emby.Server.Implementations.TV DtoOptions = dtoOptions }).Cast<Episode>().FirstOrDefault(); - var userData = _userDataManager.GetUserData(user, nextEpisode); + if (!(nextEpisode is null)) { + var userData = _userDataManager.GetUserData(user, nextEpisode); - if (userData.PlaybackPositionTicks > 0) - { - return null; + if (userData.PlaybackPositionTicks > 0) + { + return null; + } } return nextEpisode; From f48e47be5fcd5d51a4001caa05f429cf92b4a8ed Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 12:10:11 -0700 Subject: [PATCH 0601/1930] Split nested conditional --- Jellyfin.Api/Controllers/FilterController.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 7b3111cffc..521960ae61 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -71,11 +71,19 @@ namespace Jellyfin.Api.Controllers parentItem = null; } - var item = parentId.HasValue - ? parentItem - : user == null - ? _libraryManager.RootFolder - : _libraryManager.GetUserRootFolder(); + BaseItem? item; + if (parentId.HasValue) + { + item = parentItem; + } + else if (user == null) + { + item = _libraryManager.RootFolder; + } + else + { + item = _libraryManager.GetUserRootFolder(); + } var query = new InternalItemsQuery { From 6173534d333b3ab0b17b5bac928d50e8dd0c36a7 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 1 Dec 2020 21:16:36 +0000 Subject: [PATCH 0602/1930] Update Startup.cs Missed a config move --- Jellyfin.Server/Startup.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index f144dd12e5..7f1d332ee9 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -104,7 +104,8 @@ namespace Jellyfin.Server app.UseBaseUrlRedirection(); // Wrap rest of configuration so everything only listens on BaseUrl. - app.Map(_serverConfigurationManager.GetNetworkConfiguration().BaseUrl, mainApp => + var config = _serverConfigurationManager.GetNetworkConfiguration(); + app.Map(config.BaseUrl, mainApp => { if (env.IsDevelopment()) { @@ -122,8 +123,7 @@ namespace Jellyfin.Server mainApp.UseCors(); - if (_serverConfigurationManager.GetNetworkConfiguration().RequireHttps - && _serverApplicationHost.ListenWithHttps) + if (config.RequireHttps && _serverApplicationHost.ListenWithHttps) { mainApp.UseHttpsRedirection(); } From 673d2c0d261bffae1769c3a357cd5f01912afc80 Mon Sep 17 00:00:00 2001 From: Claus Vium <cvium@users.noreply.github.com> Date: Tue, 1 Dec 2020 22:31:55 +0100 Subject: [PATCH 0603/1930] Update Emby.Server.Implementations/TV/TVSeriesManager.cs --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 4dff8e252d..3cfcecbd1e 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -206,7 +206,8 @@ namespace Emby.Server.Implementations.TV DtoOptions = dtoOptions }).Cast<Episode>().FirstOrDefault(); - if (!(nextEpisode is null)) { + if (nextEpisode != null) + { var userData = _userDataManager.GetUserData(user, nextEpisode); if (userData.PlaybackPositionTicks > 0) From cd459c51f3d8a6a46a802759df1620ec43e5d2ae Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 14:47:42 -0700 Subject: [PATCH 0604/1930] Return NoResult only when request doesn't have a token. --- .../HttpServer/Security/AuthService.cs | 9 ++++++++- .../HttpServer/Security/AuthorizationContext.cs | 4 +++- Jellyfin.Api/Auth/CustomAuthenticationHandler.cs | 5 +---- MediaBrowser.Controller/Net/AuthorizationInfo.cs | 5 +++++ 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index df7a034e8f..4a0fc8239e 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,5 +1,6 @@ #pragma warning disable CS1591 +using System; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; @@ -20,9 +21,15 @@ namespace Emby.Server.Implementations.HttpServer.Security public AuthorizationInfo Authenticate(HttpRequest request) { var auth = _authorizationContext.GetAuthorizationInfo(request); + + if (!auth.HasToken) + { + throw new AuthenticationException("Request does not contain a token."); + } + if (!auth.IsAuthenticated) { - throw new AuthenticationException("Invalid token."); + throw new SecurityException("Invalid token."); } if (auth.User?.HasPermission(PermissionKind.IsDisabled) ?? false) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index fdf2e3908a..d62e2eefe4 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -102,7 +102,8 @@ namespace Emby.Server.Implementations.HttpServer.Security DeviceId = deviceId, Version = version, Token = token, - IsAuthenticated = false + IsAuthenticated = false, + HasToken = false }; if (string.IsNullOrWhiteSpace(token)) @@ -111,6 +112,7 @@ namespace Emby.Server.Implementations.HttpServer.Security return authInfo; } + authInfo.HasToken = true; var result = _authRepo.Get(new AuthenticationInfoQuery { AccessToken = token diff --git a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs index f98d5c11ae..c56233794a 100644 --- a/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs +++ b/Jellyfin.Api/Auth/CustomAuthenticationHandler.cs @@ -1,5 +1,4 @@ using System.Globalization; -using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; @@ -8,7 +7,6 @@ using Jellyfin.Data.Enums; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -79,8 +77,7 @@ namespace Jellyfin.Api.Auth } catch (SecurityException ex) { - _logger.LogDebug(ex, "Error authenticating with {Handler}", nameof(CustomAuthenticationHandler)); - return Task.FromResult(AuthenticateResult.NoResult()); + return Task.FromResult(AuthenticateResult.Fail(ex)); } } } diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs index 0194c596f1..93573e08e2 100644 --- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs +++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs @@ -58,5 +58,10 @@ namespace MediaBrowser.Controller.Net /// Gets or sets a value indicating whether the token is authenticated. /// </summary> public bool IsAuthenticated { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the request has a token. + /// </summary> + public bool HasToken { get; set; } } } From b5a7a74e897539a4f5389faca93bdfe5bfd5b4d5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 16:16:17 -0700 Subject: [PATCH 0605/1930] Use GetParentItem where applicable --- .../Library/LibraryManager.cs | 13 ++++--------- Jellyfin.Api/Controllers/ArtistsController.cs | 14 ++------------ Jellyfin.Api/Controllers/ItemsController.cs | 8 +------- Jellyfin.Api/Controllers/YearsController.cs | 7 +------ 4 files changed, 8 insertions(+), 34 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 0c1018499a..5b926b0f4f 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2462,19 +2462,14 @@ namespace Emby.Server.Implementations.Library public BaseItem GetParentItem(string parentId, Guid? userId) { - if (!string.IsNullOrEmpty(parentId)) + if (string.IsNullOrEmpty(parentId)) { - return GetItemById(new Guid(parentId)); + return GetParentItem((Guid?)null, userId); } - if (userId.HasValue && userId != Guid.Empty) - { - return GetUserRootFolder(); - } - - return RootFolder; + return GetParentItem(new Guid(parentId), userId); } - + public BaseItem GetParentItem(Guid? parentId, Guid? userId) { if (parentId.HasValue) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index cdac009d4b..fed7ed3e5a 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -118,16 +118,11 @@ namespace Jellyfin.Api.Controllers .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); User? user = null; - BaseItem parentItem; + BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId); if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); - } - else - { - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } var query = new InternalItemsQuery(user) @@ -322,16 +317,11 @@ namespace Jellyfin.Api.Controllers .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); User? user = null; - BaseItem parentItem; + BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId); if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); - } - else - { - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } var query = new InternalItemsQuery(user) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index a05c0f534a..7e9035f80f 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -239,14 +239,8 @@ namespace Jellyfin.Api.Controllers parentId = null; } - BaseItem? item = null; + var item = _libraryManager.GetParentItem(parentId, userId); QueryResult<BaseItem> result; - if (parentId.HasValue) - { - item = _libraryManager.GetItemById(parentId.Value); - } - - item ??= _libraryManager.GetUserRootFolder(); if (!(item is Folder folder)) { diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 686162bd14..48c639b08d 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -89,16 +89,11 @@ namespace Jellyfin.Api.Controllers .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); User? user = null; - BaseItem parentItem; + BaseItem parentItem = _libraryManager.GetParentItem(parentId, userId); if (userId.HasValue && !userId.Equals(Guid.Empty)) { user = _userManager.GetUserById(userId.Value); - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.GetUserRootFolder(); - } - else - { - parentItem = parentId.HasValue ? _libraryManager.GetItemById(parentId.Value) : _libraryManager.RootFolder; } IList<BaseItem> items; From 7b5285feacb278ce1d23b08c6a55b7df78126d40 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Wed, 2 Dec 2020 08:22:07 +0800 Subject: [PATCH 0606/1930] Apply suggestions from code review Co-authored-by: BaronGreenback <jimcartlidge@yahoo.co.uk> --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index be63a18e4a..bfc09cc976 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -585,7 +585,7 @@ namespace MediaBrowser.MediaEncoding.Encoder var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; - var enableHdrExtraction = allowTonemap && videoStream != null && !string.IsNullOrEmpty(videoStream.VideoRange) && string.Equals(videoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase); + var enableHdrExtraction = allowTonemap && string.Equals(videoStream?.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase); if (enableHdrExtraction) { string tonemapFilters = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p"; From 589625a3493e15c33d8233c345e777fb08decbdf Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 1 Dec 2020 17:36:36 -0700 Subject: [PATCH 0607/1930] Don't die if folder doesn't have id --- .../Migrations/Routines/RemoveDownloadImagesInAdvance.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs index 42b87ec5f5..9137ea234e 100644 --- a/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs +++ b/Jellyfin.Server/Migrations/Routines/RemoveDownloadImagesInAdvance.cs @@ -35,8 +35,14 @@ namespace Jellyfin.Server.Migrations.Routines _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries"); foreach (var virtualFolder in virtualFolders) { + // Some virtual folders don't have a proper item id. + if (!Guid.TryParse(virtualFolder.ItemId, out var folderId)) + { + continue; + } + var libraryOptions = virtualFolder.LibraryOptions; - var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(virtualFolder.ItemId); + var collectionFolder = (CollectionFolder)_libraryManager.GetItemById(folderId); // The property no longer exists in LibraryOptions, so we just re-save the options to get old data removed. collectionFolder.UpdateLibraryOptions(libraryOptions); _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name); From 09b1e571f4e4dad19495e8873a5bc712a3bf9b7c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 2 Dec 2020 07:11:42 -0700 Subject: [PATCH 0608/1930] Apply suggestions from review --- Jellyfin.Api/Controllers/FilterController.cs | 40 ++++++-------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 521960ae61..1c0f1c1dfe 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -54,35 +54,18 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes) { - var parentItem = parentId.HasValue - ? _libraryManager.GetItemById(parentId.Value) - : null; - var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; - if (includeItemTypes.Length == 1 - && (string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) + BaseItem? item = null; + if (includeItemTypes.Length != 1 + || !(string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) + || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) { - parentItem = null; - } - - BaseItem? item; - if (parentId.HasValue) - { - item = parentItem; - } - else if (user == null) - { - item = _libraryManager.RootFolder; - } - else - { - item = _libraryManager.GetUserRootFolder(); + item = _libraryManager.GetParentItem(parentId, user?.Id); } var query = new InternalItemsQuery @@ -158,14 +141,11 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isSeries, [FromQuery] bool? recursive) { - var parentItem = parentId.HasValue - ? _libraryManager.GetItemById(parentId.Value) - : null; - var user = userId.HasValue && !userId.Equals(Guid.Empty) ? _userManager.GetUserById(userId.Value) : null; + BaseItem? parentItem = null; if (includeItemTypes.Length == 1 && (string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) @@ -174,6 +154,10 @@ namespace Jellyfin.Api.Controllers { parentItem = null; } + else if (parentId.HasValue) + { + parentItem = _libraryManager.GetItemById(parentId.Value); + } var filters = new QueryFilters(); var genreQuery = new InternalItemsQuery(user) From 5bfc5b916640b82023799b079b79a3b77f00fc5f Mon Sep 17 00:00:00 2001 From: Fernando <ferferga.fer@gmail.com> Date: Wed, 2 Dec 2020 11:30:45 +0000 Subject: [PATCH 0609/1930] Translated using Weblate (Spanish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es/ --- Emby.Server.Implementations/Localization/Core/es.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es.json b/Emby.Server.Implementations/Localization/Core/es.json index fe674cf366..16fde325f3 100644 --- a/Emby.Server.Implementations/Localization/Core/es.json +++ b/Emby.Server.Implementations/Localization/Core/es.json @@ -70,7 +70,7 @@ "ScheduledTaskFailedWithName": "{0} falló", "ScheduledTaskStartedWithName": "{0} iniciada", "ServerNameNeedsToBeRestarted": "{0} necesita ser reiniciado", - "Shows": "Mostrar", + "Shows": "Series de Televisión", "Songs": "Canciones", "StartupEmbyServerIsLoading": "Jellyfin Server se está cargando. Vuelve a intentarlo en breve.", "SubtitleDownloadFailureForItem": "Error al descargar subtítulos para {0}", From e4fd61411f102abdd4aa5b6df67c9b18c103cb28 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Wed, 2 Dec 2020 15:38:52 +0100 Subject: [PATCH 0610/1930] Minor improvements --- Emby.Dlna/ContentDirectory/ControlHandler.cs | 1 - .../ServiceActionListBuilder.cs | 1 - Emby.Dlna/PlayTo/Device.cs | 6 +-- Emby.Dlna/PlayTo/PlayToController.cs | 47 +++++++------------ Emby.Dlna/PlayTo/PlayToManager.cs | 7 ++- Emby.Dlna/PlayTo/PlaylistItemFactory.cs | 4 +- Emby.Dlna/PlayTo/SsdpHttpClient.cs | 3 +- Emby.Dlna/PlayTo/TransportCommands.cs | 16 +++---- .../ApplicationHost.cs | 10 +--- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 3 +- .../LiveTv/TunerHosts/M3uParser.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 3 +- .../Subtitles/SsaParser.cs | 16 +++---- MediaBrowser.Model/Dlna/ContainerProfile.cs | 2 +- .../MediaInfo/FFProbeProvider.cs | 2 +- 15 files changed, 48 insertions(+), 75 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index b93651746b..27f1fdabad 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1681,7 +1681,6 @@ namespace Emby.Dlna.ContentDirectory private ServerItem GetItemFromObjectId(string id) { return DidlBuilder.IsIdRoot(id) - ? new ServerItem(_libraryManager.GetUserRootFolder()) : ParseItemId(id); } diff --git a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs index 1dc9c79c14..56788ae223 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ServiceActionListBuilder.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using Emby.Dlna.Common; -using MediaBrowser.Model.Dlna; namespace Emby.Dlna.MediaReceiverRegistrar { diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index f8ff03076a..938ce5fbf0 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -12,8 +12,6 @@ using System.Xml; using System.Xml.Linq; using Emby.Dlna.Common; using Emby.Dlna.Ssdp; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; using Microsoft.Extensions.Logging; namespace Emby.Dlna.PlayTo @@ -345,7 +343,7 @@ namespace Emby.Dlna.PlayTo RestartTimer(true); } - private string CreateDidlMeta(string value) + private static string CreateDidlMeta(string value) { if (string.IsNullOrEmpty(value)) { @@ -962,7 +960,7 @@ namespace Emby.Dlna.PlayTo url = "/dmr/" + url; } - if (!url.StartsWith("/", StringComparison.Ordinal)) + if (!url.StartsWith('/')) { url = "/" + url; } diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 3907b2a396..b7cd91a5c4 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using Emby.Dlna.Didl; using Jellyfin.Data.Entities; using Jellyfin.Data.Events; -using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; @@ -41,7 +40,6 @@ namespace Emby.Dlna.PlayTo private readonly IUserDataManager _userDataManager; private readonly ILocalizationManager _localization; private readonly IMediaSourceManager _mediaSourceManager; - private readonly IConfigurationManager _config; private readonly IMediaEncoder _mediaEncoder; private readonly IDeviceDiscovery _deviceDiscovery; @@ -68,7 +66,6 @@ namespace Emby.Dlna.PlayTo IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager, - IConfigurationManager config, IMediaEncoder mediaEncoder) { _session = session; @@ -84,7 +81,6 @@ namespace Emby.Dlna.PlayTo _userDataManager = userDataManager; _localization = localization; _mediaSourceManager = mediaSourceManager; - _config = config; _mediaEncoder = mediaEncoder; } @@ -337,25 +333,17 @@ namespace Emby.Dlna.PlayTo } var startIndex = command.StartIndex ?? 0; + int len = items.Count - startIndex; if (startIndex > 0) { - items = items.GetRange(startIndex, items.Count - startIndex); + items = items.GetRange(startIndex, len); } - var playlist = new List<PlaylistItem>(); - var isFirst = true; - - foreach (var item in items) + var playlist = new PlaylistItem[len]; + playlist[0] = CreatePlaylistItem(items[0], user, command.StartPositionTicks.Value, command.MediaSourceId, command.AudioStreamIndex, command.SubtitleStreamIndex); + for (int i = 1; i < len; i++) { - if (isFirst && command.StartPositionTicks.HasValue) - { - playlist.Add(CreatePlaylistItem(item, user, command.StartPositionTicks.Value, command.MediaSourceId, command.AudioStreamIndex, command.SubtitleStreamIndex)); - isFirst = false; - } - else - { - playlist.Add(CreatePlaylistItem(item, user, 0, null, null, null)); - } + playlist[i] = CreatePlaylistItem(items[i], user, 0, null, null, null); } _logger.LogDebug("{0} - Playlist created", _session.DeviceName); @@ -468,8 +456,8 @@ namespace Emby.Dlna.PlayTo _dlnaManager.GetDefaultProfile(); var mediaSources = item is IHasMediaSources - ? _mediaSourceManager.GetStaticMediaSources(item, true, user) - : new List<MediaSourceInfo>(); + ? _mediaSourceManager.GetStaticMediaSources(item, true, user).ToArray() + : Array.Empty<MediaSourceInfo>(); var playlistItem = GetPlaylistItem(item, mediaSources, profile, _session.DeviceId, mediaSourceId, audioStreamIndex, subtitleStreamIndex); playlistItem.StreamInfo.StartPositionTicks = startPostionTicks; @@ -548,7 +536,7 @@ namespace Emby.Dlna.PlayTo return null; } - private PlaylistItem GetPlaylistItem(BaseItem item, List<MediaSourceInfo> mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) + private PlaylistItem GetPlaylistItem(BaseItem item, MediaSourceInfo[] mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex) { if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase)) { @@ -557,7 +545,7 @@ namespace Emby.Dlna.PlayTo StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions { ItemId = item.Id, - MediaSources = mediaSources.ToArray(), + MediaSources = mediaSources, Profile = profile, DeviceId = deviceId, MaxBitrate = profile.MaxStreamingBitrate, @@ -577,7 +565,7 @@ namespace Emby.Dlna.PlayTo StreamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions { ItemId = item.Id, - MediaSources = mediaSources.ToArray(), + MediaSources = mediaSources, Profile = profile, DeviceId = deviceId, MaxBitrate = profile.MaxStreamingBitrate, @@ -590,7 +578,7 @@ namespace Emby.Dlna.PlayTo if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase)) { - return new PlaylistItemFactory().Create((Photo)item, profile); + return PlaylistItemFactory.Create((Photo)item, profile); } throw new ArgumentException("Unrecognized item type."); @@ -774,13 +762,14 @@ namespace Emby.Dlna.PlayTo private async Task SeekAfterTransportChange(long positionTicks, CancellationToken cancellationToken) { - const int maxWait = 15000000; - const int interval = 500; + const int MaxWait = 15000000; + const int Interval = 500; + var currentWait = 0; - while (_device.TransportState != TransportState.Playing && currentWait < maxWait) + while (_device.TransportState != TransportState.Playing && currentWait < MaxWait) { - await Task.Delay(interval).ConfigureAwait(false); - currentWait += interval; + await Task.Delay(Interval).ConfigureAwait(false); + currentWait += Interval; } await _device.Seek(TimeSpan.FromTicks(positionTicks), cancellationToken).ConfigureAwait(false); diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index cb183ce71e..f34332d622 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -90,10 +90,10 @@ namespace Emby.Dlna.PlayTo string location = info.Location.ToString(); // It has to report that it's a media renderer - if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1 && - nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) == -1) + if (!usn.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase) + && !nt.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase)) { - // _logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location); + _logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location); return; } @@ -203,7 +203,6 @@ namespace Emby.Dlna.PlayTo _userDataManager, _localization, _mediaSourceManager, - _config, _mediaEncoder); sessionInfo.AddController(controller); diff --git a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs index bedc8b9ad3..e28840a896 100644 --- a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs +++ b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs @@ -8,9 +8,9 @@ using MediaBrowser.Model.Session; namespace Emby.Dlna.PlayTo { - public class PlaylistItemFactory + public static class PlaylistItemFactory { - public PlaylistItem Create(Photo item, DeviceProfile profile) + public static PlaylistItem Create(Photo item, DeviceProfile profile) { var playlistItem = new PlaylistItem { diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index f4d7937907..557bc69a73 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using System.IO; using System.Net.Http; -using System.Net.Http.Headers; using System.Net.Mime; using System.Text; using System.Threading; @@ -60,7 +59,7 @@ namespace Emby.Dlna.PlayTo return serviceUrl; } - if (!serviceUrl.StartsWith("/", StringComparison.Ordinal)) + if (!serviceUrl.StartsWith('/')) { serviceUrl = "/" + serviceUrl; } diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index fda17a8b41..0865968ad1 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -78,7 +78,7 @@ namespace Emby.Dlna.PlayTo private static StateVariable FromXml(XElement container) { - var allowedValues = new List<string>(); + var allowedValues = Array.Empty<string>(); var element = container.Descendants(UPnpNamespaces.Svc + "allowedValueList") .FirstOrDefault(); @@ -86,14 +86,14 @@ namespace Emby.Dlna.PlayTo { var values = element.Descendants(UPnpNamespaces.Svc + "allowedValue"); - allowedValues.AddRange(values.Select(child => child.Value)); + allowedValues = values.Select(child => child.Value).ToArray(); } return new StateVariable { Name = container.GetValue(UPnpNamespaces.Svc + "name"), DataType = container.GetValue(UPnpNamespaces.Svc + "dataType"), - AllowedValues = allowedValues.ToArray() + AllowedValues = allowedValues }; } @@ -103,12 +103,12 @@ namespace Emby.Dlna.PlayTo foreach (var arg in action.ArgumentList) { - if (arg.Direction == "out") + if (string.Equals(arg.Direction, "out", StringComparison.Ordinal)) { continue; } - if (arg.Name == "InstanceID") + if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal)) { stateString += BuildArgumentXml(arg, "0"); } @@ -127,12 +127,12 @@ namespace Emby.Dlna.PlayTo foreach (var arg in action.ArgumentList) { - if (arg.Direction == "out") + if (string.Equals(arg.Direction, "out", StringComparison.Ordinal)) { continue; } - if (arg.Name == "InstanceID") + if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal)) { stateString += BuildArgumentXml(arg, "0"); } @@ -151,7 +151,7 @@ namespace Emby.Dlna.PlayTo foreach (var arg in action.ArgumentList) { - if (arg.Name == "InstanceID") + if (string.Equals(arg.Name, "InstanceID", StringComparison.Ordinal)) { stateString += BuildArgumentXml(arg, "0"); } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 30ccaf8de4..5498f5a10f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,21 +1,18 @@ #pragma warning disable CS1591 using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; -using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Xml.Serialization; using Emby.Dlna; using Emby.Dlna.Main; using Emby.Dlna.Ssdp; @@ -52,7 +49,6 @@ using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; -using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -85,7 +81,6 @@ using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.TV; using MediaBrowser.LocalMetadata.Savers; using MediaBrowser.MediaEncoding.BdInfo; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Globalization; @@ -100,7 +95,6 @@ using MediaBrowser.Providers.Manager; using MediaBrowser.Providers.Plugins.Tmdb; using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; -using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; @@ -128,7 +122,6 @@ namespace Emby.Server.Implementations private IMediaEncoder _mediaEncoder; private ISessionManager _sessionManager; - private IHttpClientFactory _httpClientFactory; private string[] _urlPrefixes; /// <summary> @@ -661,7 +654,6 @@ namespace Emby.Server.Implementations _mediaEncoder = Resolve<IMediaEncoder>(); _sessionManager = Resolve<ISessionManager>(); - _httpClientFactory = Resolve<IHttpClientFactory>(); ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize(); @@ -1049,7 +1041,7 @@ namespace Emby.Server.Implementations metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; int versionIndex = dir.LastIndexOf('_'); - if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version parsedVersion)) + if (versionIndex != -1 && Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version parsedVersion)) { // Versioned folder. versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir)); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index c0a4d12285..b6444b172a 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -237,8 +237,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun if (!inside) { - buffer[bufferIndex] = let; - bufferIndex++; + buffer[bufferIndex++] = let; } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 1d6c26c130..c82b67b41b 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts extInf = line.Substring(ExtInfPrefix.Length).Trim(); _logger.LogInformation("Found m3u channel: {0}", extInf); } - else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) + else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith('#')) { var channel = GetChannelnfo(extInf, tunerHostId, line); if (string.IsNullOrWhiteSpace(channel.Id)) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 1a5614b7b0..85da927fb4 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -256,7 +256,7 @@ namespace Jellyfin.Networking.Manager } catch (ArgumentException e) { - _logger.LogWarning(e, "Ignoring LAN value {value}.", v); + _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); } } @@ -668,7 +668,6 @@ namespace Jellyfin.Networking.Manager if (address.AddressFamily == AddressFamily.InterNetworkV6) { int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase); - if (i != -1) { str = str.Substring(0, i); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs index a5d6417473..db6b475830 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs @@ -51,7 +51,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { eventsStarted = true; } - else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(";", StringComparison.Ordinal)) + else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(';')) { // skip comment lines } @@ -151,13 +151,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - var p = new SubtitleTrackEvent(); - - p.StartPositionTicks = GetTimeCodeFromString(start); - p.EndPositionTicks = GetTimeCodeFromString(end); - p.Text = GetFormattedText(text); - - trackEvents.Add(p); + trackEvents.Add( + new SubtitleTrackEvent + { + StartPositionTicks = GetTimeCodeFromString(start), + EndPositionTicks = GetTimeCodeFromString(end), + Text = GetFormattedText(text) + }); } catch { diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index 09afa64bbd..56c89d854f 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Model.Dlna public static bool ContainsContainer(string profileContainers, string inputContainer) { var isNegativeList = false; - if (profileContainers != null && profileContainers.StartsWith("-", StringComparison.Ordinal)) + if (profileContainers != null && profileContainers.StartsWith('-')) { isNegativeList = true; profileContainers = profileContainers.Substring(1); diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index 648329757f..4fff57273c 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -203,7 +203,7 @@ namespace MediaBrowser.Providers.MediaInfo { item.ShortcutPath = File.ReadAllLines(item.Path) .Select(NormalizeStrmLine) - .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i) && !i.StartsWith("#", StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i) && !i.StartsWith('#')); } public Task<ItemUpdateType> FetchAudioInfo<T>(T item, MetadataRefreshOptions options, CancellationToken cancellationToken) From 41e127d1d2f82ea879b11a35b92dfb537554193d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 2 Dec 2020 07:42:25 -0700 Subject: [PATCH 0611/1930] Fix null reference when getting filters of an empty library --- Jellyfin.Api/Controllers/FilterController.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 31cb9e2736..0e1af66dcb 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -92,7 +92,12 @@ namespace Jellyfin.Api.Controllers } }; - var itemList = ((Folder)item!).GetItemList(query); + var itemList = ((Folder?)item)?.GetItemList(query); + if (itemList == null) + { + return new QueryFiltersLegacy(); + } + return new QueryFiltersLegacy { Years = itemList.Select(i => i.ProductionYear ?? -1) From 08be7f094a7c001bebb7d9c589b5ce3f1fd2cabe Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 2 Dec 2020 07:55:34 -0700 Subject: [PATCH 0612/1930] Cleaner type checking --- Jellyfin.Api/Controllers/FilterController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 0e1af66dcb..f55f4f5f0d 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -92,12 +92,12 @@ namespace Jellyfin.Api.Controllers } }; - var itemList = ((Folder?)item)?.GetItemList(query); - if (itemList == null) + if (!(item is Folder folder)) { return new QueryFiltersLegacy(); } + var itemList = folder.GetItemList(query); return new QueryFiltersLegacy { Years = itemList.Select(i => i.ProductionYear ?? -1) From 828504e9259a5b08ac9a53e03085c61e2271adc7 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 2 Dec 2020 08:04:08 -0700 Subject: [PATCH 0613/1930] The future is now --- Jellyfin.Api/Controllers/FilterController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index f55f4f5f0d..95c5df9205 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -92,7 +92,7 @@ namespace Jellyfin.Api.Controllers } }; - if (!(item is Folder folder)) + if (item is not Folder folder) { return new QueryFiltersLegacy(); } From 7a729ea8d69b5cea16d7ba4a03748cd8a4caf871 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 2 Dec 2020 14:59:57 -0700 Subject: [PATCH 0614/1930] Move OpenApiSecurityScheme to OperationFilter --- .../ApiServiceCollectionExtensions.cs | 13 +--- .../SecurityRequirementsOperationFilter.cs | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+), 12 deletions(-) create mode 100644 Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index e5b9620f78..618a4e92b4 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -236,18 +236,6 @@ namespace Jellyfin.Server.Extensions Description = "API key header parameter" }); - var securitySchemeRef = new OpenApiSecurityScheme - { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = AuthenticationSchemes.CustomAuthentication }, - }; - - // TODO: Apply this with an operation filter instead of globally - // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements - c.AddSecurityRequirement(new OpenApiSecurityRequirement - { - { securitySchemeRef, Array.Empty<string>() } - }); - // Add all xml doc files to swagger generator. var xmlFiles = Directory.GetFiles( AppContext.BaseDirectory, @@ -277,6 +265,7 @@ namespace Jellyfin.Server.Extensions // TODO - remove when all types are supported in System.Text.Json c.AddSwaggerTypeMappings(); + c.OperationFilter<SecurityRequirementsOperationFilter>(); c.OperationFilter<FileResponseFilter>(); c.DocumentFilter<WebsocketModelFilter>(); }); diff --git a/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs b/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs new file mode 100644 index 0000000000..802662ce2f --- /dev/null +++ b/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Jellyfin.Api.Constants; +using Microsoft.AspNetCore.Authorization; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Jellyfin.Server.Filters +{ + /// <summary> + /// Security requirement operation filter. + /// </summary> + public class SecurityRequirementsOperationFilter : IOperationFilter + { + /// <inheritdoc /> + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var requiredScopes = new List<string>(); + + // Add all method scopes. + foreach (var attribute in context.MethodInfo.GetCustomAttributes(true)) + { + if (attribute is AuthorizeAttribute authorizeAttribute + && authorizeAttribute.Policy != null + && !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal)) + { + requiredScopes.Add(authorizeAttribute.Policy); + } + } + + // Add controller scopes if any. + var controllerAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true); + if (controllerAttributes != null) + { + foreach (var attribute in controllerAttributes) + { + if (attribute is AuthorizeAttribute authorizeAttribute + && authorizeAttribute.Policy != null + && !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal)) + { + requiredScopes.Add(authorizeAttribute.Policy); + } + } + } + + if (requiredScopes.Count != 0) + { + if (!operation.Responses.ContainsKey("401")) + { + operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); + } + + if (!operation.Responses.ContainsKey("403")) + { + operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); + } + + var scheme = new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = AuthenticationSchemes.CustomAuthentication + } + }; + + operation.Security = new List<OpenApiSecurityRequirement> + { + new OpenApiSecurityRequirement + { + [scheme] = requiredScopes + } + }; + } + } + } +} \ No newline at end of file From 949753028198984a5e8c1c244a0640a62eae0ae2 Mon Sep 17 00:00:00 2001 From: Raghd Hamzeh <raghd@rhamzeh.com> Date: Wed, 2 Dec 2020 21:14:37 -0500 Subject: [PATCH 0615/1930] fix: add Palestine to supported countries --- Emby.Server.Implementations/Localization/countries.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Emby.Server.Implementations/Localization/countries.json b/Emby.Server.Implementations/Localization/countries.json index 581e9f8357..b08a3ae798 100644 --- a/Emby.Server.Implementations/Localization/countries.json +++ b/Emby.Server.Implementations/Localization/countries.json @@ -557,6 +557,12 @@ "ThreeLetterISORegionName": "OMN", "TwoLetterISORegionName": "OM" }, + { + "DisplayName": "Palestine", + "Name": "PS", + "ThreeLetterISORegionName": "PSE", + "TwoLetterISORegionName": "PS" + }, { "DisplayName": "Panama", "Name": "PA", From f4edca7c2790207b5be9abb3b49029c9fbe04828 Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Wed, 2 Dec 2020 18:51:53 -0800 Subject: [PATCH 0616/1930] Move MetadataRefreshThrottler to BaseItemManager --- .../BaseItemManager/BaseItemManager.cs | 17 ++++++++- .../BaseItemManager/IBaseItemManager.cs | 9 ++++- MediaBrowser.Controller/Entities/Folder.cs | 35 ++----------------- .../Providers/IProviderManager.cs | 8 +++++ .../Manager/ProviderManager.cs | 20 +++++++++++ 5 files changed, 54 insertions(+), 35 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 67aa7f3383..0c8fa82447 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -1,5 +1,6 @@ -using System; +using System; using System.Linq; +using System.Threading; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -19,8 +20,22 @@ namespace MediaBrowser.Controller.BaseItemManager public BaseItemManager(IServerConfigurationManager serverConfigurationManager) { _serverConfigurationManager = serverConfigurationManager; + + MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => { + var concurrency = _serverConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency; + + if (concurrency <= 0) + { + concurrency = Environment.ProcessorCount; + } + + return new SemaphoreSlim(concurrency); + }); } + /// <inheritdoc /> + public Lazy<SemaphoreSlim> MetadataRefreshThrottler { get; private set; } + /// <inheritdoc /> public bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name) { diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs index ee4d3dcdcc..d5f36dc2e2 100644 --- a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs @@ -1,4 +1,6 @@ -using MediaBrowser.Controller.Entities; +using System; +using System.Threading; +using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Configuration; namespace MediaBrowser.Controller.BaseItemManager @@ -8,6 +10,11 @@ namespace MediaBrowser.Controller.BaseItemManager /// </summary> public interface IBaseItemManager { + /// <summary> + /// Gets the semaphore used to limit the amount of concurrent metadata refreshes. + /// </summary> + Lazy<SemaphoreSlim> MetadataRefreshThrottler { get; } + /// <summary> /// Is metadata fetcher enabled. /// </summary> diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index e41407d7f4..57d04ddfac 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -36,17 +36,6 @@ namespace MediaBrowser.Controller.Entities /// </summary> public class Folder : BaseItem { - private static Lazy<SemaphoreSlim> _metadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => { - var concurrency = ConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency; - - if (concurrency <= 0) - { - concurrency = Environment.ProcessorCount; - } - - return new SemaphoreSlim(concurrency); - }); - public static IUserViewManager UserViewManager { get; set; } /// <summary> @@ -491,7 +480,7 @@ namespace MediaBrowser.Controller.Entities private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken) { // limit the amount of concurrent metadata refreshes - await RunMetadataRefresh( + await ProviderManager.RunMetadataRefresh( async () => { var series = container as Series; @@ -518,7 +507,7 @@ namespace MediaBrowser.Controller.Entities if (refreshOptions.RefreshItem(child)) { // limit the amount of concurrent metadata refreshes - await RunMetadataRefresh( + await ProviderManager.RunMetadataRefresh( async () => await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); } @@ -1252,26 +1241,6 @@ namespace MediaBrowser.Controller.Entities return true; } - /// <summary> - /// Runs multiple metadata refreshes concurrently. - /// </summary> - /// <param name="action">The action to run.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns> - private static async Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken) - { - await _metadataRefreshThrottler.Value.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - await action().ConfigureAwait(false); - } - finally - { - _metadataRefreshThrottler.Value.Release(); - } - } - public List<BaseItem> GetChildren(User user, bool includeLinkedChildren) { if (user == null) diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 996ec27c09..0a4967223f 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -45,6 +45,14 @@ namespace MediaBrowser.Controller.Providers /// <returns>Task.</returns> Task<ItemUpdateType> RefreshSingleItem(BaseItem item, MetadataRefreshOptions options, CancellationToken cancellationToken); + /// <summary> + /// Runs multiple metadata refreshes concurrently. + /// </summary> + /// <param name="action">The action to run.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns> + Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken); + /// <summary> /// Saves the image. /// </summary> diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index e7e44876db..fbf4bc68b4 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -1167,6 +1167,26 @@ namespace MediaBrowser.Providers.Manager return RefreshItem(item, options, cancellationToken); } + /// <summary> + /// Runs multiple metadata refreshes concurrently. + /// </summary> + /// <param name="action">The action to run.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns> + public async Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken) + { + await _baseItemManager.MetadataRefreshThrottler.Value.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + await action().ConfigureAwait(false); + } + finally + { + _baseItemManager.MetadataRefreshThrottler.Value.Release(); + } + } + /// <inheritdoc/> public void Dispose() { From 26a05e69748285e2cb2a7647496e44e6c70a0d97 Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Wed, 2 Dec 2020 23:07:51 -0800 Subject: [PATCH 0617/1930] Handle config updates --- .../BaseItemManager/BaseItemManager.cs | 42 +++++++++++++++---- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 0c8fa82447..4981b09273 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Threading; +using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -13,6 +14,8 @@ namespace MediaBrowser.Controller.BaseItemManager { private readonly IServerConfigurationManager _serverConfigurationManager; + private int _metadataRefreshConcurrency = 0; + /// <summary> /// Initializes a new instance of the <see cref="BaseItemManager"/> class. /// </summary> @@ -21,16 +24,18 @@ namespace MediaBrowser.Controller.BaseItemManager { _serverConfigurationManager = serverConfigurationManager; - MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => { - var concurrency = _serverConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency; + _metadataRefreshConcurrency = GetMetadataRefreshConcurrency(); + SetupMetadataThrottler(); - if (concurrency <= 0) + _serverConfigurationManager.ConfigurationUpdated += (object sender, EventArgs e) => + { + int newMetadataRefreshConcurrency = GetMetadataRefreshConcurrency(); + if (_metadataRefreshConcurrency != newMetadataRefreshConcurrency) { - concurrency = Environment.ProcessorCount; + _metadataRefreshConcurrency = newMetadataRefreshConcurrency; + SetupMetadataThrottler(); } - - return new SemaphoreSlim(concurrency); - }); + }; } /// <inheritdoc /> @@ -97,5 +102,28 @@ namespace MediaBrowser.Controller.BaseItemManager return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); } + + /// <summary> + /// Creates the metadata refresh throttler. + /// </summary> + private void SetupMetadataThrottler() + { + MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(_metadataRefreshConcurrency)); + } + + /// <summary> + /// Returns the metadata refresh concurrency. + /// </summary> + private int GetMetadataRefreshConcurrency() + { + var concurrency = _serverConfigurationManager.Configuration.LibraryMetadataRefreshConcurrency; + + if (concurrency <= 0) + { + concurrency = Environment.ProcessorCount; + } + + return concurrency; + } } } From 74f211960a5df659d51b4e836ee784497829a3ed Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Wed, 2 Dec 2020 23:14:18 -0800 Subject: [PATCH 0618/1930] only recreate the lazy when needed --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 4981b09273..7aec3b3228 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -108,7 +108,10 @@ namespace MediaBrowser.Controller.BaseItemManager /// </summary> private void SetupMetadataThrottler() { - MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(_metadataRefreshConcurrency)); + if (MetadataRefreshThrottler == null || MetadataRefreshThrottler.IsValueCreated) + { + MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(_metadataRefreshConcurrency)); + } } /// <summary> From 2b6b2cbf31d44c03e1bf68eff155fc0918df9dfb Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Wed, 2 Dec 2020 23:23:13 -0800 Subject: [PATCH 0619/1930] Remove Lazy --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 7 ++----- .../BaseItemManager/IBaseItemManager.cs | 2 +- MediaBrowser.Providers/Manager/ProviderManager.cs | 7 +++++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 7aec3b3228..c018627b45 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -39,7 +39,7 @@ namespace MediaBrowser.Controller.BaseItemManager } /// <inheritdoc /> - public Lazy<SemaphoreSlim> MetadataRefreshThrottler { get; private set; } + public SemaphoreSlim MetadataRefreshThrottler { get; private set; } /// <inheritdoc /> public bool IsMetadataFetcherEnabled(BaseItem baseItem, LibraryOptions libraryOptions, string name) @@ -108,10 +108,7 @@ namespace MediaBrowser.Controller.BaseItemManager /// </summary> private void SetupMetadataThrottler() { - if (MetadataRefreshThrottler == null || MetadataRefreshThrottler.IsValueCreated) - { - MetadataRefreshThrottler = new Lazy<SemaphoreSlim>(() => new SemaphoreSlim(_metadataRefreshConcurrency)); - } + MetadataRefreshThrottler = new SemaphoreSlim(_metadataRefreshConcurrency); } /// <summary> diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs index d5f36dc2e2..e1f5d05a60 100644 --- a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs @@ -13,7 +13,7 @@ namespace MediaBrowser.Controller.BaseItemManager /// <summary> /// Gets the semaphore used to limit the amount of concurrent metadata refreshes. /// </summary> - Lazy<SemaphoreSlim> MetadataRefreshThrottler { get; } + SemaphoreSlim MetadataRefreshThrottler { get; } /// <summary> /// Is metadata fetcher enabled. diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index fbf4bc68b4..a20c47cf2e 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -1175,7 +1175,10 @@ namespace MediaBrowser.Providers.Manager /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns> public async Task RunMetadataRefresh(Func<Task> action, CancellationToken cancellationToken) { - await _baseItemManager.MetadataRefreshThrottler.Value.WaitAsync(cancellationToken).ConfigureAwait(false); + // create a variable for this since it is possible MetadataRefreshThrottler could change due to a config update during a scan + var metadataRefreshThrottler = _baseItemManager.MetadataRefreshThrottler; + + await metadataRefreshThrottler.WaitAsync(cancellationToken).ConfigureAwait(false); try { @@ -1183,7 +1186,7 @@ namespace MediaBrowser.Providers.Manager } finally { - _baseItemManager.MetadataRefreshThrottler.Value.Release(); + metadataRefreshThrottler.Release(); } } From 7e0ea296c383b9b9cd778bb12834c2a73df3d1ea Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 3 Dec 2020 10:43:44 +0100 Subject: [PATCH 0620/1930] Move request validation to auth policies --- .../SyncPlay/SyncPlayManager.cs | 62 ------------------- .../SyncPlayAccessHandler.cs | 58 +++++++++++++++++ .../SyncPlayAccessRequirement.cs | 33 ++++++++++ Jellyfin.Api/Constants/Policies.cs | 10 +++ .../Controllers/SyncPlayController.cs | 3 +- .../ApiServiceCollectionExtensions.cs | 17 +++++ 6 files changed, 120 insertions(+), 63 deletions(-) create mode 100644 Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs create mode 100644 Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 7e1f24f8c2..0410048c4f 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -102,11 +102,6 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { - if (!IsRequestValid(session, request)) - { - return; - } - // Locking required to access list of groups. lock (_groupsLock) { @@ -132,11 +127,6 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { - if (!IsRequestValid(session, request)) - { - return; - } - var user = _userManager.GetUserById(session.UserId); // Locking required to access list of groups. @@ -190,11 +180,6 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { - if (!IsRequestValid(session, request)) - { - return; - } - // Locking required to access list of groups. lock (_groupsLock) { @@ -230,11 +215,6 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request) { - if (!IsRequestValid(session, request)) - { - return new List<GroupInfoDto>(); - } - var user = _userManager.GetUserById(session.UserId); List<GroupInfoDto> list = new List<GroupInfoDto>(); @@ -260,11 +240,6 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { - if (!IsRequestValid(session, request)) - { - return; - } - IGroupController group; lock (_mapsLock) { @@ -417,42 +392,5 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Session was in wrong group!"); } } - - /// <summary> - /// Checks if a given session is allowed to make a given request. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The request.</param> - /// <returns><c>true</c> if the request is valid, <c>false</c> otherwise. Will return <c>false</c> also when session or request is null.</returns> - private bool IsRequestValid(SessionInfo session, ISyncPlayRequest request) - { - if (session == null || (request == null)) - { - return false; - } - - var user = _userManager.GetUserById(session.UserId); - - if (user.SyncPlayAccess == SyncPlayAccess.None) - { - _logger.LogWarning("Session {SessionId} requested {RequestType} but does not have access to SyncPlay.", session.Id, request.Type); - - // TODO: rename to a more generic error. Next PR will fix this. - var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.JoinGroupDenied, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return false; - } - - if (request.Type.Equals(RequestType.NewGroup) && user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) - { - _logger.LogWarning("Session {SessionId} does not have permission to create groups.", session.Id); - - var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.CreateGroupDenied, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return false; - } - - return true; - } } } diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs new file mode 100644 index 0000000000..2c3294523f --- /dev/null +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs @@ -0,0 +1,58 @@ +using System.Threading.Tasks; +using Jellyfin.Api.Helpers; +using Jellyfin.Data.Enums; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Library; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; + +namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy +{ + /// <summary> + /// Default authorization handler. + /// </summary> + public class SyncPlayAccessHandler : BaseAuthorizationHandler<SyncPlayAccessRequirement> + { + private readonly IUserManager _userManager; + + /// <summary> + /// Initializes a new instance of the <see cref="SyncPlayAccessHandler"/> class. + /// </summary> + /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> + /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param> + /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param> + public SyncPlayAccessHandler( + IUserManager userManager, + INetworkManager networkManager, + IHttpContextAccessor httpContextAccessor) + : base(userManager, networkManager, httpContextAccessor) + { + _userManager = userManager; + } + + /// <inheritdoc /> + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SyncPlayAccessRequirement requirement) + { + if (!ValidateClaims(context.User)) + { + context.Fail(); + return Task.CompletedTask; + } + + var userId = ClaimHelpers.GetUserId(context.User); + var user = _userManager.GetUserById(userId!.Value); + + if ((requirement.RequiredAccess.HasValue && user.SyncPlayAccess == requirement.RequiredAccess) + || (user.SyncPlayAccess == SyncPlayAccess.JoinGroups || user.SyncPlayAccess == SyncPlayAccess.CreateAndJoinGroups)) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + + return Task.CompletedTask; + } + } +} diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs new file mode 100644 index 0000000000..7fcaf69f6e --- /dev/null +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs @@ -0,0 +1,33 @@ +using Jellyfin.Data.Enums; +using Microsoft.AspNetCore.Authorization; + +namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy +{ + /// <summary> + /// The default authorization requirement. + /// </summary> + public class SyncPlayAccessRequirement : IAuthorizationRequirement + { + /// <summary> + /// Initializes a new instance of the <see cref="SyncPlayAccessRequirement"/> class. + /// </summary> + /// <param name="requiredAccess">A value of <see cref="SyncPlayAccess"/>.</param> + public SyncPlayAccessRequirement(SyncPlayAccess requiredAccess) + { + RequiredAccess = requiredAccess; + } + + /// <summary> + /// Initializes a new instance of the <see cref="SyncPlayAccessRequirement"/> class. + /// </summary> + public SyncPlayAccessRequirement() + { + RequiredAccess = null; + } + + /// <summary> + /// Gets the required SyncPlay access. + /// </summary> + public SyncPlayAccess? RequiredAccess { get; } + } +} diff --git a/Jellyfin.Api/Constants/Policies.cs b/Jellyfin.Api/Constants/Policies.cs index 7d77674700..b35ceea1a3 100644 --- a/Jellyfin.Api/Constants/Policies.cs +++ b/Jellyfin.Api/Constants/Policies.cs @@ -49,5 +49,15 @@ namespace Jellyfin.Api.Constants /// Policy name for escaping schedule controls or requiring first time setup. /// </summary> public const string FirstTimeSetupOrIgnoreParentalControl = "FirstTimeSetupOrIgnoreParentalControl"; + + /// <summary> + /// Policy name for requiring access to SyncPlay. + /// </summary> + public const string SyncPlayAccess = "SyncPlayAccess"; + + /// <summary> + /// Policy name for requiring group creation access to SyncPlay. + /// </summary> + public const string SyncPlayCreateGroupAccess = "SyncPlayCreateGroupAccess"; } } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index ed5ea3c8a7..763940c733 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -20,7 +20,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// The sync play controller. /// </summary> - [Authorize(Policy = Policies.DefaultAuthorization)] + [Authorize(Policy = Policies.SyncPlayAccess)] public class SyncPlayController : BaseJellyfinApiController { private readonly ISessionManager _sessionManager; @@ -51,6 +51,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("New")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayCreateGroupAccess)] public ActionResult SyncPlayCreateGroup( [FromBody, Required] NewGroupRequestBody requestData) { diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 6cb88c9f73..cdcc4bb86a 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -15,9 +15,11 @@ using Jellyfin.Api.Auth.IgnoreParentalControlPolicy; using Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy; using Jellyfin.Api.Auth.LocalAccessPolicy; using Jellyfin.Api.Auth.RequiresElevationPolicy; +using Jellyfin.Api.Auth.SyncPlayAccessPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -58,6 +60,7 @@ namespace Jellyfin.Server.Extensions serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessHandler>(); serviceCollection.AddSingleton<IAuthorizationHandler, LocalAccessOrRequiresElevationHandler>(); serviceCollection.AddSingleton<IAuthorizationHandler, RequiresElevationHandler>(); + serviceCollection.AddSingleton<IAuthorizationHandler, SyncPlayAccessHandler>(); return serviceCollection.AddAuthorizationCore(options => { options.AddPolicy( @@ -123,6 +126,20 @@ namespace Jellyfin.Server.Extensions policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); policy.AddRequirements(new RequiresElevationRequirement()); }); + options.AddPolicy( + Policies.SyncPlayAccess, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new SyncPlayAccessRequirement()); + }); + options.AddPolicy( + Policies.SyncPlayCreateGroupAccess, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccess.CreateAndJoinGroups)); + }); }); } From bbe872524d18e356ca7c4b1abf44e3a247decd2b Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 3 Dec 2020 20:12:05 +0800 Subject: [PATCH 0621/1930] optimize load plugin logs --- Emby.Server.Implementations/ApplicationHost.cs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 5498f5a10f..ebba5f02fc 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -774,17 +774,10 @@ namespace Emby.Server.Implementations if (Plugins != null) { - var pluginBuilder = new StringBuilder(); - foreach (var plugin in Plugins) { - pluginBuilder.Append(plugin.Name) - .Append(' ') - .Append(plugin.Version) - .AppendLine(); + Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name.ToString(), plugin.Version.ToString()); } - - Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString()); } _urlPrefixes = GetUrlPrefixes().ToArray(); From d496fd2d482aff50d59cc6534654fc7a29132d78 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Thu, 3 Dec 2020 21:34:25 +0800 Subject: [PATCH 0622/1930] Apply suggestions from code review Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index ebba5f02fc..37d6f9db4f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -776,7 +776,7 @@ namespace Emby.Server.Implementations { foreach (var plugin in Plugins) { - Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name.ToString(), plugin.Version.ToString()); + Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version); } } From ca5c20c9889f2c279f0b9d80ce776ddc8ee31ad1 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 3 Dec 2020 07:34:15 -0700 Subject: [PATCH 0623/1930] Remove IIsoMounter and IsoMounter --- .../ApplicationHost.cs | 4 -- Emby.Server.Implementations/IO/IsoManager.cs | 67 ------------------- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 5 -- .../MediaEncoding/IMediaEncoder.cs | 2 +- .../Encoder/MediaEncoder.cs | 6 +- MediaBrowser.Model/IO/IIsoManager.cs | 35 ---------- MediaBrowser.Model/IO/IIsoMount.cs | 22 ------ MediaBrowser.Model/IO/IIsoMounter.cs | 35 ---------- .../MediaInfo/FFProbeVideoInfo.cs | 2 +- 9 files changed, 4 insertions(+), 174 deletions(-) delete mode 100644 Emby.Server.Implementations/IO/IsoManager.cs delete mode 100644 MediaBrowser.Model/IO/IIsoManager.cs delete mode 100644 MediaBrowser.Model/IO/IIsoMount.cs delete mode 100644 MediaBrowser.Model/IO/IIsoMounter.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 30ccaf8de4..29c93faa62 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -538,8 +538,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(NetManager); - ServiceCollection.AddSingleton<IIsoManager, IsoManager>(); - ServiceCollection.AddSingleton<ITaskManager, TaskManager>(); ServiceCollection.AddSingleton(_xmlSerializer); @@ -820,8 +818,6 @@ namespace Emby.Server.Implementations Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>()); Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>()); - - Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>()); } /// <summary> diff --git a/Emby.Server.Implementations/IO/IsoManager.cs b/Emby.Server.Implementations/IO/IsoManager.cs deleted file mode 100644 index 94e92c2a6a..0000000000 --- a/Emby.Server.Implementations/IO/IsoManager.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.IO; - -namespace Emby.Server.Implementations.IO -{ - /// <summary> - /// Class IsoManager. - /// </summary> - public class IsoManager : IIsoManager - { - /// <summary> - /// The _mounters. - /// </summary> - private readonly List<IIsoMounter> _mounters = new List<IIsoMounter>(); - - /// <summary> - /// Mounts the specified iso path. - /// </summary> - /// <param name="isoPath">The iso path.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns><see creaf="IsoMount" />.</returns> - public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(isoPath)) - { - throw new ArgumentNullException(nameof(isoPath)); - } - - var mounter = _mounters.FirstOrDefault(i => i.CanMount(isoPath)); - - if (mounter == null) - { - throw new ArgumentException( - string.Format( - CultureInfo.InvariantCulture, - "No mounters are able to mount {0}", - isoPath)); - } - - return mounter.Mount(isoPath, cancellationToken); - } - - /// <summary> - /// Determines whether this instance can mount the specified path. - /// </summary> - /// <param name="path">The path.</param> - /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns> - public bool CanMount(string path) - { - return _mounters.Any(i => i.CanMount(path)); - } - - /// <summary> - /// Adds the parts. - /// </summary> - /// <param name="mounters">The mounters.</param> - public void AddParts(IEnumerable<IIsoMounter> mounters) - { - _mounters.AddRange(mounters); - } - } -} diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index bb2265dba9..240d132b15 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -12,7 +12,6 @@ using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using Jellyfin.Data.Enums; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -46,7 +45,6 @@ namespace Jellyfin.Api.Helpers private readonly IAuthorizationContext _authorizationContext; private readonly EncodingHelper _encodingHelper; private readonly IFileSystem _fileSystem; - private readonly IIsoManager _isoManager; private readonly ILogger<TranscodingJobHelper> _logger; private readonly IMediaEncoder _mediaEncoder; private readonly IMediaSourceManager _mediaSourceManager; @@ -64,7 +62,6 @@ namespace Jellyfin.Api.Helpers /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param> /// <param name="authorizationContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param> - /// <param name="isoManager">Instance of the <see cref="IIsoManager"/> interface.</param> /// <param name="subtitleEncoder">Instance of the <see cref="ISubtitleEncoder"/> interface.</param> /// <param name="configuration">Instance of the <see cref="IConfiguration"/> interface.</param> /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param> @@ -76,7 +73,6 @@ namespace Jellyfin.Api.Helpers IServerConfigurationManager serverConfigurationManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, - IIsoManager isoManager, ISubtitleEncoder subtitleEncoder, IConfiguration configuration, ILoggerFactory loggerFactory) @@ -88,7 +84,6 @@ namespace Jellyfin.Api.Helpers _serverConfigurationManager = serverConfigurationManager; _sessionManager = sessionManager; _authorizationContext = authorizationContext; - _isoManager = isoManager; _loggerFactory = loggerFactory; _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index e7f042d2f5..34fe895cc4 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -117,6 +117,6 @@ namespace MediaBrowser.Controller.MediaEncoding void UpdateEncoderPath(string path, string pathType); - IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber); + IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber); } } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 3808942788..b1da9c712d 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -949,16 +949,14 @@ namespace MediaBrowser.MediaEncoding.Encoder } /// <inheritdoc /> - public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber) + public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, uint? titleNumber) { // min size 300 mb const long MinPlayableSize = 314572800; - var root = isoMount != null ? isoMount.MountedPath : path; - // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size // Once we reach a file that is at least the minimum, return all subsequent ones - var allVobs = _fileSystem.GetFiles(root, true) + var allVobs = _fileSystem.GetFiles(path, true) .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase)) .OrderBy(i => i.FullName) .ToList(); diff --git a/MediaBrowser.Model/IO/IIsoManager.cs b/MediaBrowser.Model/IO/IIsoManager.cs deleted file mode 100644 index 299bb0a213..0000000000 --- a/MediaBrowser.Model/IO/IIsoManager.cs +++ /dev/null @@ -1,35 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.IO -{ - public interface IIsoManager - { - /// <summary> - /// Mounts the specified iso path. - /// </summary> - /// <param name="isoPath">The iso path.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>IsoMount.</returns> - /// <exception cref="IOException">Unable to create mount.</exception> - Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken); - - /// <summary> - /// Determines whether this instance can mount the specified path. - /// </summary> - /// <param name="path">The path.</param> - /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns> - bool CanMount(string path); - - /// <summary> - /// Adds the parts. - /// </summary> - /// <param name="mounters">The mounters.</param> - void AddParts(IEnumerable<IIsoMounter> mounters); - } -} diff --git a/MediaBrowser.Model/IO/IIsoMount.cs b/MediaBrowser.Model/IO/IIsoMount.cs deleted file mode 100644 index ea65d976a0..0000000000 --- a/MediaBrowser.Model/IO/IIsoMount.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -namespace MediaBrowser.Model.IO -{ - /// <summary> - /// Interface IIsoMount. - /// </summary> - public interface IIsoMount : IDisposable - { - /// <summary> - /// Gets the iso path. - /// </summary> - /// <value>The iso path.</value> - string IsoPath { get; } - - /// <summary> - /// Gets the mounted path. - /// </summary> - /// <value>The mounted path.</value> - string MountedPath { get; } - } -} diff --git a/MediaBrowser.Model/IO/IIsoMounter.cs b/MediaBrowser.Model/IO/IIsoMounter.cs deleted file mode 100644 index 0d257395a9..0000000000 --- a/MediaBrowser.Model/IO/IIsoMounter.cs +++ /dev/null @@ -1,35 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.IO -{ - public interface IIsoMounter - { - /// <summary> - /// Gets the name. - /// </summary> - /// <value>The name.</value> - string Name { get; } - - /// <summary> - /// Mounts the specified iso path. - /// </summary> - /// <param name="isoPath">The iso path.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>IsoMount.</returns> - /// <exception cref="ArgumentNullException">isoPath</exception> - /// <exception cref="IOException">Unable to create mount.</exception> - Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken); - - /// <summary> - /// Determines whether this instance can mount the specified path. - /// </summary> - /// <param name="path">The path.</param> - /// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns> - bool CanMount(string path); - } -} diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 6d39c091ef..74849a5221 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -619,7 +619,7 @@ namespace MediaBrowser.Providers.MediaInfo item.RunTimeTicks = GetRuntime(primaryTitle); } - return _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, null, titleNumber) + return _mediaEncoder.GetPrimaryPlaylistVobFiles(item.Path, titleNumber) .Select(Path.GetFileName) .ToArray(); } From 389367fec80561548c6d0771242712f675f95319 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Thu, 3 Dec 2020 15:41:34 +0100 Subject: [PATCH 0624/1930] Rename 'track' into 'item' in SyncPlay --- .../Controllers/SyncPlayController.cs | 52 +++++++++---------- .../GroupStates/AbstractGroupState.cs | 4 +- .../SyncPlay/GroupStates/IdleGroupState.cs | 4 +- .../SyncPlay/GroupStates/PausedGroupState.cs | 4 +- .../SyncPlay/GroupStates/PlayingGroupState.cs | 4 +- .../SyncPlay/GroupStates/WaitingGroupState.cs | 12 ++--- .../SyncPlay/IGroupState.cs | 12 ++--- ...roupRequest.cs => NextItemGroupRequest.cs} | 10 ++-- ...Request.cs => PreviousItemGroupRequest.cs} | 10 ++-- .../SyncPlay/PlayQueueUpdateReason.cs | 4 +- .../SyncPlay/PlaybackRequestType.cs | 8 +-- ...kRequestBody.cs => NextItemRequestBody.cs} | 8 +-- ...uestBody.cs => PreviousItemRequestBody.cs} | 8 +-- 13 files changed, 70 insertions(+), 70 deletions(-) rename MediaBrowser.Controller/SyncPlay/PlaybackRequests/{NextTrackGroupRequest.cs => NextItemGroupRequest.cs} (77%) rename MediaBrowser.Controller/SyncPlay/PlaybackRequests/{PreviousTrackGroupRequest.cs => PreviousItemGroupRequest.cs} (81%) rename MediaBrowser.Model/SyncPlay/RequestBodies/{NextTrackRequestBody.cs => NextItemRequestBody.cs} (67%) rename MediaBrowser.Model/SyncPlay/RequestBodies/{PreviousTrackRequestBody.cs => PreviousItemRequestBody.cs} (76%) diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 763940c733..f8bbed9c42 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -108,14 +108,14 @@ namespace Jellyfin.Api.Controllers } /// <summary> - /// Request play in SyncPlay group. + /// Request to set new playlist in SyncPlay group. /// </summary> /// <param name="requestData">The new playlist to play in the group.</param> - /// <response code="204">Play request sent to all group members.</response> + /// <response code="204">Queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> - [HttpPost("Play")] + [HttpPost("SetNewQueue")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayPlay( + public ActionResult SyncPlaySetNewQueue( [FromBody, Required] PlayRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -131,7 +131,7 @@ namespace Jellyfin.Api.Controllers /// Request to change playlist item in SyncPlay group. /// </summary> /// <param name="requestData">The new item to play.</param> - /// <response code="204">Queue update request sent to all group members.</response> + /// <response code="204">Queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetPlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -148,7 +148,7 @@ namespace Jellyfin.Api.Controllers /// Request to remove items from the playlist in SyncPlay group. /// </summary> /// <param name="requestData">The items to remove.</param> - /// <response code="204">Queue update request sent to all group members.</response> + /// <response code="204">Queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("RemoveFromPlaylist")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -165,7 +165,7 @@ namespace Jellyfin.Api.Controllers /// Request to move an item in the playlist in SyncPlay group. /// </summary> /// <param name="requestData">The new position for the item.</param> - /// <response code="204">Queue update request sent to all group members.</response> + /// <response code="204">Queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("MovePlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -182,7 +182,7 @@ namespace Jellyfin.Api.Controllers /// Request to queue items to the playlist of a SyncPlay group. /// </summary> /// <param name="requestData">The items to add.</param> - /// <response code="204">Queue update request sent to all group members.</response> + /// <response code="204">Queue update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -198,7 +198,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request unpause in SyncPlay group. /// </summary> - /// <response code="204">Unpause request sent to all group members.</response> + /// <response code="204">Unpause update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Unpause")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -213,7 +213,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request pause in SyncPlay group. /// </summary> - /// <response code="204">Pause request sent to all group members.</response> + /// <response code="204">Pause update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Pause")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -228,7 +228,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Request stop in SyncPlay group. /// </summary> - /// <response code="204">Stop request sent to all group members.</response> + /// <response code="204">Stop update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Stop")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -244,7 +244,7 @@ namespace Jellyfin.Api.Controllers /// Request seek in SyncPlay group. /// </summary> /// <param name="requestData">The new playback position.</param> - /// <response code="204">Seek request sent to all group members.</response> + /// <response code="204">Seek update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Seek")] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -317,35 +317,35 @@ namespace Jellyfin.Api.Controllers } /// <summary> - /// Request next track in SyncPlay group. + /// Request next item in SyncPlay group. /// </summary> - /// <param name="requestData">The current track information.</param> - /// <response code="204">Next track request sent to all group members.</response> + /// <param name="requestData">The current item information.</param> + /// <response code="204">Next item update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> - [HttpPost("NextTrack")] + [HttpPost("NextItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayNextTrack( - [FromBody, Required] NextTrackRequestBody requestData) + public ActionResult SyncPlayNextItem( + [FromBody, Required] NextItemRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new NextTrackGroupRequest(requestData.PlaylistItemId); + var syncPlayRequest = new NextItemGroupRequest(requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } /// <summary> - /// Request previous track in SyncPlay group. + /// Request previous item in SyncPlay group. /// </summary> - /// <param name="requestData">The current track information.</param> - /// <response code="204">Previous track request sent to all group members.</response> + /// <param name="requestData">The current item information.</param> + /// <response code="204">Previous item update sent to all group members.</response> /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> - [HttpPost("PreviousTrack")] + [HttpPost("PreviousItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SyncPlayPreviousTrack( - [FromBody, Required] PreviousTrackRequestBody requestData) + public ActionResult SyncPlayPreviousItem( + [FromBody, Required] PreviousItemRequestBody requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); - var syncPlayRequest = new PreviousTrackGroupRequest(requestData.PlaylistItemId); + var syncPlayRequest = new PreviousItemGroupRequest(requestData.PlaylistItemId); _syncPlayManager.HandleRequest(currentSession, syncPlayRequest, CancellationToken.None); return NoContent(); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index 0b15e3ae4a..5e3d4a2528 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -157,13 +157,13 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index 7730a298c2..8074d5a96b 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); @@ -102,7 +102,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index 90411f61bc..28e5db950d 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -145,7 +145,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); @@ -154,7 +154,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index aab87d9c39..278a0af084 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -148,7 +148,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); @@ -157,7 +157,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index fefb8067fe..f5f603c296 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -560,7 +560,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -582,7 +582,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (newItem) { // Send playing-queue update. - var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextTrack); + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.NextItem); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); @@ -601,12 +601,12 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SetState(newState); - _logger.LogDebug("No next track available in group {GroupId}.", context.GroupId.ToString()); + _logger.LogDebug("No next item available in group {GroupId}.", context.GroupId.ToString()); } } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -628,7 +628,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (newItem) { // Send playing-queue update. - var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousTrack); + var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.PreviousItem); var update = context.NewSyncPlayGroupUpdate(GroupUpdateType.PlayQueue, playQueueUpdate); context.SendGroupUpdate(session, SyncPlayBroadcastType.AllGroup, update, cancellationToken); @@ -647,7 +647,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates context.SetState(newState); - _logger.LogDebug("No previous track available in group {GroupId}.", context.GroupId.ToString()); + _logger.LogDebug("No previous item available in group {GroupId}.", context.GroupId.ToString()); } } diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs index 0028823b4e..89a8e2e2e7 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -155,24 +155,24 @@ namespace MediaBrowser.Controller.SyncPlay void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a next-track request from a session. Context's state can change. + /// Handles a next-item request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The next-track request.</param> + /// <param name="request">The next-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> - /// Handles a previous-track request from a session. Context's state can change. + /// Handles a previous-item request from a session. Context's state can change. /// </summary> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The previous-track request.</param> + /// <param name="request">The previous-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousTrackGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a set-repeat-mode request from a session. Context's state should not change. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs similarity index 77% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs index 73b7d0908b..ab60265a6b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs @@ -5,15 +5,15 @@ using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> - /// Class NextTrackGroupRequest. + /// Class NextItemGroupRequest. /// </summary> - public class NextTrackGroupRequest : AbstractPlaybackRequest + public class NextItemGroupRequest : AbstractPlaybackRequest { /// <summary> - /// Initializes a new instance of the <see cref="NextTrackGroupRequest"/> class. + /// Initializes a new instance of the <see cref="NextItemGroupRequest"/> class. /// </summary> /// <param name="playlistItemId">The playing item identifier.</param> - public NextTrackGroupRequest(string playlistItemId) + public NextItemGroupRequest(string playlistItemId) { PlaylistItemId = playlistItemId; } @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public override PlaybackRequestType Action { get; } = PlaybackRequestType.NextTrack; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.NextItem; /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs similarity index 81% rename from MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs rename to MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs index 4c70beb0ef..445c5fce65 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousTrackGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs @@ -5,15 +5,15 @@ using MediaBrowser.Model.SyncPlay; namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests { /// <summary> - /// Class PreviousTrackGroupRequest. + /// Class PreviousItemGroupRequest. /// </summary> - public class PreviousTrackGroupRequest : AbstractPlaybackRequest + public class PreviousItemGroupRequest : AbstractPlaybackRequest { /// <summary> - /// Initializes a new instance of the <see cref="PreviousTrackGroupRequest"/> class. + /// Initializes a new instance of the <see cref="PreviousItemGroupRequest"/> class. /// </summary> /// <param name="playlistItemId">The playing item identifier.</param> - public PreviousTrackGroupRequest(string playlistItemId) + public PreviousItemGroupRequest(string playlistItemId) { PlaylistItemId = playlistItemId; } @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests public string PlaylistItemId { get; } /// <inheritdoc /> - public override PlaybackRequestType Action { get; } = PlaybackRequestType.PreviousTrack; + public override PlaybackRequestType Action { get; } = PlaybackRequestType.PreviousItem; /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) diff --git a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs index e78940fe68..b609f4b1bd 100644 --- a/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs +++ b/MediaBrowser.Model/SyncPlay/PlayQueueUpdateReason.cs @@ -38,12 +38,12 @@ namespace MediaBrowser.Model.SyncPlay /// <summary> /// A user is requesting the next item in queue. /// </summary> - NextTrack = 6, + NextItem = 6, /// <summary> /// A user is requesting the previous item in queue. /// </summary> - PreviousTrack = 7, + PreviousItem = 7, /// <summary> /// A user is changing repeat mode. diff --git a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs index 4809dc44f8..4429623dd9 100644 --- a/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs +++ b/MediaBrowser.Model/SyncPlay/PlaybackRequestType.cs @@ -61,14 +61,14 @@ namespace MediaBrowser.Model.SyncPlay Ready = 10, /// <summary> - /// A user is requesting next track in playlist. + /// A user is requesting next item in playlist. /// </summary> - NextTrack = 11, + NextItem = 11, /// <summary> - /// A user is requesting previous track in playlist. + /// A user is requesting previous item in playlist. /// </summary> - PreviousTrack = 12, + PreviousItem = 12, /// <summary> /// A user is setting the repeat mode. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs similarity index 67% rename from MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs rename to MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs index 1d8d135cbb..39ce75dc19 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/NextTrackRequestBody.cs +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs @@ -1,14 +1,14 @@ namespace MediaBrowser.Model.SyncPlay.RequestBodies { /// <summary> - /// Class NextTrackRequestBody. + /// Class NextItemRequestBody. /// </summary> - public class NextTrackRequestBody + public class NextItemRequestBody { /// <summary> - /// Initializes a new instance of the <see cref="NextTrackRequestBody"/> class. + /// Initializes a new instance of the <see cref="NextItemRequestBody"/> class. /// </summary> - public NextTrackRequestBody() + public NextItemRequestBody() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs b/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs similarity index 76% rename from MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs rename to MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs index 95ebeeb908..671a7291ce 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousTrackRequestBody.cs +++ b/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs @@ -1,14 +1,14 @@ namespace MediaBrowser.Model.SyncPlay.RequestBodies { /// <summary> - /// Class PreviousTrackRequestBody. + /// Class PreviousItemRequestBody. /// </summary> - public class PreviousTrackRequestBody + public class PreviousItemRequestBody { /// <summary> - /// Initializes a new instance of the <see cref="PreviousTrackRequestBody"/> class. + /// Initializes a new instance of the <see cref="PreviousItemRequestBody"/> class. /// </summary> - public PreviousTrackRequestBody() + public PreviousItemRequestBody() { PlaylistItemId = string.Empty; } From 7169c0a22da8147e1fd00f6568e41d235123809f Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Thu, 3 Dec 2020 19:01:57 +0100 Subject: [PATCH 0625/1930] Move SyncPlay request DTOs to proper namespace --- .../Controllers/SyncPlayController.cs | 34 +++++++++---------- .../Models/SyncPlayDtos/BufferRequestDto.cs | 10 +++--- .../SyncPlayDtos/IgnoreWaitRequestDto.cs | 6 ++-- .../SyncPlayDtos/JoinGroupRequestDto.cs | 6 ++-- .../MovePlaylistItemRequestDto.cs | 10 +++--- .../Models/SyncPlayDtos/NewGroupRequestDto.cs | 10 +++--- .../Models/SyncPlayDtos/NextItemRequestDto.cs | 10 +++--- .../Models/SyncPlayDtos/PingRequestDto.cs | 6 ++-- .../Models/SyncPlayDtos/PlayRequestDto.cs | 10 +++--- .../SyncPlayDtos/PreviousItemRequestDto.cs | 10 +++--- .../Models/SyncPlayDtos/QueueRequestDto.cs | 11 +++--- .../Models/SyncPlayDtos/ReadyRequestDto.cs | 8 ++--- .../RemoveFromPlaylistRequestDto.cs | 10 +++--- .../Models/SyncPlayDtos/SeekRequestDto.cs | 6 ++-- .../SyncPlayDtos/SetPlaylistItemRequestDto.cs | 10 +++--- .../SyncPlayDtos/SetRepeatModeRequestDto.cs | 8 +++-- .../SyncPlayDtos/SetShuffleModeRequestDto.cs | 8 +++-- .../SyncPlay/ISyncPlayManager.cs | 1 - 18 files changed, 89 insertions(+), 85 deletions(-) rename MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs (86%) rename MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs (68%) rename MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs (67%) rename MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs (74%) rename MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs (68%) rename MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs (70%) rename MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs (65%) rename MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs (84%) rename MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs (68%) rename MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs (77%) rename MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs (88%) rename MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs (70%) rename MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs (67%) rename MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs (68%) rename MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs (59%) rename MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs => Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs (59%) diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index f8bbed9c42..32e020c8ae 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -4,13 +4,13 @@ using System.ComponentModel.DataAnnotations; using System.Threading; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; +using Jellyfin.Api.Models.SyncPlayDtos; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Model.SyncPlay.RequestBodies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -53,7 +53,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] [Authorize(Policy = Policies.SyncPlayCreateGroupAccess)] public ActionResult SyncPlayCreateGroup( - [FromBody, Required] NewGroupRequestBody requestData) + [FromBody, Required] NewGroupRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new NewGroupRequest(requestData.GroupName); @@ -70,7 +70,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Join")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayJoinGroup( - [FromBody, Required] JoinGroupRequestBody requestData) + [FromBody, Required] JoinGroupRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new JoinGroupRequest(requestData.GroupId); @@ -116,7 +116,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetNewQueue")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetNewQueue( - [FromBody, Required] PlayRequestBody requestData) + [FromBody, Required] PlayRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new PlayGroupRequest( @@ -136,7 +136,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetPlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetPlaylistItem( - [FromBody, Required] SetPlaylistItemRequestBody requestData) + [FromBody, Required] SetPlaylistItemRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new SetPlaylistItemGroupRequest(requestData.PlaylistItemId); @@ -153,7 +153,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("RemoveFromPlaylist")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayRemoveFromPlaylist( - [FromBody, Required] RemoveFromPlaylistRequestBody requestData) + [FromBody, Required] RemoveFromPlaylistRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new RemoveFromPlaylistGroupRequest(requestData.PlaylistItemIds); @@ -170,7 +170,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("MovePlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayMovePlaylistItem( - [FromBody, Required] MovePlaylistItemRequestBody requestData) + [FromBody, Required] MovePlaylistItemRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new MovePlaylistItemGroupRequest(requestData.PlaylistItemId, requestData.NewIndex); @@ -187,7 +187,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayQueue( - [FromBody, Required] QueueRequestBody requestData) + [FromBody, Required] QueueRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new QueueGroupRequest(requestData.ItemIds, requestData.Mode); @@ -249,7 +249,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Seek")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySeek( - [FromBody, Required] SeekRequestBody requestData) + [FromBody, Required] SeekRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new SeekGroupRequest(requestData.PositionTicks); @@ -266,7 +266,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Buffering")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayBuffering( - [FromBody, Required] BufferRequestBody requestData) + [FromBody, Required] BufferRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new BufferGroupRequest( @@ -287,7 +287,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Ready")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayReady( - [FromBody, Required] ReadyRequestBody requestData) + [FromBody, Required] ReadyRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new ReadyGroupRequest( @@ -308,7 +308,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetIgnoreWait")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetIgnoreWait( - [FromBody, Required] IgnoreWaitRequestBody requestData) + [FromBody, Required] IgnoreWaitRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new IgnoreWaitGroupRequest(requestData.IgnoreWait); @@ -325,7 +325,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("NextItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayNextItem( - [FromBody, Required] NextItemRequestBody requestData) + [FromBody, Required] NextItemRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new NextItemGroupRequest(requestData.PlaylistItemId); @@ -342,7 +342,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("PreviousItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPreviousItem( - [FromBody, Required] PreviousItemRequestBody requestData) + [FromBody, Required] PreviousItemRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new PreviousItemGroupRequest(requestData.PlaylistItemId); @@ -359,7 +359,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetRepeatMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetRepeatMode( - [FromBody, Required] SetRepeatModeRequestBody requestData) + [FromBody, Required] SetRepeatModeRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new SetRepeatModeGroupRequest(requestData.Mode); @@ -376,7 +376,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("SetShuffleMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlaySetShuffleMode( - [FromBody, Required] SetShuffleModeRequestBody requestData) + [FromBody, Required] SetShuffleModeRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new SetShuffleModeGroupRequest(requestData.Mode); @@ -393,7 +393,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Ping")] [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SyncPlayPing( - [FromBody, Required] PingRequestBody requestData) + [FromBody, Required] PingRequestDto requestData) { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); var syncPlayRequest = new PingGroupRequest(requestData.Ping); diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs similarity index 86% rename from MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs index 09ca712e51..cafc400c9c 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/BufferRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs @@ -1,16 +1,16 @@ using System; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class BufferRequestBody. + /// Class BufferRequestDto. /// </summary> - public class BufferRequestBody + public class BufferRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="BufferRequestBody"/> class. + /// Initializes a new instance of the <see cref="BufferRequestDto"/> class. /// </summary> - public BufferRequestBody() + public BufferRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs similarity index 68% rename from MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs index 22407e88ed..4c30b7be43 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/IgnoreWaitRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/IgnoreWaitRequestDto.cs @@ -1,9 +1,9 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class IgnoreWaitRequestBody. + /// Class IgnoreWaitRequestDto. /// </summary> - public class IgnoreWaitRequestBody + public class IgnoreWaitRequestDto { /// <summary> /// Gets or sets a value indicating whether the client should be ignored. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs similarity index 67% rename from MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs index 2cec7bdc21..ed97b8d6a5 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/JoinGroupRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/JoinGroupRequestDto.cs @@ -1,11 +1,11 @@ using System; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class JoinGroupRequestBody. + /// Class JoinGroupRequestDto. /// </summary> - public class JoinGroupRequestBody + public class JoinGroupRequestDto { /// <summary> /// Gets or sets the group identifier. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs similarity index 74% rename from MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs index d18eb68ffe..9e9c0b1eab 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/MovePlaylistItemRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs @@ -1,14 +1,14 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class MovePlaylistItemRequestBody. + /// Class MovePlaylistItemRequestDto. /// </summary> - public class MovePlaylistItemRequestBody + public class MovePlaylistItemRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="MovePlaylistItemRequestBody"/> class. + /// Initializes a new instance of the <see cref="MovePlaylistItemRequestDto"/> class. /// </summary> - public MovePlaylistItemRequestBody() + public MovePlaylistItemRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs similarity index 68% rename from MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs index 1a85d276b9..441d7be367 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/NewGroupRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/NewGroupRequestDto.cs @@ -1,14 +1,14 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class NewGroupRequestBody. + /// Class NewGroupRequestDto. /// </summary> - public class NewGroupRequestBody + public class NewGroupRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="NewGroupRequestBody"/> class. + /// Initializes a new instance of the <see cref="NewGroupRequestDto"/> class. /// </summary> - public NewGroupRequestBody() + public NewGroupRequestDto() { GroupName = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs similarity index 70% rename from MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs index 39ce75dc19..aa67954e75 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/NextItemRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs @@ -1,14 +1,14 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class NextItemRequestBody. + /// Class NextItemRequestDto. /// </summary> - public class NextItemRequestBody + public class NextItemRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="NextItemRequestBody"/> class. + /// Initializes a new instance of the <see cref="NextItemRequestDto"/> class. /// </summary> - public NextItemRequestBody() + public NextItemRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs similarity index 65% rename from MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs index f08015bc46..c4ac068565 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/PingRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/PingRequestDto.cs @@ -1,9 +1,9 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class PingRequestBody. + /// Class PingRequestDto. /// </summary> - public class PingRequestBody + public class PingRequestDto { /// <summary> /// Gets or sets the ping time. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs similarity index 84% rename from MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs index 97ec95c624..844388cd99 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/PlayRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/PlayRequestDto.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class PlayRequestBody. + /// Class PlayRequestDto. /// </summary> - public class PlayRequestBody + public class PlayRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="PlayRequestBody"/> class. + /// Initializes a new instance of the <see cref="PlayRequestDto"/> class. /// </summary> - public PlayRequestBody() + public PlayRequestDto() { PlayingQueue = Array.Empty<Guid>(); } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs similarity index 68% rename from MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs index 671a7291ce..b23d4dee0a 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/PreviousItemRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs @@ -1,14 +1,14 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class PreviousItemRequestBody. + /// Class PreviousItemRequestDto. /// </summary> - public class PreviousItemRequestBody + public class PreviousItemRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="PreviousItemRequestBody"/> class. + /// Initializes a new instance of the <see cref="PreviousItemRequestDto"/> class. /// </summary> - public PreviousItemRequestBody() + public PreviousItemRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs similarity index 77% rename from MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs index 1afc61dd46..2b187f443f 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/QueueRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/QueueRequestDto.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; +using MediaBrowser.Model.SyncPlay; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class QueueRequestBody. + /// Class QueueRequestDto. /// </summary> - public class QueueRequestBody + public class QueueRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="QueueRequestBody"/> class. + /// Initializes a new instance of the <see cref="QueueRequestDto"/> class. /// </summary> - public QueueRequestBody() + public QueueRequestDto() { ItemIds = Array.Empty<Guid>(); } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs similarity index 88% rename from MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs index 359186e781..0155d52495 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/ReadyRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs @@ -1,16 +1,16 @@ using System; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> /// Class ReadyRequest. /// </summary> - public class ReadyRequestBody + public class ReadyRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="ReadyRequestBody"/> class. + /// Initializes a new instance of the <see cref="ReadyRequestDto"/> class. /// </summary> - public ReadyRequestBody() + public ReadyRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs similarity index 70% rename from MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs index a2b617cd03..facb809fca 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/RemoveFromPlaylistRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs @@ -1,17 +1,17 @@ using System; using System.Collections.Generic; -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class RemoveFromPlaylistRequestBody. + /// Class RemoveFromPlaylistRequestDto. /// </summary> - public class RemoveFromPlaylistRequestBody + public class RemoveFromPlaylistRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="RemoveFromPlaylistRequestBody"/> class. + /// Initializes a new instance of the <see cref="RemoveFromPlaylistRequestDto"/> class. /// </summary> - public RemoveFromPlaylistRequestBody() + public RemoveFromPlaylistRequestDto() { PlaylistItemIds = Array.Empty<string>(); } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs similarity index 67% rename from MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs index 689183bb6a..b9af0be7ff 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/SeekRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/SeekRequestDto.cs @@ -1,9 +1,9 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class SeekRequestBody. + /// Class SeekRequestDto. /// </summary> - public class SeekRequestBody + public class SeekRequestDto { /// <summary> /// Gets or sets the position ticks. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs similarity index 68% rename from MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs index abe66c479e..3440858712 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/SetPlaylistItemRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs @@ -1,14 +1,14 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class SetPlaylistItemRequestBody. + /// Class SetPlaylistItemRequestDto. /// </summary> - public class SetPlaylistItemRequestBody + public class SetPlaylistItemRequestDto { /// <summary> - /// Initializes a new instance of the <see cref="SetPlaylistItemRequestBody"/> class. + /// Initializes a new instance of the <see cref="SetPlaylistItemRequestDto"/> class. /// </summary> - public SetPlaylistItemRequestBody() + public SetPlaylistItemRequestDto() { PlaylistItemId = string.Empty; } diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs similarity index 59% rename from MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs index 6de5415cae..e748fc3e0f 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/SetRepeatModeRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/SetRepeatModeRequestDto.cs @@ -1,9 +1,11 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +using MediaBrowser.Model.SyncPlay; + +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class SetRepeatModeRequestBody. + /// Class SetRepeatModeRequestDto. /// </summary> - public class SetRepeatModeRequestBody + public class SetRepeatModeRequestDto { /// <summary> /// Gets or sets the repeat mode. diff --git a/MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs similarity index 59% rename from MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs rename to Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs index 867cb938dc..0e427f4a4d 100644 --- a/MediaBrowser.Model/SyncPlay/RequestBodies/SetShuffleModeRequestBody.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/SetShuffleModeRequestDto.cs @@ -1,9 +1,11 @@ -namespace MediaBrowser.Model.SyncPlay.RequestBodies +using MediaBrowser.Model.SyncPlay; + +namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> - /// Class SetShuffleModeRequestBody. + /// Class SetShuffleModeRequestDto. /// </summary> - public class SetShuffleModeRequestBody + public class SetShuffleModeRequestDto { /// <summary> /// Gets or sets the shuffle mode. diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 146e4351df..d0244563a4 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -4,7 +4,6 @@ using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.Requests; using MediaBrowser.Model.SyncPlay; -using MediaBrowser.Model.SyncPlay.RequestBodies; namespace MediaBrowser.Controller.SyncPlay { From b7eb4da04e0cbb820becc9022975f69aed4f8531 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Thu, 3 Dec 2020 21:01:18 +0100 Subject: [PATCH 0626/1930] Rename GroupController into Group --- .../SyncPlay/{GroupController.cs => Group.cs} | 73 +++++++++------- .../SyncPlay/SyncPlayManager.cs | 29 ++++--- .../SyncPlay/IGroupController.cs | 87 ------------------- 3 files changed, 58 insertions(+), 131 deletions(-) rename Emby.Server.Implementations/SyncPlay/{GroupController.cs => Group.cs} (91%) delete mode 100644 MediaBrowser.Controller/SyncPlay/IGroupController.cs diff --git a/Emby.Server.Implementations/SyncPlay/GroupController.cs b/Emby.Server.Implementations/SyncPlay/Group.cs similarity index 91% rename from Emby.Server.Implementations/SyncPlay/GroupController.cs rename to Emby.Server.Implementations/SyncPlay/Group.cs index 16acae99e8..e32f5e25dc 100644 --- a/Emby.Server.Implementations/SyncPlay/GroupController.cs +++ b/Emby.Server.Implementations/SyncPlay/Group.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; -using Jellyfin.Data.Enums; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; @@ -19,17 +16,17 @@ using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.SyncPlay { /// <summary> - /// Class GroupController. + /// Class Group. /// </summary> /// <remarks> /// Class is not thread-safe, external locking is required when accessing methods. /// </remarks> - public class GroupController : IGroupController, IGroupStateContext + public class Group : IGroupStateContext { /// <summary> /// The logger. /// </summary> - private readonly ILogger<GroupController> _logger; + private readonly ILogger<Group> _logger; /// <summary> /// The logger factory. @@ -63,13 +60,13 @@ namespace Emby.Server.Implementations.SyncPlay private IGroupState _state; /// <summary> - /// Initializes a new instance of the <see cref="GroupController" /> class. + /// Initializes a new instance of the <see cref="Group" /> class. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <param name="userManager">The user manager.</param> /// <param name="sessionManager">The session manager.</param> /// <param name="libraryManager">The library manager.</param> - public GroupController( + public Group( ILoggerFactory loggerFactory, IUserManager userManager, ISessionManager sessionManager, @@ -79,7 +76,7 @@ namespace Emby.Server.Implementations.SyncPlay _userManager = userManager; _sessionManager = sessionManager; _libraryManager = libraryManager; - _logger = loggerFactory.CreateLogger<GroupController>(); + _logger = loggerFactory.CreateLogger<Group>(); _state = new IdleGroupState(loggerFactory); } @@ -235,10 +232,18 @@ namespace Emby.Server.Implementations.SyncPlay return !usersWithNoAccess.Any(); } - /// <inheritdoc /> + /// <summary> + /// Checks if the group is empty. + /// </summary> + /// <returns><c>true</c> if the group is empty, <c>false</c> otherwise.</returns> public bool IsGroupEmpty() => _participants.Count == 0; - /// <inheritdoc /> + /// <summary> + /// Initializes the group with the session's info. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> public void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { GroupName = request.GroupName; @@ -273,7 +278,12 @@ namespace Emby.Server.Implementations.SyncPlay _logger.LogInformation("Session {SessionId} created group {GroupId}.", session.Id, GroupId.ToString()); } - /// <inheritdoc /> + /// <summary> + /// Adds the session to the group. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { AddSession(session); @@ -289,21 +299,12 @@ namespace Emby.Server.Implementations.SyncPlay _logger.LogInformation("Session {SessionId} joined group {GroupId}.", session.Id, GroupId.ToString()); } - /// <inheritdoc /> - public void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) - { - var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, GetInfo()); - SendGroupUpdate(session, SyncPlayBroadcastType.CurrentSession, updateSession, cancellationToken); - - var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName); - SendGroupUpdate(session, SyncPlayBroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken); - - _state.SessionJoined(this, _state.Type, session, cancellationToken); - - _logger.LogInformation("Session {SessionId} re-joined group {GroupId}.", session.Id, GroupId.ToString()); - } - - /// <inheritdoc /> + /// <summary> + /// Removes the session from the group. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> public void SessionLeave(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { _state.SessionLeaving(this, _state.Type, session, cancellationToken); @@ -319,7 +320,12 @@ namespace Emby.Server.Implementations.SyncPlay _logger.LogInformation("Session {SessionId} left group {GroupId}.", session.Id, GroupId.ToString()); } - /// <inheritdoc /> + /// <summary> + /// Handles the requested action by the session. + /// </summary> + /// <param name="session">The session.</param> + /// <param name="request">The requested action.</param> + /// <param name="cancellationToken">The cancellation token.</param> public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { // The server's job is to maintain a consistent state for clients to reference @@ -329,14 +335,21 @@ namespace Emby.Server.Implementations.SyncPlay request.Apply(this, _state, session, cancellationToken); } - /// <inheritdoc /> + /// <summary> + /// Gets the info about the group for the clients. + /// </summary> + /// <returns>The group info for the clients.</returns> public GroupInfoDto GetInfo() { var participants = _participants.Values.Select(session => session.Session.UserName).Distinct().ToList(); return new GroupInfoDto(GroupId, GroupName, _state.Type, participants, DateTime.UtcNow); } - /// <inheritdoc /> + /// <summary> + /// Checks if a user has access to all content in the play queue. + /// </summary> + /// <param name="user">The user.</param> + /// <returns><c>true</c> if the user can access the play queue; <c>false</c> otherwise.</returns> public bool HasAccessToPlayQueue(User user) { var items = PlayQueue.GetPlaylist().Select(item => item.ItemId).ToList(); diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 0410048c4f..b2422f8e6e 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -44,20 +44,20 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// The map between sessions and groups. /// </summary> - private readonly Dictionary<string, IGroupController> _sessionToGroupMap = - new Dictionary<string, IGroupController>(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, Group> _sessionToGroupMap = + new Dictionary<string, Group>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The groups. /// </summary> - private readonly Dictionary<Guid, IGroupController> _groups = - new Dictionary<Guid, IGroupController>(); + private readonly Dictionary<Guid, Group> _groups = + new Dictionary<Guid, Group>(); /// <summary> /// Lock used for accessing any group. /// </summary> /// <remarks> - /// Always lock before <see cref="_mapsLock"/> and before locking on any <see cref="IGroupController"/>. + /// Always lock before <see cref="_mapsLock"/> and before locking on any <see cref="Group"/>. /// </remarks> private readonly object _groupsLock = new object(); @@ -65,7 +65,7 @@ namespace Emby.Server.Implementations.SyncPlay /// Lock used for accessing the session-to-group map. /// </summary> /// <remarks> - /// Always lock after <see cref="_groupsLock"/> and before locking on any <see cref="IGroupController"/>. + /// Always lock after <see cref="_groupsLock"/> and before locking on any <see cref="Group"/>. /// </remarks> private readonly object _mapsLock = new object(); @@ -115,7 +115,7 @@ namespace Emby.Server.Implementations.SyncPlay LeaveGroup(session, leaveGroupRequest, cancellationToken); } - var group = new GroupController(_loggerFactory, _userManager, _sessionManager, _libraryManager); + var group = new Group(_loggerFactory, _userManager, _sessionManager, _libraryManager); _groups[group.GroupId] = group; AddSessionToGroup(session, group); @@ -132,7 +132,7 @@ namespace Emby.Server.Implementations.SyncPlay // Locking required to access list of groups. lock (_groupsLock) { - _groups.TryGetValue(request.GroupId, out IGroupController group); + _groups.TryGetValue(request.GroupId, out Group group); if (group == null) { @@ -162,7 +162,8 @@ namespace Emby.Server.Implementations.SyncPlay { if (FindJoinedGroupId(session).Equals(request.GroupId)) { - group.SessionRestore(session, request, cancellationToken); + // Restore session. + group.SessionJoin(session, request, cancellationToken); return; } @@ -240,7 +241,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { - IGroupController group; + Group group; lock (_mapsLock) { group = FindJoinedGroup(session); @@ -255,7 +256,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // Group lock required as GroupController is not thread-safe. + // Group lock required as Group is not thread-safe. lock (group) { group.HandleRequest(session, request, cancellationToken); @@ -317,7 +318,7 @@ namespace Emby.Server.Implementations.SyncPlay /// </remarks> /// <param name="session">The session.</param> /// <returns>The group.</returns> - private IGroupController FindJoinedGroup(SessionInfo session) + private Group FindJoinedGroup(SessionInfo session) { _sessionToGroupMap.TryGetValue(session.Id, out var group); return group; @@ -345,7 +346,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> - private void AddSessionToGroup(SessionInfo session, IGroupController group) + private void AddSessionToGroup(SessionInfo session, Group group) { if (session == null) { @@ -369,7 +370,7 @@ namespace Emby.Server.Implementations.SyncPlay /// <param name="session">The session.</param> /// <param name="group">The group.</param> /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> - private void RemoveSessionFromGroup(SessionInfo session, IGroupController group) + private void RemoveSessionFromGroup(SessionInfo session, Group group) { if (session == null) { diff --git a/MediaBrowser.Controller/SyncPlay/IGroupController.cs b/MediaBrowser.Controller/SyncPlay/IGroupController.cs deleted file mode 100644 index 07f9659dd1..0000000000 --- a/MediaBrowser.Controller/SyncPlay/IGroupController.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Threading; -using Jellyfin.Data.Entities; -using MediaBrowser.Controller.Session; -using MediaBrowser.Controller.SyncPlay.Queue; -using MediaBrowser.Controller.SyncPlay.Requests; -using MediaBrowser.Model.SyncPlay; - -namespace MediaBrowser.Controller.SyncPlay -{ - /// <summary> - /// Interface IGroupController. - /// </summary> - public interface IGroupController - { - /// <summary> - /// Gets the group identifier. - /// </summary> - /// <value>The group identifier.</value> - Guid GroupId { get; } - - /// <summary> - /// Gets the play queue. - /// </summary> - /// <value>The play queue.</value> - PlayQueueManager PlayQueue { get; } - - /// <summary> - /// Checks if the group is empty. - /// </summary> - /// <returns><c>true</c> if the group is empty, <c>false</c> otherwise.</returns> - bool IsGroupEmpty(); - - /// <summary> - /// Initializes the group with the session's info. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The request.</param> - /// <param name="cancellationToken">The cancellation token.</param> - void CreateGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Adds the session to the group. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The request.</param> - /// <param name="cancellationToken">The cancellation token.</param> - void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Restores the state of a session that already joined the group. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The request.</param> - /// <param name="cancellationToken">The cancellation token.</param> - void SessionRestore(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Removes the session from the group. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The request.</param> - /// <param name="cancellationToken">The cancellation token.</param> - void SessionLeave(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Handles the requested action by the session. - /// </summary> - /// <param name="session">The session.</param> - /// <param name="request">The requested action.</param> - /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken); - - /// <summary> - /// Gets the info about the group for the clients. - /// </summary> - /// <returns>The group info for the clients.</returns> - GroupInfoDto GetInfo(); - - /// <summary> - /// Checks if a user has access to all content in the play queue. - /// </summary> - /// <param name="user">The user.</param> - /// <returns><c>true</c> if the user can access the play queue; <c>false</c> otherwise.</returns> - bool HasAccessToPlayQueue(User user); - } -} From b0c79edd2c25f560208a40aedea05498d48ca80e Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 3 Dec 2020 13:51:12 -0700 Subject: [PATCH 0627/1930] Add support for custom item display preferences --- .../DisplayPreferencesController.cs | 36 +- .../Entities/CustomItemDisplayPreferences.cs | 80 +++ Jellyfin.Server.Implementations/JellyfinDb.cs | 10 + ...07_AddCustomDisplayPreferences.Designer.cs | 516 ++++++++++++++++++ ...01203203707_AddCustomDisplayPreferences.cs | 70 +++ .../Migrations/JellyfinDbModelSnapshot.cs | 131 +++-- .../Users/DisplayPreferencesManager.cs | 24 + .../IDisplayPreferencesManager.cs | 16 + 8 files changed, 842 insertions(+), 41 deletions(-) create mode 100644 Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs create mode 100644 Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs create mode 100644 Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 76f5717e30..27b628774b 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -81,6 +81,19 @@ namespace Jellyfin.Api.Controllers dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture); dto.CustomPrefs["tvhome"] = displayPreferences.TvHome; + // Load all custom display preferences + var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, displayPreferences.Client); + if (customDisplayPreferences != null) + { + foreach (var (key, value) in customDisplayPreferences) + { + if (!dto.CustomPrefs.ContainsKey(key)) + { + dto.CustomPrefs[key] = value; + } + } + } + // This will essentially be a noop if no changes have been made, but new prefs must be saved at least. _displayPreferencesManager.SaveChanges(); @@ -124,21 +137,33 @@ namespace Jellyfin.Api.Controllers existingDisplayPreferences.ChromecastVersion = displayPreferences.CustomPrefs.TryGetValue("chromecastVersion", out var chromecastVersion) ? Enum.Parse<ChromecastVersion>(chromecastVersion, true) : ChromecastVersion.Stable; + displayPreferences.CustomPrefs.Remove("chromecastVersion"); + existingDisplayPreferences.EnableNextVideoInfoOverlay = displayPreferences.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enableNextVideoInfoOverlay) ? bool.Parse(enableNextVideoInfoOverlay) : true; + displayPreferences.CustomPrefs.Remove("enableNextVideoInfoOverlay"); + existingDisplayPreferences.SkipBackwardLength = displayPreferences.CustomPrefs.TryGetValue("skipBackLength", out var skipBackLength) ? int.Parse(skipBackLength, CultureInfo.InvariantCulture) : 10000; + displayPreferences.CustomPrefs.Remove("skipBackLength"); + existingDisplayPreferences.SkipForwardLength = displayPreferences.CustomPrefs.TryGetValue("skipForwardLength", out var skipForwardLength) ? int.Parse(skipForwardLength, CultureInfo.InvariantCulture) : 30000; + displayPreferences.CustomPrefs.Remove("skipForwardLength"); + existingDisplayPreferences.DashboardTheme = displayPreferences.CustomPrefs.TryGetValue("dashboardTheme", out var theme) ? theme : string.Empty; + displayPreferences.CustomPrefs.Remove("dashboardTheme"); + existingDisplayPreferences.TvHome = displayPreferences.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty; + displayPreferences.CustomPrefs.Remove("tvhome"); + existingDisplayPreferences.HomeSections.Clear(); foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("homesection", StringComparison.OrdinalIgnoreCase))) @@ -149,13 +174,18 @@ namespace Jellyfin.Api.Controllers type = order < 7 ? defaults[order] : HomeSectionType.None; } + displayPreferences.CustomPrefs.Remove(key); existingDisplayPreferences.HomeSections.Add(new HomeSection { Order = order, Type = type }); } foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase))) { - var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, Guid.Parse(key.Substring("landing-".Length)), existingDisplayPreferences.Client); - itemPreferences.ViewType = Enum.Parse<ViewType>(displayPreferences.ViewType); + if (Guid.TryParse(key.Substring("landing-".Length), out var preferenceId)) + { + var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, preferenceId, existingDisplayPreferences.Client); + itemPreferences.ViewType = Enum.Parse<ViewType>(displayPreferences.ViewType); + displayPreferences.CustomPrefs.Remove(key); + } } var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, Guid.Empty, existingDisplayPreferences.Client); @@ -169,6 +199,8 @@ namespace Jellyfin.Api.Controllers itemPrefs.ViewType = viewType; } + // Set all remaining custom preferences. + _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs); _displayPreferencesManager.SaveChanges(); return NoContent(); diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs new file mode 100644 index 0000000000..452d933eba --- /dev/null +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -0,0 +1,80 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Jellyfin.Data.Entities +{ + /// <summary> + /// An entity that represents a user's custom display preferences for a specific item. + /// </summary> + public class CustomItemDisplayPreferences + { + /// <summary> + /// Initializes a new instance of the <see cref="CustomItemDisplayPreferences"/> class. + /// </summary> + /// <param name="userId">The user id.</param> + /// <param name="client">The client.</param> + /// <param name="preferenceKey">The preference key.</param> + /// <param name="preferenceValue">The preference value.</param> + public CustomItemDisplayPreferences(Guid userId, string client, string preferenceKey, string preferenceValue) + { + UserId = userId; + Client = client; + Key = preferenceKey; + Value = preferenceValue; + } + + /// <summary> + /// Initializes a new instance of the <see cref="CustomItemDisplayPreferences"/> class. + /// </summary> + protected CustomItemDisplayPreferences() + { + } + + /// <summary> + /// Gets or sets the Id. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; protected set; } + + /// <summary> + /// Gets or sets the user Id. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + public Guid UserId { get; set; } + + /// <summary> + /// Gets or sets the client string. + /// </summary> + /// <remarks> + /// Required. Max Length = 32. + /// </remarks> + [Required] + [MaxLength(32)] + [StringLength(32)] + public string Client { get; set; } + + /// <summary> + /// Gets or sets the preference key. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + [Required] + public string Key { get; set; } + + /// <summary> + /// Gets or sets the preference value. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + [Required] + public string Value { get; set; } + } +} diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index bf8818f8d6..a8aa9b319b 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -34,6 +34,8 @@ namespace Jellyfin.Server.Implementations public virtual DbSet<ItemDisplayPreferences> ItemDisplayPreferences { get; set; } + public virtual DbSet<CustomItemDisplayPreferences> CustomItemDisplayPreferences { get; set; } + public virtual DbSet<Permission> Permissions { get; set; } public virtual DbSet<Preference> Preferences { get; set; } @@ -153,6 +155,14 @@ namespace Jellyfin.Server.Implementations modelBuilder.Entity<DisplayPreferences>() .HasIndex(entity => new { entity.UserId, entity.Client }) .IsUnique(); + + modelBuilder.Entity<CustomItemDisplayPreferences>() + .HasIndex(entity => entity.UserId) + .IsUnique(false); + + modelBuilder.Entity<CustomItemDisplayPreferences>() + .HasIndex(entity => new { entity.UserId, entity.Client, entity.Key }) + .IsUnique(); } } } diff --git a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs new file mode 100644 index 0000000000..ce3e30b599 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs @@ -0,0 +1,516 @@ +#pragma warning disable CS1591 +// <auto-generated /> +using System; +using Jellyfin.Server.Implementations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Jellyfin.Server.Implementations.Migrations +{ + [DbContext(typeof(JellyfinDb))] + [Migration("20201203203707_AddCustomDisplayPreferences")] + partial class AddCustomDisplayPreferences + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("jellyfin") + .HasAnnotation("ProductVersion", "5.0.0"); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("DayOfWeek") + .HasColumnType("INTEGER"); + + b.Property<double>("EndHour") + .HasColumnType("REAL"); + + b.Property<double>("StartHour") + .HasColumnType("REAL"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AccessSchedules"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<DateTime>("DateCreated") + .HasColumnType("TEXT"); + + b.Property<string>("ItemId") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property<int>("LogSeverity") + .HasColumnType("INTEGER"); + + b.Property<string>("Name") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<string>("Overview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<string>("ShortOverview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<string>("Type") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ActivityLogs"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.CustomItemDisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<string>("Key") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<string>("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "Client", "Key") + .IsUnique(); + + b.ToTable("CustomItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("ChromecastVersion") + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<string>("DashboardTheme") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<bool>("EnableNextVideoInfoOverlay") + .HasColumnType("INTEGER"); + + b.Property<int?>("IndexBy") + .HasColumnType("INTEGER"); + + b.Property<int>("ScrollDirection") + .HasColumnType("INTEGER"); + + b.Property<bool>("ShowBackdrop") + .HasColumnType("INTEGER"); + + b.Property<bool>("ShowSidebar") + .HasColumnType("INTEGER"); + + b.Property<int>("SkipBackwardLength") + .HasColumnType("INTEGER"); + + b.Property<int>("SkipForwardLength") + .HasColumnType("INTEGER"); + + b.Property<string>("TvHome") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "Client") + .IsUnique(); + + b.ToTable("DisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("DisplayPreferencesId") + .HasColumnType("INTEGER"); + + b.Property<int>("Order") + .HasColumnType("INTEGER"); + + b.Property<int>("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DisplayPreferencesId"); + + b.ToTable("HomeSection"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<DateTime>("LastModified") + .HasColumnType("TEXT"); + + b.Property<string>("Path") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<Guid?>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ImageInfos"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<int?>("IndexBy") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<bool>("RememberIndexing") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberSorting") + .HasColumnType("INTEGER"); + + b.Property<string>("SortBy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property<int>("SortOrder") + .HasColumnType("INTEGER"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<int>("ViewType") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("ItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("Kind") + .HasColumnType("INTEGER"); + + b.Property<Guid?>("Permission_Permissions_Guid") + .HasColumnType("TEXT"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<bool>("Value") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Permission_Permissions_Guid"); + + b.ToTable("Permissions"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("Kind") + .HasColumnType("INTEGER"); + + b.Property<Guid?>("Preference_Preferences_Guid") + .HasColumnType("TEXT"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<string>("Value") + .IsRequired() + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Preference_Preferences_Guid"); + + b.ToTable("Preferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<string>("AudioLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<string>("AuthenticationProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<bool>("DisplayCollectionsView") + .HasColumnType("INTEGER"); + + b.Property<bool>("DisplayMissingEpisodes") + .HasColumnType("INTEGER"); + + b.Property<string>("EasyPassword") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property<bool>("EnableAutoLogin") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableLocalPassword") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableNextEpisodeAutoPlay") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableUserPreferenceAccess") + .HasColumnType("INTEGER"); + + b.Property<bool>("HidePlayedInLatest") + .HasColumnType("INTEGER"); + + b.Property<long>("InternalId") + .HasColumnType("INTEGER"); + + b.Property<int>("InvalidLoginAttemptCount") + .HasColumnType("INTEGER"); + + b.Property<DateTime?>("LastActivityDate") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("LastLoginDate") + .HasColumnType("TEXT"); + + b.Property<int?>("LoginAttemptsBeforeLockout") + .HasColumnType("INTEGER"); + + b.Property<int>("MaxActiveSessions") + .HasColumnType("INTEGER"); + + b.Property<int?>("MaxParentalAgeRating") + .HasColumnType("INTEGER"); + + b.Property<bool>("MustUpdatePassword") + .HasColumnType("INTEGER"); + + b.Property<string>("Password") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property<string>("PasswordResetProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<bool>("PlayDefaultAudioTrack") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberAudioSelections") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberSubtitleSelections") + .HasColumnType("INTEGER"); + + b.Property<int?>("RemoteClientBitrateLimit") + .HasColumnType("INTEGER"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<string>("SubtitleLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<int>("SubtitleMode") + .HasColumnType("INTEGER"); + + b.Property<int>("SyncPlayAccess") + .HasColumnType("INTEGER"); + + b.Property<string>("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("AccessSchedules") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithOne("DisplayPreferences") + .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null) + .WithMany("HomeSections") + .HasForeignKey("DisplayPreferencesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithOne("ProfileImage") + .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("ItemDisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Permissions") + .HasForeignKey("Permission_Permissions_Guid"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Preferences") + .HasForeignKey("Preference_Preferences_Guid"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Navigation("HomeSections"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Navigation("AccessSchedules"); + + b.Navigation("DisplayPreferences") + .IsRequired(); + + b.Navigation("ItemDisplayPreferences"); + + b.Navigation("Permissions"); + + b.Navigation("Preferences"); + + b.Navigation("ProfileImage"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs b/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs new file mode 100644 index 0000000000..a07b265928 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs @@ -0,0 +1,70 @@ +#pragma warning disable CS1591 +// <auto-generated /> +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Jellyfin.Server.Implementations.Migrations +{ + public partial class AddCustomDisplayPreferences : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn<int>( + name: "MaxActiveSessions", + schema: "jellyfin", + table: "Users", + type: "INTEGER", + nullable: false, + defaultValue: 0, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true); + + migrationBuilder.CreateTable( + name: "CustomItemDisplayPreferences", + schema: "jellyfin", + columns: table => new + { + Id = table.Column<int>(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column<Guid>(type: "TEXT", nullable: false), + Client = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false), + Key = table.Column<string>(type: "TEXT", nullable: false), + Value = table.Column<string>(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_CustomItemDisplayPreferences", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_CustomItemDisplayPreferences_UserId", + schema: "jellyfin", + table: "CustomItemDisplayPreferences", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_CustomItemDisplayPreferences_UserId_Client_Key", + schema: "jellyfin", + table: "CustomItemDisplayPreferences", + columns: new[] { "UserId", "Client", "Key" }, + unique: true); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "CustomItemDisplayPreferences", + schema: "jellyfin"); + + migrationBuilder.AlterColumn<int>( + name: "MaxActiveSessions", + schema: "jellyfin", + table: "Users", + type: "INTEGER", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER"); + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs index 16d62f4826..3b85c911cd 100644 --- a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs +++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Migrations #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("jellyfin") - .HasAnnotation("ProductVersion", "3.1.8"); + .HasAnnotation("ProductVersion", "5.0.0"); modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => { @@ -52,33 +52,33 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("TEXT"); b.Property<string>("ItemId") - .HasColumnType("TEXT") - .HasMaxLength(256); + .HasMaxLength(256) + .HasColumnType("TEXT"); b.Property<int>("LogSeverity") .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(512); + .HasMaxLength(512) + .HasColumnType("TEXT"); b.Property<string>("Overview") - .HasColumnType("TEXT") - .HasMaxLength(512); + .HasMaxLength(512) + .HasColumnType("TEXT"); b.Property<uint>("RowVersion") .IsConcurrencyToken() .HasColumnType("INTEGER"); b.Property<string>("ShortOverview") - .HasColumnType("TEXT") - .HasMaxLength(512); + .HasMaxLength(512) + .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(256); + .HasMaxLength(256) + .HasColumnType("TEXT"); b.Property<Guid>("UserId") .HasColumnType("TEXT"); @@ -88,6 +88,38 @@ namespace Jellyfin.Server.Implementations.Migrations b.ToTable("ActivityLogs"); }); + modelBuilder.Entity("Jellyfin.Data.Entities.CustomItemDisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<string>("Key") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<string>("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "Client", "Key") + .IsUnique(); + + b.ToTable("CustomItemDisplayPreferences"); + }); + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => { b.Property<int>("Id") @@ -99,12 +131,12 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("Client") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(32); + .HasMaxLength(32) + .HasColumnType("TEXT"); b.Property<string>("DashboardTheme") - .HasColumnType("TEXT") - .HasMaxLength(32); + .HasMaxLength(32) + .HasColumnType("TEXT"); b.Property<bool>("EnableNextVideoInfoOverlay") .HasColumnType("INTEGER"); @@ -128,8 +160,8 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("INTEGER"); b.Property<string>("TvHome") - .HasColumnType("TEXT") - .HasMaxLength(32); + .HasMaxLength(32) + .HasColumnType("TEXT"); b.Property<Guid>("UserId") .HasColumnType("TEXT"); @@ -177,8 +209,8 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("Path") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(512); + .HasMaxLength(512) + .HasColumnType("TEXT"); b.Property<Guid?>("UserId") .HasColumnType("TEXT"); @@ -199,8 +231,8 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("Client") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(32); + .HasMaxLength(32) + .HasColumnType("TEXT"); b.Property<int?>("IndexBy") .HasColumnType("INTEGER"); @@ -216,8 +248,8 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("SortBy") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(64); + .HasMaxLength(64) + .HasColumnType("TEXT"); b.Property<int>("SortOrder") .HasColumnType("INTEGER"); @@ -279,8 +311,8 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("Value") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(65535); + .HasMaxLength(65535) + .HasColumnType("TEXT"); b.HasKey("Id"); @@ -296,13 +328,13 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("TEXT"); b.Property<string>("AudioLanguagePreference") - .HasColumnType("TEXT") - .HasMaxLength(255); + .HasMaxLength(255) + .HasColumnType("TEXT"); b.Property<string>("AuthenticationProviderId") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); + .HasMaxLength(255) + .HasColumnType("TEXT"); b.Property<bool>("DisplayCollectionsView") .HasColumnType("INTEGER"); @@ -311,8 +343,8 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("INTEGER"); b.Property<string>("EasyPassword") - .HasColumnType("TEXT") - .HasMaxLength(65535); + .HasMaxLength(65535) + .HasColumnType("TEXT"); b.Property<bool>("EnableAutoLogin") .HasColumnType("INTEGER"); @@ -354,13 +386,13 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("INTEGER"); b.Property<string>("Password") - .HasColumnType("TEXT") - .HasMaxLength(65535); + .HasMaxLength(65535) + .HasColumnType("TEXT"); b.Property<string>("PasswordResetProviderId") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); + .HasMaxLength(255) + .HasColumnType("TEXT"); b.Property<bool>("PlayDefaultAudioTrack") .HasColumnType("INTEGER"); @@ -379,8 +411,8 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("INTEGER"); b.Property<string>("SubtitleLanguagePreference") - .HasColumnType("TEXT") - .HasMaxLength(255); + .HasMaxLength(255) + .HasColumnType("TEXT"); b.Property<int>("SubtitleMode") .HasColumnType("INTEGER"); @@ -390,8 +422,8 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<string>("Username") .IsRequired() - .HasColumnType("TEXT") - .HasMaxLength(255); + .HasMaxLength(255) + .HasColumnType("TEXT"); b.HasKey("Id"); @@ -454,6 +486,27 @@ namespace Jellyfin.Server.Implementations.Migrations .WithMany("Preferences") .HasForeignKey("Preference_Preferences_Guid"); }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Navigation("HomeSections"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Navigation("AccessSchedules"); + + b.Navigation("DisplayPreferences") + .IsRequired(); + + b.Navigation("ItemDisplayPreferences"); + + b.Navigation("Permissions"); + + b.Navigation("Preferences"); + + b.Navigation("ProfileImage"); + }); #pragma warning restore 612, 618 } } diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs index 76f9433854..1f3b4ff17d 100644 --- a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs +++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs @@ -66,6 +66,30 @@ namespace Jellyfin.Server.Implementations.Users .ToList(); } + /// <inheritdoc /> + public IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, string client) + { + return _dbContext.CustomItemDisplayPreferences + .AsQueryable() + .Where(prefs => prefs.UserId == userId && string.Equals(prefs.Client, client)) + .ToDictionary(prefs => prefs.Key, prefs => prefs.Value); + } + + /// <inheritdoc /> + public void SetCustomItemDisplayPreferences(Guid userId, string client, Dictionary<string, string> customPreferences) + { + var existingPrefs = _dbContext.CustomItemDisplayPreferences + .AsQueryable() + .Where(prefs => prefs.UserId == userId && string.Equals(prefs.Client, client)); + _dbContext.CustomItemDisplayPreferences.RemoveRange(existingPrefs); + + foreach (var (key, value) in customPreferences) + { + _dbContext.CustomItemDisplayPreferences + .Add(new CustomItemDisplayPreferences(userId, client, key, value)); + } + } + /// <inheritdoc /> public void SaveChanges() { diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index 6658269bdb..97176eb92c 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -40,6 +40,22 @@ namespace MediaBrowser.Controller /// <returns>A list of item display preferences.</returns> IList<ItemDisplayPreferences> ListItemDisplayPreferences(Guid userId, string client); + /// <summary> + /// Gets all of the custom item display preferences for the user and client. + /// </summary> + /// <param name="userId">The user id.</param> + /// <param name="client">The client string.</param> + /// <returns>The dictionary of custom item display preferences.</returns> + IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, string client); + + /// <summary> + /// Sets the custom item display preference for the user and client. + /// </summary> + /// <param name="userId">The user id.</param> + /// <param name="client">The client id.</param> + /// <param name="customPreferences">A dictionary of custom item display preferences.</param> + void SetCustomItemDisplayPreferences(Guid userId, string client, Dictionary<string, string> customPreferences); + /// <summary> /// Saves changes made to the database. /// </summary> From 685c96646849ddfebd47017345595a239a83b58d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 3 Dec 2020 14:35:18 -0700 Subject: [PATCH 0628/1930] Suggestion from review --- Jellyfin.Api/Controllers/DisplayPreferencesController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 27b628774b..e970524d3b 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -87,10 +87,7 @@ namespace Jellyfin.Api.Controllers { foreach (var (key, value) in customDisplayPreferences) { - if (!dto.CustomPrefs.ContainsKey(key)) - { - dto.CustomPrefs[key] = value; - } + dto.CustomPrefs.TryAdd(key, value); } } From cff2b7fed1edb55cf62f723b5ce96ae918f4b049 Mon Sep 17 00:00:00 2001 From: Page Asgardius <hackerman@disroot.org> Date: Thu, 3 Dec 2020 18:29:21 +0000 Subject: [PATCH 0629/1930] Translated using Weblate (Spanish (Mexico)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es_MX/ --- Emby.Server.Implementations/Localization/Core/es-MX.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es-MX.json b/Emby.Server.Implementations/Localization/Core/es-MX.json index ab54c0ea6a..05181116da 100644 --- a/Emby.Server.Implementations/Localization/Core/es-MX.json +++ b/Emby.Server.Implementations/Localization/Core/es-MX.json @@ -113,5 +113,9 @@ "TasksChannelsCategory": "Canales de Internet", "TasksApplicationCategory": "Aplicación", "TasksLibraryCategory": "Biblioteca", - "TasksMaintenanceCategory": "Mantenimiento" + "TasksMaintenanceCategory": "Mantenimiento", + "TaskCleanActivityLogDescription": "Elimina entradas del registro de actividad que sean más antiguas al periodo establecido.", + "TaskCleanActivityLog": "Limpiar registro de actividades", + "Undefined": "Sin definir", + "Forced": "Forzado" } From e765184afa04b4f901f97406bada0cf94bc81605 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 3 Dec 2020 15:00:26 -0700 Subject: [PATCH 0630/1930] Fix existing DisplayPreferences migration --- .../DisplayPreferencesController.cs | 2 +- .../Routines/MigrateDisplayPreferencesDb.cs | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index e970524d3b..7c94880bce 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -177,7 +177,7 @@ namespace Jellyfin.Api.Controllers foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase))) { - if (Guid.TryParse(key.Substring("landing-".Length), out var preferenceId)) + if (Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var preferenceId)) { var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, preferenceId, existingDisplayPreferences.Client); itemPreferences.ViewType = Enum.Parse<ViewType>(displayPreferences.ViewType); diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 8992c281db..7b79184fc0 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -105,6 +105,7 @@ namespace Jellyfin.Server.Migrations.Routines var chromecastVersion = dto.CustomPrefs.TryGetValue("chromecastVersion", out var version) ? chromecastDict[version] : ChromecastVersion.Stable; + dto.CustomPrefs.Remove("chromecastVersion"); var displayPreferences = new DisplayPreferences(dtoUserId, result[2].ToString()) { @@ -126,15 +127,24 @@ namespace Jellyfin.Server.Migrations.Routines TvHome = dto.CustomPrefs.TryGetValue("tvhome", out var home) ? home : string.Empty }; + dto.CustomPrefs.Remove("skipForwardLength"); + dto.CustomPrefs.Remove("skipBackLength"); + dto.CustomPrefs.Remove("enableNextVideoInfoOverlay"); + dto.CustomPrefs.Remove("dashboardtheme"); + dto.CustomPrefs.Remove("tvhome"); + for (int i = 0; i < 7; i++) { - dto.CustomPrefs.TryGetValue("homesection" + i, out var homeSection); + var key = "homesection" + i; + dto.CustomPrefs.TryGetValue(key, out var homeSection); displayPreferences.HomeSections.Add(new HomeSection { Order = i, Type = Enum.TryParse<HomeSectionType>(homeSection, true, out var type) ? type : defaults[i] }); + + dto.CustomPrefs.Remove(key); } var defaultLibraryPrefs = new ItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayPreferences.Client) @@ -167,9 +177,15 @@ namespace Jellyfin.Server.Migrations.Routines libraryDisplayPreferences.ViewType = viewType; } + dto.CustomPrefs.Remove(key); dbContext.ItemDisplayPreferences.Add(libraryDisplayPreferences); } + foreach (var (key, value) in dto.CustomPrefs) + { + dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, displayPreferences.Client, key, value)); + } + dbContext.Add(displayPreferences); } From a9367b616927c9ec0b100bed49be14e3a4c67531 Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Thu, 3 Dec 2020 17:11:53 -0800 Subject: [PATCH 0631/1930] Add OnConfigurationUpdated method --- .../BaseItemManager/BaseItemManager.cs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index c018627b45..085f769d0c 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -27,15 +27,7 @@ namespace MediaBrowser.Controller.BaseItemManager _metadataRefreshConcurrency = GetMetadataRefreshConcurrency(); SetupMetadataThrottler(); - _serverConfigurationManager.ConfigurationUpdated += (object sender, EventArgs e) => - { - int newMetadataRefreshConcurrency = GetMetadataRefreshConcurrency(); - if (_metadataRefreshConcurrency != newMetadataRefreshConcurrency) - { - _metadataRefreshConcurrency = newMetadataRefreshConcurrency; - SetupMetadataThrottler(); - } - }; + _serverConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated; } /// <inheritdoc /> @@ -103,6 +95,20 @@ namespace MediaBrowser.Controller.BaseItemManager return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); } + /// <summary> + /// Called when the configuration is updated. + /// It will refresh the metadata throttler if the relevant config changed. + /// </summary> + private void OnConfigurationUpdated(object sender, EventArgs e) + { + int newMetadataRefreshConcurrency = GetMetadataRefreshConcurrency(); + if (_metadataRefreshConcurrency != newMetadataRefreshConcurrency) + { + _metadataRefreshConcurrency = newMetadataRefreshConcurrency; + SetupMetadataThrottler(); + } + } + /// <summary> /// Creates the metadata refresh throttler. /// </summary> From b7443f6042e8c641be969abafad7202459d2b413 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 3 Dec 2020 20:16:11 -0700 Subject: [PATCH 0632/1930] Optimize FavoritePersons query --- Emby.Server.Implementations/Data/SqliteItemRepository.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 50c7a07d48..f7a6708c91 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -5039,9 +5039,9 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type if (query.User != null && query.IsFavorite.HasValue) { - commandText.Append(" LEFT JOIN TypedBaseItems tbi ON tbi.Name=p.Name AND tbi.Type='"); + commandText.Append(" INNER JOIN TypedBaseItems tbi ON tbi.Name=p.Name AND tbi.Type='"); commandText.Append(typeof(Person).FullName); - commandText.Append("' LEFT JOIN UserDatas ON tbi.UserDataKey=key AND userId=@UserId"); + commandText.Append("' INNER JOIN UserDatas ON tbi.UserDataKey=key AND userId=@UserId"); } var whereClauses = GetPeopleWhereClauses(query, null); From cba1aced8aa3a9471815c6e6db18bc11611dd59f Mon Sep 17 00:00:00 2001 From: jeansebbeaulieu <jsbeaulieu87@gmail.com> Date: Fri, 4 Dec 2020 06:12:44 +0000 Subject: [PATCH 0633/1930] Translated using Weblate (French (Canada)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr_CA/ --- Emby.Server.Implementations/Localization/Core/fr-CA.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr-CA.json b/Emby.Server.Implementations/Localization/Core/fr-CA.json index 3d7592e3c8..5aa65a5257 100644 --- a/Emby.Server.Implementations/Localization/Core/fr-CA.json +++ b/Emby.Server.Implementations/Localization/Core/fr-CA.json @@ -113,5 +113,6 @@ "TaskCleanCache": "Nettoyer le répertoire des fichiers temporaires", "TasksApplicationCategory": "Application", "TaskCleanCacheDescription": "Supprime les fichiers temporaires qui ne sont plus nécessaire pour le système.", - "TasksChannelsCategory": "Canaux Internet" + "TasksChannelsCategory": "Canaux Internet", + "Default": "Par défaut" } From 958c3a32170b6fa62ed1bdd04fd7824139abe9c5 Mon Sep 17 00:00:00 2001 From: Eero Nevaluoto <eero.nevaluoto@gmail.com> Date: Fri, 4 Dec 2020 12:39:04 +0000 Subject: [PATCH 0634/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- Emby.Server.Implementations/Localization/Core/fi.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index 61bef29ed2..954759b5c0 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -114,5 +114,8 @@ "TasksApplicationCategory": "Sovellus", "TasksLibraryCategory": "Kirjasto", "Forced": "Pakotettu", - "Default": "Oletus" + "Default": "Oletus", + "TaskCleanActivityLogDescription": "Poistaa määritettyä vanhemmat tapahtumat aktiviteettilokista.", + "TaskCleanActivityLog": "Tyhjennä aktiviteettiloki", + "Undefined": "Määrittelemätön" } From 60b7e49a7f62e5f1ab06e3c85665f900235f2ff5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 4 Dec 2020 08:00:55 -0700 Subject: [PATCH 0635/1930] Suggestions from code review --- .../Data/SqliteItemRepository.cs | 23 ++++----- Jellyfin.Server/Migrations/MigrationRunner.cs | 3 +- .../Routines/AddPeopleQueryIndex.cs | 49 +++++++++++++++++++ 3 files changed, 61 insertions(+), 14 deletions(-) create mode 100644 Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index f7a6708c91..6e1f2feae4 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -5037,13 +5037,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type var commandText = new StringBuilder("select Distinct p.Name from People p"); - if (query.User != null && query.IsFavorite.HasValue) - { - commandText.Append(" INNER JOIN TypedBaseItems tbi ON tbi.Name=p.Name AND tbi.Type='"); - commandText.Append(typeof(Person).FullName); - commandText.Append("' INNER JOIN UserDatas ON tbi.UserDataKey=key AND userId=@UserId"); - } - var whereClauses = GetPeopleWhereClauses(query, null); if (whereClauses.Count != 0) @@ -5124,6 +5117,16 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type { var whereClauses = new List<string>(); + if (query.User != null && query.IsFavorite.HasValue) + { + whereClauses.Add(@"p.Name IN ( +SELECT Name FROM TypedBaseItems WHERE UserDataKey IN ( +SELECT key FROM UserDatas WHERE isFavorite=@IsFavorite AND userId=@UserId) +AND Type = @InternalPersonType)"); + statement?.TryBind("@IsFavorite", query.IsFavorite.Value); + statement?.TryBind("@InternalPersonType", typeof(Person).FullName); + } + if (!query.ItemId.Equals(Guid.Empty)) { whereClauses.Add("ItemId=@ItemId"); @@ -5176,12 +5179,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type statement?.TryBind("@NameContains", "%" + query.NameContains + "%"); } - if (query.IsFavorite.HasValue) - { - whereClauses.Add("isFavorite=@IsFavorite"); - statement?.TryBind("@IsFavorite", query.IsFavorite.Value); - } - if (query.User != null) { statement?.TryBind("@UserId", query.User.InternalId); diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index aca1654084..305660ae65 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -24,7 +24,8 @@ namespace Jellyfin.Server.Migrations typeof(Routines.MigrateUserDb), typeof(Routines.ReaddDefaultPluginRepository), typeof(Routines.MigrateDisplayPreferencesDb), - typeof(Routines.RemoveDownloadImagesInAdvance) + typeof(Routines.RemoveDownloadImagesInAdvance), + typeof(Routines.AddPeopleQueryIndex) }; /// <summary> diff --git a/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs new file mode 100644 index 0000000000..2521d99527 --- /dev/null +++ b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using MediaBrowser.Controller; +using Microsoft.Extensions.Logging; +using SQLitePCL.pretty; + +namespace Jellyfin.Server.Migrations.Routines +{ + /// <summary> + /// Migration to add table indexes to optimize the Persons query. + /// </summary> + public class AddPeopleQueryIndex : IMigrationRoutine + { + private const string DbFilename = "library.db"; + private readonly ILogger<AddPeopleQueryIndex> _logger; + private readonly IServerApplicationPaths _serverApplicationPaths; + + /// <summary> + /// Initializes a new instance of the <see cref="AddPeopleQueryIndex"/> class. + /// </summary> + /// <param name="logger">Instance of the <see cref="ILogger{AddPeopleQueryIndex}"/> interface.</param> + /// <param name="serverApplicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param> + public AddPeopleQueryIndex(ILogger<AddPeopleQueryIndex> logger, IServerApplicationPaths serverApplicationPaths) + { + _logger = logger; + _serverApplicationPaths = serverApplicationPaths; + } + + /// <inheritdoc /> + public Guid Id => new Guid("DE009B59-BAAE-428D-A810-F67762DC05B8"); + + /// <inheritdoc /> + public string Name => "AddPeopleQueryIndex"; + + /// <inheritdoc /> + public bool PerformOnNewInstall => true; + + /// <inheritdoc /> + public void Perform() + { + var databasePath = Path.Join(_serverApplicationPaths.DataPath, DbFilename); + using var connection = SQLite3.Open(databasePath, ConnectionFlags.ReadWrite, null); + _logger.LogInformation("Creating index idx_TypedBaseItemsUserDataKeyType"); + connection.Execute("CREATE INDEX idx_TypedBaseItemsUserDataKeyType ON TypedBaseItems(UserDataKey, Type);"); + _logger.LogInformation("Creating index idx_PeopleNameListOrder"); + connection.Execute("CREATE INDEX idx_PeopleNameListOrder ON People(Name, ListOrder);"); + } + } +} \ No newline at end of file From 8d8738835ecc36c6f00157d4131d8200d5dd582a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 4 Dec 2020 09:16:38 -0700 Subject: [PATCH 0636/1930] Use DisplayPreferencesId as ItemId --- Jellyfin.Api/Controllers/DisplayPreferencesController.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 7c94880bce..bf3d23e444 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -47,8 +47,10 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] Guid userId, [FromQuery, Required] string client) { + _ = Guid.TryParse(displayPreferencesId, out var itemId); var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, client); - var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, Guid.Empty, displayPreferences.Client); + var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client); + itemPreferences.ItemId = itemId; var dto = new DisplayPreferencesDto { @@ -125,6 +127,7 @@ namespace Jellyfin.Api.Controllers HomeSectionType.LatestMedia, HomeSectionType.None, }; + _ = Guid.TryParse(displayPreferencesId, out var itemId); var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, client); existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null; existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop; @@ -185,11 +188,12 @@ namespace Jellyfin.Api.Controllers } } - var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, Guid.Empty, existingDisplayPreferences.Client); + var itemPrefs = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, itemId, existingDisplayPreferences.Client); itemPrefs.SortBy = displayPreferences.SortBy; itemPrefs.SortOrder = displayPreferences.SortOrder; itemPrefs.RememberIndexing = displayPreferences.RememberIndexing; itemPrefs.RememberSorting = displayPreferences.RememberSorting; + itemPrefs.ItemId = itemId; if (Enum.TryParse<ViewType>(displayPreferences.ViewType, true, out var viewType)) { From cbf70e7a037f9edb431cf0e0f43b261b9a1cf203 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Fri, 4 Dec 2020 20:15:16 +0100 Subject: [PATCH 0637/1930] Change type of PlaylistItemId to Guid --- Emby.Server.Implementations/SyncPlay/Group.cs | 6 ++-- .../Models/SyncPlayDtos/BufferRequestDto.cs | 4 +-- .../MovePlaylistItemRequestDto.cs | 6 ++-- .../Models/SyncPlayDtos/NextItemRequestDto.cs | 6 ++-- .../SyncPlayDtos/PreviousItemRequestDto.cs | 6 ++-- .../Models/SyncPlayDtos/ReadyRequestDto.cs | 4 +-- .../RemoveFromPlaylistRequestDto.cs | 4 +-- .../SyncPlayDtos/SetPlaylistItemRequestDto.cs | 6 ++-- .../SyncPlay/GroupStates/WaitingGroupState.cs | 8 ++--- .../SyncPlay/IGroupStateContext.cs | 6 ++-- .../PlaybackRequests/BufferGroupRequest.cs | 4 +-- .../MovePlaylistItemGroupRequest.cs | 5 +-- .../PlaybackRequests/NextItemGroupRequest.cs | 5 +-- .../PreviousItemGroupRequest.cs | 5 +-- .../PlaybackRequests/ReadyGroupRequest.cs | 4 +-- .../RemoveFromPlaylistGroupRequest.cs | 6 ++-- .../SetPlaylistItemGroupRequest.cs | 5 +-- .../SyncPlay/Queue/PlayQueueManager.cs | 32 +++++-------------- MediaBrowser.Model/SyncPlay/QueueItem.cs | 6 ++-- MediaBrowser.Model/SyncPlay/SendCommand.cs | 4 +-- 20 files changed, 63 insertions(+), 69 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/Group.cs b/Emby.Server.Implementations/SyncPlay/Group.cs index e32f5e25dc..b5031b708b 100644 --- a/Emby.Server.Implementations/SyncPlay/Group.cs +++ b/Emby.Server.Implementations/SyncPlay/Group.cs @@ -505,7 +505,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool SetPlayingItem(string playlistItemId) + public bool SetPlayingItem(Guid playlistItemId) { var itemFound = PlayQueue.SetPlayingItemByPlaylistId(playlistItemId); @@ -525,7 +525,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool RemoveFromPlayQueue(IReadOnlyList<string> playlistItemIds) + public bool RemoveFromPlayQueue(IReadOnlyList<Guid> playlistItemIds) { var playingItemRemoved = PlayQueue.RemoveFromPlaylist(playlistItemIds); if (playingItemRemoved) @@ -548,7 +548,7 @@ namespace Emby.Server.Implementations.SyncPlay } /// <inheritdoc /> - public bool MoveItemInPlayQueue(string playlistItemId, int newIndex) + public bool MoveItemInPlayQueue(Guid playlistItemId, int newIndex) { return PlayQueue.MovePlaylistItem(playlistItemId, newIndex); } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs index cafc400c9c..479c440840 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/BufferRequestDto.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public BufferRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> @@ -37,6 +37,6 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// Gets or sets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } } } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs index 9e9c0b1eab..3af25f3e3e 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/MovePlaylistItemRequestDto.cs @@ -1,3 +1,5 @@ +using System; + namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> @@ -10,14 +12,14 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public MovePlaylistItemRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> /// Gets or sets the playlist identifier of the item. /// </summary> /// <value>The playlist identifier of the item.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } /// <summary> /// Gets or sets the new position. diff --git a/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs index aa67954e75..f59a93f13d 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/NextItemRequestDto.cs @@ -1,3 +1,5 @@ +using System; + namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> @@ -10,13 +12,13 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public NextItemRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> /// Gets or sets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } } } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs index b23d4dee0a..7fd4a49be2 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/PreviousItemRequestDto.cs @@ -1,3 +1,5 @@ +using System; + namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> @@ -10,13 +12,13 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public PreviousItemRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> /// Gets or sets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } } } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs index 0155d52495..d9c193016a 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/ReadyRequestDto.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public ReadyRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> @@ -37,6 +37,6 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// Gets or sets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } } } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs index facb809fca..e9b2b2cb37 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/RemoveFromPlaylistRequestDto.cs @@ -13,13 +13,13 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public RemoveFromPlaylistRequestDto() { - PlaylistItemIds = Array.Empty<string>(); + PlaylistItemIds = Array.Empty<Guid>(); } /// <summary> /// Gets or sets the playlist identifiers ot the items. /// </summary> /// <value>The playlist identifiers ot the items.</value> - public IReadOnlyList<string> PlaylistItemIds { get; set; } + public IReadOnlyList<Guid> PlaylistItemIds { get; set; } } } diff --git a/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs index 3440858712..b937679fc1 100644 --- a/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs +++ b/Jellyfin.Api/Models/SyncPlayDtos/SetPlaylistItemRequestDto.cs @@ -1,3 +1,5 @@ +using System; + namespace Jellyfin.Api.Models.SyncPlayDtos { /// <summary> @@ -10,13 +12,13 @@ namespace Jellyfin.Api.Models.SyncPlayDtos /// </summary> public SetPlaylistItemRequestDto() { - PlaylistItemId = string.Empty; + PlaylistItemId = Guid.Empty; } /// <summary> /// Gets or sets the playlist identifier of the playing item. /// </summary> /// <value>The playlist identifier of the playing item.</value> - public string PlaylistItemId { get; set; } + public Guid PlaylistItemId { get; set; } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index f5f603c296..c2820604f3 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -329,7 +329,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } // Make sure the client is playing the correct item. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString()); @@ -403,7 +403,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } // Make sure the client is playing the correct item. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("Session {SessionId} reported wrong playlist item in group {GroupId}.", session.Id, context.GroupId.ToString()); @@ -572,7 +572,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates ResumePlaying = true; // Make sure the client knows the playing item, to avoid duplicate requests. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString()); return; @@ -618,7 +618,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates ResumePlaying = true; // Make sure the client knows the playing item, to avoid duplicate requests. - if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId(), StringComparison.OrdinalIgnoreCase)) + if (!request.PlaylistItemId.Equals(context.PlayQueue.GetPlayingItemPlaylistId())) { _logger.LogDebug("Session {SessionId} provided the wrong playlist item for group {GroupId}.", session.Id, context.GroupId.ToString()); return; diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs index 13f1b23169..aa263638aa 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs @@ -158,14 +158,14 @@ namespace MediaBrowser.Controller.SyncPlay /// </summary> /// <param name="playlistItemId">The new playing item identifier.</param> /// <returns><c>true</c> if the play queue has been changed; <c>false</c> if something went wrong.</returns> - bool SetPlayingItem(string playlistItemId); + bool SetPlayingItem(Guid playlistItemId); /// <summary> /// Removes items from the play queue. /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - bool RemoveFromPlayQueue(IReadOnlyList<string> playlistItemIds); + bool RemoveFromPlayQueue(IReadOnlyList<Guid> playlistItemIds); /// <summary> /// Moves an item in the play queue. @@ -173,7 +173,7 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="playlistItemId">The playlist identifier of the item to move.</param> /// <param name="newIndex">The new position.</param> /// <returns><c>true</c> if item has been moved; <c>false</c> if something went wrong.</returns> - bool MoveItemInPlayQueue(string playlistItemId, int newIndex); + bool MoveItemInPlayQueue(Guid playlistItemId, int newIndex); /// <summary> /// Updates the play queue. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index 2981dbbdd6..39e0ec2099 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="positionTicks">The position ticks.</param> /// <param name="isPlaying">Whether the client playback is unpaused.</param> /// <param name="playlistItemId">The playlist item identifier of the playing item.</param> - public BufferGroupRequest(DateTime when, long positionTicks, bool isPlaying, string playlistItemId) + public BufferGroupRequest(DateTime when, long positionTicks, bool isPlaying, Guid playlistItemId) { When = when; PositionTicks = positionTicks; @@ -47,7 +47,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.Buffer; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index efca4ed3ef..7ebf67af1d 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; @@ -14,7 +15,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// </summary> /// <param name="playlistItemId">The playlist identifier of the item.</param> /// <param name="newIndex">The new position.</param> - public MovePlaylistItemGroupRequest(string playlistItemId, int newIndex) + public MovePlaylistItemGroupRequest(Guid playlistItemId, int newIndex) { PlaylistItemId = playlistItemId; NewIndex = newIndex; @@ -24,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playlist identifier of the item. /// </summary> /// <value>The playlist identifier of the item.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <summary> /// Gets the new position. diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs index ab60265a6b..478414137c 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; @@ -13,7 +14,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Initializes a new instance of the <see cref="NextItemGroupRequest"/> class. /// </summary> /// <param name="playlistItemId">The playing item identifier.</param> - public NextItemGroupRequest(string playlistItemId) + public NextItemGroupRequest(Guid playlistItemId) { PlaylistItemId = playlistItemId; } @@ -22,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.NextItem; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs index 445c5fce65..ad3ea5e553 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; @@ -13,7 +14,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Initializes a new instance of the <see cref="PreviousItemGroupRequest"/> class. /// </summary> /// <param name="playlistItemId">The playing item identifier.</param> - public PreviousItemGroupRequest(string playlistItemId) + public PreviousItemGroupRequest(Guid playlistItemId) { PlaylistItemId = playlistItemId; } @@ -22,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playing item identifier. /// </summary> /// <value>The playing item identifier.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.PreviousItem; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index b09db4ba80..b2efcc97df 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <param name="positionTicks">The position ticks.</param> /// <param name="isPlaying">Whether the client playback is unpaused.</param> /// <param name="playlistItemId">The playlist item identifier of the playing item.</param> - public ReadyGroupRequest(DateTime when, long positionTicks, bool isPlaying, string playlistItemId) + public ReadyGroupRequest(DateTime when, long positionTicks, bool isPlaying, Guid playlistItemId) { When = when; PositionTicks = positionTicks; @@ -47,7 +47,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playlist item identifier of the playing item. /// </summary> /// <value>The playlist item identifier.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.Ready; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index dac1914aa7..24009d93ca 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -15,16 +15,16 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Initializes a new instance of the <see cref="RemoveFromPlaylistGroupRequest"/> class. /// </summary> /// <param name="items">The playlist ids of the items to remove.</param> - public RemoveFromPlaylistGroupRequest(IReadOnlyList<string> items) + public RemoveFromPlaylistGroupRequest(IReadOnlyList<Guid> items) { - PlaylistItemIds = items ?? Array.Empty<string>(); + PlaylistItemIds = items ?? Array.Empty<Guid>(); } /// <summary> /// Gets the playlist identifiers ot the items. /// </summary> /// <value>The playlist identifiers ot the items.</value> - public IReadOnlyList<string> PlaylistItemIds { get; } + public IReadOnlyList<Guid> PlaylistItemIds { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.RemoveFromPlaylist; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index 58fed3fa07..3edf9b8a42 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; @@ -13,7 +14,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Initializes a new instance of the <see cref="SetPlaylistItemGroupRequest"/> class. /// </summary> /// <param name="playlistItemId">The playlist identifier of the item.</param> - public SetPlaylistItemGroupRequest(string playlistItemId) + public SetPlaylistItemGroupRequest(Guid playlistItemId) { PlaylistItemId = playlistItemId; } @@ -22,7 +23,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// Gets the playlist identifier of the playing item. /// </summary> /// <value>The playlist identifier of the playing item.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <inheritdoc /> public override PlaybackRequestType Action { get; } = PlaybackRequestType.SetPlaylistItem; diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index bfb9d1e4c1..fdec29417e 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -66,12 +66,6 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// <value>The shuffled playlist, or play queue of the group.</value> private List<QueueItem> ShuffledPlaylist { get; set; } = new List<QueueItem>(); - /// <summary> - /// Gets or sets the progressive identifier counter. - /// </summary> - /// <value>The progressive identifier.</value> - private int ProgressiveId { get; set; } - /// <summary> /// Checks if an item is playing. /// </summary> @@ -233,10 +227,10 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// Gets playlist identifier of the playing item, if any. /// </summary> /// <returns>The playlist identifier of the playing item.</returns> - public string GetPlayingItemPlaylistId() + public Guid GetPlayingItemPlaylistId() { var playingItem = GetPlayingItem(); - return playingItem?.PlaylistItemId; + return playingItem?.PlaylistItemId ?? Guid.Empty; } /// <summary> @@ -265,10 +259,10 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// </summary> /// <param name="playlistItemId">The new playing item identifier.</param> /// <returns><c>true</c> if playing item has been set; <c>false</c> if item is not in the playlist.</returns> - public bool SetPlayingItemByPlaylistId(string playlistItemId) + public bool SetPlayingItemByPlaylistId(Guid playlistItemId) { var playlist = GetPlaylistInternal(); - PlayingItemIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)); + PlayingItemIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId)); LastChange = DateTime.UtcNow; return PlayingItemIndex != NoPlayingItemIndex; @@ -298,7 +292,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// </summary> /// <param name="playlistItemIds">The items to remove.</param> /// <returns><c>true</c> if playing item got removed; <c>false</c> otherwise.</returns> - public bool RemoveFromPlaylist(IReadOnlyList<string> playlistItemIds) + public bool RemoveFromPlaylist(IReadOnlyList<Guid> playlistItemIds) { var playingItem = GetPlayingItem(); @@ -341,12 +335,12 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// <param name="playlistItemId">The item to move.</param> /// <param name="newIndex">The new position.</param> /// <returns><c>true</c> if the item has been moved; <c>false</c> otherwise.</returns> - public bool MovePlaylistItem(string playlistItemId, int newIndex) + public bool MovePlaylistItem(Guid playlistItemId, int newIndex) { var playlist = GetPlaylistInternal(); var playingItem = GetPlayingItem(); - var oldIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId, StringComparison.OrdinalIgnoreCase)); + var oldIndex = playlist.FindIndex(item => item.PlaylistItemId.Equals(playlistItemId)); if (oldIndex < 0) { return false; @@ -367,7 +361,6 @@ namespace MediaBrowser.Controller.SyncPlay.Queue /// </summary> public void Reset() { - ProgressiveId = 0; SortedPlaylist.Clear(); ShuffledPlaylist.Clear(); PlayingItemIndex = NoPlayingItemIndex; @@ -529,15 +522,6 @@ namespace MediaBrowser.Controller.SyncPlay.Queue } } - /// <summary> - /// Gets the next available identifier. - /// </summary> - /// <returns>The next available identifier.</returns> - private int GetNextProgressiveId() - { - return ProgressiveId++; - } - /// <summary> /// Creates a list from the array of items. Each item is given an unique playlist identifier. /// </summary> @@ -547,7 +531,7 @@ namespace MediaBrowser.Controller.SyncPlay.Queue var list = new List<QueueItem>(); foreach (var item in items) { - var queueItem = new QueueItem(item, "syncPlayItem" + GetNextProgressiveId()); + var queueItem = new QueueItem(item); list.Add(queueItem); } diff --git a/MediaBrowser.Model/SyncPlay/QueueItem.cs b/MediaBrowser.Model/SyncPlay/QueueItem.cs index 9c4d3a4ceb..a6dcc109ed 100644 --- a/MediaBrowser.Model/SyncPlay/QueueItem.cs +++ b/MediaBrowser.Model/SyncPlay/QueueItem.cs @@ -11,11 +11,9 @@ namespace MediaBrowser.Model.SyncPlay /// Initializes a new instance of the <see cref="QueueItem"/> class. /// </summary> /// <param name="itemId">The item identifier.</param> - /// <param name="playlistItemId">The playlist identifier of the item.</param> - public QueueItem(Guid itemId, string playlistItemId) + public QueueItem(Guid itemId) { ItemId = itemId; - PlaylistItemId = playlistItemId; } /// <summary> @@ -28,6 +26,6 @@ namespace MediaBrowser.Model.SyncPlay /// Gets the playlist identifier of the item. /// </summary> /// <value>The playlist identifier of the item.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } = Guid.NewGuid(); } } diff --git a/MediaBrowser.Model/SyncPlay/SendCommand.cs b/MediaBrowser.Model/SyncPlay/SendCommand.cs index ab4c64130c..73cb50876d 100644 --- a/MediaBrowser.Model/SyncPlay/SendCommand.cs +++ b/MediaBrowser.Model/SyncPlay/SendCommand.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Model.SyncPlay /// <param name="command">The command.</param> /// <param name="positionTicks">The position ticks, for commands that require it.</param> /// <param name="emittedAt">The UTC time when this command has been emitted.</param> - public SendCommand(Guid groupId, string playlistItemId, DateTime when, SendCommandType command, long? positionTicks, DateTime emittedAt) + public SendCommand(Guid groupId, Guid playlistItemId, DateTime when, SendCommandType command, long? positionTicks, DateTime emittedAt) { GroupId = groupId; PlaylistItemId = playlistItemId; @@ -36,7 +36,7 @@ namespace MediaBrowser.Model.SyncPlay /// Gets the playlist identifier of the playing item. /// </summary> /// <value>The playlist identifier of the playing item.</value> - public string PlaylistItemId { get; } + public Guid PlaylistItemId { get; } /// <summary> /// Gets or sets the UTC time when to execute the command. From 1f57b594e6f724e99b614326d207884d6e18439d Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Fri, 4 Dec 2020 21:27:25 +0100 Subject: [PATCH 0638/1930] Loosen locking logic in SyncPlayManager --- .../SyncPlay/SyncPlayManager.cs | 337 ++++++++---------- 1 file changed, 143 insertions(+), 194 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index b2422f8e6e..e43f5c2c31 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -1,7 +1,7 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; -using Jellyfin.Data.Enums; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay; @@ -44,31 +44,23 @@ namespace Emby.Server.Implementations.SyncPlay /// <summary> /// The map between sessions and groups. /// </summary> - private readonly Dictionary<string, Group> _sessionToGroupMap = - new Dictionary<string, Group>(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary<string, Group> _sessionToGroupMap = + new ConcurrentDictionary<string, Group>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The groups. /// </summary> - private readonly Dictionary<Guid, Group> _groups = - new Dictionary<Guid, Group>(); + private readonly ConcurrentDictionary<Guid, Group> _groups = + new ConcurrentDictionary<Guid, Group>(); /// <summary> - /// Lock used for accessing any group. + /// Lock used for accessing multiple groups at once. /// </summary> /// <remarks> - /// Always lock before <see cref="_mapsLock"/> and before locking on any <see cref="Group"/>. + /// This lock has priority on locks made on <see cref="Group"/>. /// </remarks> private readonly object _groupsLock = new object(); - /// <summary> - /// Lock used for accessing the session-to-group map. - /// </summary> - /// <remarks> - /// Always lock after <see cref="_groupsLock"/> and before locking on any <see cref="Group"/>. - /// </remarks> - private readonly object _mapsLock = new object(); - private bool _disposed = false; /// <summary> @@ -102,31 +94,51 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void NewGroup(SessionInfo session, NewGroupRequest request, CancellationToken cancellationToken) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (request == null) + { + throw new InvalidOperationException("Request is null!"); + } + // Locking required to access list of groups. lock (_groupsLock) { - // Locking required as session-to-group map will be edited. - // Locking the group is not required as it is not visible yet. - lock (_mapsLock) + // Make sure that session has not joined another group. + if (_sessionToGroupMap.ContainsKey(session.Id)) { - if (IsSessionInGroup(session)) - { - var leaveGroupRequest = new LeaveGroupRequest(); - LeaveGroup(session, leaveGroupRequest, cancellationToken); - } - - var group = new Group(_loggerFactory, _userManager, _sessionManager, _libraryManager); - _groups[group.GroupId] = group; - - AddSessionToGroup(session, group); - group.CreateGroup(session, request, cancellationToken); + var leaveGroupRequest = new LeaveGroupRequest(); + LeaveGroup(session, leaveGroupRequest, cancellationToken); } + + var group = new Group(_loggerFactory, _userManager, _sessionManager, _libraryManager); + _groups[group.GroupId] = group; + + if (!_sessionToGroupMap.TryAdd(session.Id, group)) + { + throw new InvalidOperationException("Could not add session to group!"); + } + + group.CreateGroup(session, request, cancellationToken); } } /// <inheritdoc /> public void JoinGroup(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (request == null) + { + throw new InvalidOperationException("Request is null!"); + } + var user = _userManager.GetUserById(session.UserId); // Locking required to access list of groups. @@ -143,37 +155,37 @@ namespace Emby.Server.Implementations.SyncPlay return; } - // Locking required as session-to-group map will be edited. - lock (_mapsLock) + // Group lock required to let other requests end first. + lock (group) { - // Group lock required to let other requests end first. - lock (group) + if (!group.HasAccessToPlayQueue(user)) { - if (!group.HasAccessToPlayQueue(user)) - { - _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString()); + _logger.LogWarning("Session {SessionId} tried to join group {GroupId} but does not have access to some content of the playing queue.", session.Id, group.GroupId.ToString()); - var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + var error = new GroupUpdate<string>(group.GroupId, GroupUpdateType.LibraryAccessDenied, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return; + } + + if (_sessionToGroupMap.TryGetValue(session.Id, out var existingGroup)) + { + if (existingGroup.GroupId.Equals(request.GroupId)) + { + // Restore session. + group.SessionJoin(session, request, cancellationToken); return; } - if (IsSessionInGroup(session)) - { - if (FindJoinedGroupId(session).Equals(request.GroupId)) - { - // Restore session. - group.SessionJoin(session, request, cancellationToken); - return; - } - - var leaveGroupRequest = new LeaveGroupRequest(); - LeaveGroup(session, leaveGroupRequest, cancellationToken); - } - - AddSessionToGroup(session, group); - group.SessionJoin(session, request, cancellationToken); + var leaveGroupRequest = new LeaveGroupRequest(); + LeaveGroup(session, leaveGroupRequest, cancellationToken); } + + if (!_sessionToGroupMap.TryAdd(session.Id, group)) + { + throw new InvalidOperationException("Could not add session to group!"); + } + + group.SessionJoin(session, request, cancellationToken); } } } @@ -181,26 +193,36 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (request == null) + { + throw new InvalidOperationException("Request is null!"); + } + // Locking required to access list of groups. lock (_groupsLock) { - // Locking required as session-to-group map will be edited. - lock (_mapsLock) + if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) { - var group = FindJoinedGroup(session); - if (group == null) - { - _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); - - var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); - _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return; - } - // Group lock required to let other requests end first. lock (group) { - RemoveSessionFromGroup(session, group); + if (_sessionToGroupMap.TryRemove(session.Id, out var tempGroup)) + { + if (!tempGroup.GroupId.Equals(group.GroupId)) + { + throw new InvalidOperationException("Session was in wrong group!"); + } + } + else + { + throw new InvalidOperationException("Could not remove session from group!"); + } + group.SessionLeave(session, request, cancellationToken); if (group.IsGroupEmpty()) @@ -210,27 +232,41 @@ namespace Emby.Server.Implementations.SyncPlay } } } + else + { + _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); + + var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); + _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); + return; + } } } /// <inheritdoc /> public List<GroupInfoDto> ListGroups(SessionInfo session, ListGroupsRequest request) { + if (session == null) + { + throw new InvalidOperationException("Session is null!"); + } + + if (request == null) + { + throw new InvalidOperationException("Request is null!"); + } + var user = _userManager.GetUserById(session.UserId); List<GroupInfoDto> list = new List<GroupInfoDto>(); - // Locking required to access list of groups. - lock (_groupsLock) + foreach (var group in _groups.Values) { - foreach (var group in _groups.Values) + // Locking required as group is not thread-safe. + lock (group) { - // Locking required as group is not thread-safe. - lock (group) + if (group.HasAccessToPlayQueue(user)) { - if (group.HasAccessToPlayQueue(user)) - { - list.Add(group.GetInfo()); - } + list.Add(group.GetInfo()); } } } @@ -241,25 +277,43 @@ namespace Emby.Server.Implementations.SyncPlay /// <inheritdoc /> public void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken) { - Group group; - lock (_mapsLock) + if (session == null) { - group = FindJoinedGroup(session); + throw new InvalidOperationException("Session is null!"); } - if (group == null) + if (request == null) + { + throw new InvalidOperationException("Request is null!"); + } + + if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) + { + // Group lock required as Group is not thread-safe. + lock (group) + { + // Make sure that session still belongs to this group. + if (_sessionToGroupMap.TryGetValue(session.Id, out var checkGroup) && !checkGroup.GroupId.Equals(group.GroupId)) + { + // Drop request. + return; + } + + // Drop request if group is empty. + if (group.IsGroupEmpty()) + { + return; + } + + group.HandleRequest(session, request, cancellationToken); + } + } + else { _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); - return; - } - - // Group lock required as Group is not thread-safe. - lock (group) - { - group.HandleRequest(session, request, cancellationToken); } } @@ -282,115 +336,10 @@ namespace Emby.Server.Implementations.SyncPlay { var session = e.SessionInfo; - Guid groupId = Guid.Empty; - lock (_mapsLock) + if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) { - groupId = FindJoinedGroupId(session); - } - - if (groupId.Equals(Guid.Empty)) - { - return; - } - - var request = new JoinGroupRequest(groupId); - JoinGroup(session, request, CancellationToken.None); - } - - /// <summary> - /// Checks if a given session has joined a group. - /// </summary> - /// <remarks> - /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. - /// </remarks> - /// <param name="session">The session.</param> - /// <returns><c>true</c> if the session has joined a group, <c>false</c> otherwise.</returns> - private bool IsSessionInGroup(SessionInfo session) - { - return _sessionToGroupMap.ContainsKey(session.Id); - } - - /// <summary> - /// Gets the group joined by the given session, if any. - /// </summary> - /// <remarks> - /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. - /// </remarks> - /// <param name="session">The session.</param> - /// <returns>The group.</returns> - private Group FindJoinedGroup(SessionInfo session) - { - _sessionToGroupMap.TryGetValue(session.Id, out var group); - return group; - } - - /// <summary> - /// Gets the group identifier joined by the given session, if any. - /// </summary> - /// <remarks> - /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. - /// </remarks> - /// <param name="session">The session.</param> - /// <returns>The group identifier if the session has joined a group, an empty identifier otherwise.</returns> - private Guid FindJoinedGroupId(SessionInfo session) - { - return FindJoinedGroup(session)?.GroupId ?? Guid.Empty; - } - - /// <summary> - /// Maps a session to a group. - /// </summary> - /// <remarks> - /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. - /// </remarks> - /// <param name="session">The session.</param> - /// <param name="group">The group.</param> - /// <exception cref="InvalidOperationException">Thrown when the user is in another group already.</exception> - private void AddSessionToGroup(SessionInfo session, Group group) - { - if (session == null) - { - throw new InvalidOperationException("Session is null!"); - } - - if (IsSessionInGroup(session)) - { - throw new InvalidOperationException("Session in other group already!"); - } - - _sessionToGroupMap[session.Id] = group ?? throw new InvalidOperationException("Group is null!"); - } - - /// <summary> - /// Unmaps a session from a group. - /// </summary> - /// <remarks> - /// Method is not thread-safe, external locking on <see cref="_mapsLock"/> is required. - /// </remarks> - /// <param name="session">The session.</param> - /// <param name="group">The group.</param> - /// <exception cref="InvalidOperationException">Thrown when the user is not found in the specified group.</exception> - private void RemoveSessionFromGroup(SessionInfo session, Group group) - { - if (session == null) - { - throw new InvalidOperationException("Session is null!"); - } - - if (group == null) - { - throw new InvalidOperationException("Group is null!"); - } - - if (!IsSessionInGroup(session)) - { - throw new InvalidOperationException("Session not in any group!"); - } - - _sessionToGroupMap.Remove(session.Id, out var tempGroup); - if (!tempGroup.GroupId.Equals(group.GroupId)) - { - throw new InvalidOperationException("Session was in wrong group!"); + var request = new JoinGroupRequest(group.GroupId); + JoinGroup(session, request, CancellationToken.None); } } } From 23473ef8fb2fb7bb1004f1748d67e0ff03354765 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Fri, 4 Dec 2020 22:03:35 +0100 Subject: [PATCH 0639/1930] Fix access policies to SyncPlay --- Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs | 2 +- Jellyfin.Api/Controllers/SyncPlayController.cs | 2 ++ Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs index 2c3294523f..b5932ea6b4 100644 --- a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs @@ -43,7 +43,7 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy var user = _userManager.GetUserById(userId!.Value); if ((requirement.RequiredAccess.HasValue && user.SyncPlayAccess == requirement.RequiredAccess) - || (user.SyncPlayAccess == SyncPlayAccess.JoinGroups || user.SyncPlayAccess == SyncPlayAccess.CreateAndJoinGroups)) + || user.SyncPlayAccess == SyncPlayAccess.CreateAndJoinGroups) { context.Succeed(requirement); } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 32e020c8ae..471c9180da 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -69,6 +69,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Join")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayAccess)] public ActionResult SyncPlayJoinGroup( [FromBody, Required] JoinGroupRequestDto requestData) { @@ -100,6 +101,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="IEnumerable{GroupInfoView}"/> containing the available SyncPlay groups.</returns> [HttpGet("List")] [ProducesResponseType(StatusCodes.Status200OK)] + [Authorize(Policy = Policies.SyncPlayAccess)] public ActionResult<IEnumerable<GroupInfoDto>> SyncPlayGetGroups() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index cdcc4bb86a..7c4d341df4 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -131,7 +131,7 @@ namespace Jellyfin.Server.Extensions policy => { policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); - policy.AddRequirements(new SyncPlayAccessRequirement()); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccess.JoinGroups)); }); options.AddPolicy( Policies.SyncPlayCreateGroupAccess, From e49bb3f4e65ae6f6e79a44c142a07798711710aa Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 4 Dec 2020 14:12:59 -0700 Subject: [PATCH 0640/1930] Add support for web serving .mem files --- Jellyfin.Server/Startup.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 7f1d332ee9..aa3ef53500 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -133,8 +133,9 @@ namespace Jellyfin.Server { var extensionProvider = new FileExtensionContentTypeProvider(); - // subtitles octopus requires .data files. + // subtitles octopus requires .data, .mem files. extensionProvider.Mappings.Add(".data", MediaTypeNames.Application.Octet); + extensionProvider.Mappings.Add(".mem", MediaTypeNames.Application.Octet); mainApp.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(_serverConfigurationManager.ApplicationPaths.WebPath), From e5304014627d9cd76fc7389a47ee85a34d66ca1d Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Fri, 4 Dec 2020 22:15:00 +0100 Subject: [PATCH 0641/1930] Remove spammy debug line --- Emby.Dlna/PlayTo/PlayToManager.cs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index f34332d622..a6793a7081 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -87,13 +87,10 @@ namespace Emby.Dlna.PlayTo nt = string.Empty; } - string location = info.Location.ToString(); - // It has to report that it's a media renderer if (!usn.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase) && !nt.Contains("MediaRenderer:", StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("Upnp device {0} does not contain a MediaRenderer device (0).", location); return; } @@ -113,7 +110,7 @@ namespace Emby.Dlna.PlayTo return; } - await AddDevice(info, location, cancellationToken).ConfigureAwait(false); + await AddDevice(info, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -160,19 +157,18 @@ namespace Emby.Dlna.PlayTo return tmp.ToString(); } - private async Task AddDevice(UpnpDeviceInfo info, string location, CancellationToken cancellationToken) + private async Task AddDevice(UpnpDeviceInfo info, CancellationToken cancellationToken) { var uri = info.Location; - _logger.LogDebug("Attempting to create PlayToController from location {0}", location); + _logger.LogDebug("Attempting to create PlayToController from location {0}", uri); - _logger.LogDebug("Logging session activity from location {0}", location); if (info.Headers.TryGetValue("USN", out string uuid)) { uuid = GetUuid(uuid); } else { - uuid = location.GetMD5().ToString("N", CultureInfo.InvariantCulture); + uuid = uri.ToString().GetMD5().ToString("N", CultureInfo.InvariantCulture); } var sessionInfo = _sessionManager.LogSessionActivity("DLNA", _appHost.ApplicationVersionString, uuid, null, uri.OriginalString, null); From cc64ee483d6620319d148ad27dbd1e26d8195ea6 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Fri, 4 Dec 2020 23:16:15 +0100 Subject: [PATCH 0642/1930] Reorder parameters in HandleRequest --- Emby.Server.Implementations/SyncPlay/Group.cs | 10 +++ .../SyncPlay/SyncPlayManager.cs | 1 + .../GroupStates/AbstractGroupState.cs | 40 +++++------ .../SyncPlay/GroupStates/IdleGroupState.cs | 26 +++---- .../SyncPlay/GroupStates/PausedGroupState.cs | 32 ++++----- .../SyncPlay/GroupStates/PlayingGroupState.cs | 32 ++++----- .../SyncPlay/GroupStates/WaitingGroupState.cs | 38 +++++----- .../SyncPlay/IGroupState.cs | 72 +++++++++---------- .../PlaybackRequests/BufferGroupRequest.cs | 2 +- .../IgnoreWaitGroupRequest.cs | 2 +- .../MovePlaylistItemGroupRequest.cs | 2 +- .../PlaybackRequests/NextItemGroupRequest.cs | 2 +- .../PlaybackRequests/PauseGroupRequest.cs | 2 +- .../PlaybackRequests/PingGroupRequest.cs | 2 +- .../PlaybackRequests/PlayGroupRequest.cs | 2 +- .../PreviousItemGroupRequest.cs | 2 +- .../PlaybackRequests/QueueGroupRequest.cs | 2 +- .../PlaybackRequests/ReadyGroupRequest.cs | 2 +- .../RemoveFromPlaylistGroupRequest.cs | 2 +- .../PlaybackRequests/SeekGroupRequest.cs | 2 +- .../SetPlaylistItemGroupRequest.cs | 2 +- .../SetRepeatModeGroupRequest.cs | 2 +- .../SetShuffleModeGroupRequest.cs | 2 +- .../PlaybackRequests/StopGroupRequest.cs | 2 +- .../PlaybackRequests/UnpauseGroupRequest.cs | 2 +- 25 files changed, 148 insertions(+), 137 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/Group.cs b/Emby.Server.Implementations/SyncPlay/Group.cs index b5031b708b..7c2ad2477a 100644 --- a/Emby.Server.Implementations/SyncPlay/Group.cs +++ b/Emby.Server.Implementations/SyncPlay/Group.cs @@ -332,6 +332,16 @@ namespace Emby.Server.Implementations.SyncPlay // and notify clients of state changes. The actual syncing of media playback // happens client side. Clients are aware of the server's time and use it to sync. _logger.LogInformation("Session {SessionId} requested {RequestType} in group {GroupId} that is {StateType}.", session.Id, request.Action, GroupId.ToString(), _state.Type); + + // Apply requested changes to this group given its current state. + // Every request has a slightly different outcome depending on the group's state. + // There are currently four different group states that accomplish different goals: + // - Idle: in this state no media is playing and clients should be idle (playback is stopped). + // - Waiting: in this state the group is waiting for all the clients to be ready to start the playback, + // that is, they've either finished loading the media for the first time or they've finished buffering. + // Once all clients report to be ready the group's state can change to Playing or Paused. + // - Playing: clients have some media loaded and playback is unpaused. + // - Paused: clients have some media loaded but playback is currently paused. request.Apply(this, _state, session, cancellationToken); } diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index e43f5c2c31..348213ee15 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -305,6 +305,7 @@ namespace Emby.Server.Implementations.SyncPlay return; } + // Apply requested changes to group. group.HandleRequest(session, request, cancellationToken); } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index 5e3d4a2528..e3de22db38 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -44,27 +44,27 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates public abstract void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, IGroupPlaybackRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IGroupPlaybackRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(RemoveFromPlaylistGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { var playingItemRemoved = context.RemoveFromPlayQueue(request.PlaylistItemIds); @@ -79,12 +79,12 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates IGroupState idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); var stopRequest = new StopGroupRequest(); - idleState.HandleRequest(context, Type, stopRequest, session, cancellationToken); + idleState.HandleRequest(stopRequest, context, Type, session, cancellationToken); } } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(MovePlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { var result = context.MoveItemInPlayQueue(request.PlaylistItemId, request.NewIndex); @@ -100,7 +100,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(QueueGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { var result = context.AddToPlayQueue(request.ItemIds, request.Mode); @@ -121,55 +121,55 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { UnhandledRequest(request); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(SetRepeatModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { context.SetRepeatMode(request.Mode); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.RepeatMode); @@ -178,7 +178,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(SetShuffleModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { context.SetShuffleMode(request.Mode); var playQueueUpdate = context.GetPlayQueueUpdate(PlayQueueUpdateReason.ShuffleMode); @@ -187,14 +187,14 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(PingGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Collected pings are used to account for network latency when unpausing playback. context.UpdatePing(session, request.Ping); } /// <inheritdoc /> - public virtual void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public virtual void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { context.SetIgnoreGroupWait(session, request.IgnoreWait); } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index 8074d5a96b..12ce6c8f82 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -45,69 +45,69 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { SendStopCommand(context, prevState, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { SendStopCommand(context, prevState, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { SendStopCommand(context, prevState, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { SendStopCommand(context, prevState, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { SendStopCommand(context, prevState, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } private void SendStopCommand(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index 28e5db950d..fba8ba9e2e 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -49,25 +49,25 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); - playingState.HandleRequest(context, Type, request, session, cancellationToken); + playingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { if (!prevState.Equals(Type)) { @@ -98,34 +98,34 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); - idleState.HandleRequest(context, Type, request, session, cancellationToken); + idleState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { if (prevState.Equals(Type)) { @@ -145,21 +145,21 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index 278a0af084..9797b247ce 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -54,16 +54,16 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { if (!prevState.Equals(Type)) { @@ -91,34 +91,34 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var pausedState = new PausedGroupState(LoggerFactory); context.SetState(pausedState); - pausedState.HandleRequest(context, Type, request, session, cancellationToken); + pausedState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); - idleState.HandleRequest(context, Type, request, session, cancellationToken); + idleState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { if (IgnoreBuffering) { @@ -128,11 +128,11 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { if (prevState.Equals(Type)) { @@ -148,21 +148,21 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Change state. var waitingState = new WaitingGroupState(LoggerFactory); context.SetState(waitingState); - waitingState.HandleRequest(context, Type, request, session, cancellationToken); + waitingState.HandleRequest(request, context, Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index c2820604f3..507573653f 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -108,7 +108,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); - playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); + playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken); } else { @@ -122,7 +122,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -160,7 +160,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -198,7 +198,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -236,7 +236,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates IgnoreBuffering = true }; context.SetState(playingState); - playingState.HandleRequest(context, Type, request, session, cancellationToken); + playingState.HandleRequest(request, context, Type, session, cancellationToken); } else { @@ -250,7 +250,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -267,7 +267,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -279,11 +279,11 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Change state. var idleState = new IdleGroupState(LoggerFactory); context.SetState(idleState); - idleState.HandleRequest(context, Type, request, session, cancellationToken); + idleState.HandleRequest(request, context, Type, session, cancellationToken); } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -319,7 +319,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -393,7 +393,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -511,7 +511,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates // Change state. var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); - playingState.HandleRequest(context, Type, request, session, cancellationToken); + playingState.HandleRequest(request, context, Type, session, cancellationToken); } } else @@ -548,19 +548,19 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates if (InitialState.Equals(GroupStateType.Playing)) { // Group went from playing to waiting state and a pause request occured while waiting. - var pauserequest = new PauseGroupRequest(); - pausedState.HandleRequest(context, Type, pauserequest, session, cancellationToken); + var pauseRequest = new PauseGroupRequest(); + pausedState.HandleRequest(pauseRequest, context, Type, session, cancellationToken); } else if (InitialState.Equals(GroupStateType.Paused)) { - pausedState.HandleRequest(context, Type, request, session, cancellationToken); + pausedState.HandleRequest(request, context, Type, session, cancellationToken); } } } } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -606,7 +606,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { // Save state if first event. if (!InitialStateSet) @@ -652,7 +652,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates } /// <inheritdoc /> - public override void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken) + public override void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken) { context.SetIgnoreGroupWait(session, request.IgnoreWait); @@ -666,7 +666,7 @@ namespace MediaBrowser.Controller.SyncPlay.GroupStates var playingState = new PlayingGroupState(LoggerFactory); context.SetState(playingState); var unpauseRequest = new UnpauseGroupRequest(); - playingState.HandleRequest(context, Type, unpauseRequest, session, cancellationToken); + playingState.HandleRequest(unpauseRequest, context, Type, session, cancellationToken); } else { diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs index 89a8e2e2e7..95ee09985f 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -37,181 +37,181 @@ namespace MediaBrowser.Controller.SyncPlay /// <summary> /// Generic handler. Context's state can change. /// </summary> + /// <param name="request">The generic request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The generic request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, IGroupPlaybackRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IGroupPlaybackRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a play request from a session. Context's state can change. /// </summary> + /// <param name="request">The play request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The play request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, PlayGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a set-playlist-item request from a session. Context's state can change. /// </summary> + /// <param name="request">The set-playlist-item request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The set-playlist-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetPlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(SetPlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a remove-items request from a session. Context's state can change. /// </summary> + /// <param name="request">The remove-items request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The remove-items request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, RemoveFromPlaylistGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(RemoveFromPlaylistGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a move-playlist-item request from a session. Context's state should not change. /// </summary> + /// <param name="request">The move-playlist-item request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The move-playlist-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, MovePlaylistItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(MovePlaylistItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a queue request from a session. Context's state should not change. /// </summary> + /// <param name="request">The queue request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The queue request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, QueueGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(QueueGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles an unpause request from a session. Context's state can change. /// </summary> + /// <param name="request">The unpause request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The unpause request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, UnpauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a pause request from a session. Context's state can change. /// </summary> + /// <param name="request">The pause request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The pause request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, PauseGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a stop request from a session. Context's state can change. /// </summary> + /// <param name="request">The stop request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The stop request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, StopGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a seek request from a session. Context's state can change. /// </summary> + /// <param name="request">The seek request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The seek request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, SeekGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a buffer request from a session. Context's state can change. /// </summary> + /// <param name="request">The buffer request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The buffer request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, BufferGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a ready request from a session. Context's state can change. /// </summary> + /// <param name="request">The ready request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The ready request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, ReadyGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a next-item request from a session. Context's state can change. /// </summary> + /// <param name="request">The next-item request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The next-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, NextItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a previous-item request from a session. Context's state can change. /// </summary> + /// <param name="request">The previous-item request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The previous-item request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, PreviousItemGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a set-repeat-mode request from a session. Context's state should not change. /// </summary> + /// <param name="request">The repeat-mode request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The repeat-mode request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetRepeatModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(SetRepeatModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a set-shuffle-mode request from a session. Context's state should not change. /// </summary> + /// <param name="request">The shuffle-mode request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The shuffle-mode request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, SetShuffleModeGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(SetShuffleModeGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Updates the ping of a session. Context's state should not change. /// </summary> + /// <param name="request">The ping request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The ping request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, PingGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(PingGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); /// <summary> /// Handles a ignore-wait request from a session. Context's state can change. /// </summary> + /// <param name="request">The ignore-wait request.</param> /// <param name="context">The context of the state.</param> /// <param name="prevState">The previous state.</param> - /// <param name="request">The ignore-wait request.</param> /// <param name="session">The session.</param> /// <param name="cancellationToken">The cancellation token.</param> - void HandleRequest(IGroupStateContext context, GroupStateType prevState, IgnoreWaitGroupRequest request, SessionInfo session, CancellationToken cancellationToken); + void HandleRequest(IgnoreWaitGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index 39e0ec2099..11cc99fcda 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs index a375895ad0..64ef791ed7 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index 7ebf67af1d..9cd8da5668 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -39,7 +39,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs index 478414137c..e0ae0deb76 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs index 8ce2b1fc80..2869b35f77 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs index 19c940cdf8..8ef3b20303 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index 88e0ebad2b..16f9b40874 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs index ad3ea5e553..166ee08007 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index ba5e3e2327..d4af63b6d4 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -40,7 +40,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index b2efcc97df..74f01cbeaf 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index 24009d93ca..47c06c2227 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs index 41e28467c0..ecaa689ae3 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index 3edf9b8a42..c3451703ed 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs index 6a5ec1d117..51011672ea 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs index fe007c8d89..d7b2504b4b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs index c42e229d1f..ad739213c5 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/StopGroupRequest.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs index b4c1744e95..aaf3d65a84 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/UnpauseGroupRequest.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.SyncPlay.PlaybackRequests /// <inheritdoc /> public override void Apply(IGroupStateContext context, IGroupState state, SessionInfo session, CancellationToken cancellationToken) { - state.HandleRequest(context, state.Type, this, session, cancellationToken); + state.HandleRequest(this, context, state.Type, session, cancellationToken); } } } From 3db6ae91f6aa68a1eaf3da3d385b069bdd7721ee Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 4 Dec 2020 16:00:11 -0700 Subject: [PATCH 0643/1930] Add ItemId to all display preferences --- .../DisplayPreferencesController.cs | 10 ++--- .../Entities/CustomItemDisplayPreferences.cs | 12 +++++- Jellyfin.Data/Entities/DisplayPreferences.cs | 12 +++++- Jellyfin.Data/Jellyfin.Data.csproj | 2 +- Jellyfin.Server.Implementations/JellyfinDb.cs | 4 +- ...5_AddCustomDisplayPreferences.Designer.cs} | 12 ++++-- ...1204223655_AddCustomDisplayPreferences.cs} | 42 ++++++++++++++++++- .../Migrations/JellyfinDbModelSnapshot.cs | 10 ++++- .../Users/DisplayPreferencesManager.cs | 20 +++++---- .../Routines/MigrateDisplayPreferencesDb.cs | 16 +++++-- .../IDisplayPreferencesManager.cs | 9 ++-- 11 files changed, 117 insertions(+), 32 deletions(-) rename Jellyfin.Server.Implementations/Migrations/{20201203203707_AddCustomDisplayPreferences.Designer.cs => 20201204223655_AddCustomDisplayPreferences.Designer.cs} (97%) rename Jellyfin.Server.Implementations/Migrations/{20201203203707_AddCustomDisplayPreferences.cs => 20201204223655_AddCustomDisplayPreferences.cs} (60%) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index bf3d23e444..7e67dfe948 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -48,14 +48,14 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] string client) { _ = Guid.TryParse(displayPreferencesId, out var itemId); - var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, client); + var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client); var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client); itemPreferences.ItemId = itemId; var dto = new DisplayPreferencesDto { Client = displayPreferences.Client, - Id = displayPreferences.UserId.ToString(), + Id = displayPreferences.ItemId.ToString(), ViewType = itemPreferences.ViewType.ToString(), SortBy = itemPreferences.SortBy, SortOrder = itemPreferences.SortOrder, @@ -84,7 +84,7 @@ namespace Jellyfin.Api.Controllers dto.CustomPrefs["tvhome"] = displayPreferences.TvHome; // Load all custom display preferences - var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, displayPreferences.Client); + var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client); if (customDisplayPreferences != null) { foreach (var (key, value) in customDisplayPreferences) @@ -128,7 +128,7 @@ namespace Jellyfin.Api.Controllers }; _ = Guid.TryParse(displayPreferencesId, out var itemId); - var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, client); + var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client); existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null; existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop; existingDisplayPreferences.ShowSidebar = displayPreferences.ShowSidebar; @@ -201,7 +201,7 @@ namespace Jellyfin.Api.Controllers } // Set all remaining custom preferences. - _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs); + _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs); _displayPreferencesManager.SaveChanges(); return NoContent(); diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs index 452d933eba..511e3b281a 100644 --- a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -13,12 +13,14 @@ namespace Jellyfin.Data.Entities /// Initializes a new instance of the <see cref="CustomItemDisplayPreferences"/> class. /// </summary> /// <param name="userId">The user id.</param> + /// <param name="itemId">The item id.</param> /// <param name="client">The client.</param> /// <param name="preferenceKey">The preference key.</param> /// <param name="preferenceValue">The preference value.</param> - public CustomItemDisplayPreferences(Guid userId, string client, string preferenceKey, string preferenceValue) + public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string preferenceKey, string preferenceValue) { UserId = userId; + ItemId = itemId; Client = client; Key = preferenceKey; Value = preferenceValue; @@ -48,6 +50,14 @@ namespace Jellyfin.Data.Entities /// </remarks> public Guid UserId { get; set; } + /// <summary> + /// Gets or sets the id of the associated item. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + public Guid ItemId { get; set; } + /// <summary> /// Gets or sets the client string. /// </summary> diff --git a/Jellyfin.Data/Entities/DisplayPreferences.cs b/Jellyfin.Data/Entities/DisplayPreferences.cs index 701e4df004..1a8ca1da37 100644 --- a/Jellyfin.Data/Entities/DisplayPreferences.cs +++ b/Jellyfin.Data/Entities/DisplayPreferences.cs @@ -17,10 +17,12 @@ namespace Jellyfin.Data.Entities /// Initializes a new instance of the <see cref="DisplayPreferences"/> class. /// </summary> /// <param name="userId">The user's id.</param> + /// <param name="itemId">The item id.</param> /// <param name="client">The client string.</param> - public DisplayPreferences(Guid userId, string client) + public DisplayPreferences(Guid userId, Guid itemId, string client) { UserId = userId; + ItemId = itemId; Client = client; ShowSidebar = false; ShowBackdrop = true; @@ -58,6 +60,14 @@ namespace Jellyfin.Data.Entities /// </remarks> public Guid UserId { get; set; } + /// <summary> + /// Gets or sets the id of the associated item. + /// </summary> + /// <remarks> + /// Required. + /// </remarks> + public Guid ItemId { get; set; } + /// <summary> /// Gets or sets the client string. /// </summary> diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 9ae129d072..89d6f4d9b7 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -29,7 +29,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/> + <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> </ItemGroup> <!-- Code analysers--> diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index a8aa9b319b..7f3f837494 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -153,7 +153,7 @@ namespace Jellyfin.Server.Implementations .IsUnique(false); modelBuilder.Entity<DisplayPreferences>() - .HasIndex(entity => new { entity.UserId, entity.Client }) + .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client }) .IsUnique(); modelBuilder.Entity<CustomItemDisplayPreferences>() @@ -161,7 +161,7 @@ namespace Jellyfin.Server.Implementations .IsUnique(false); modelBuilder.Entity<CustomItemDisplayPreferences>() - .HasIndex(entity => new { entity.UserId, entity.Client, entity.Key }) + .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client, entity.Key }) .IsUnique(); } } diff --git a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs similarity index 97% rename from Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs rename to Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs index ce3e30b599..10663d0655 100644 --- a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.Designer.cs +++ b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.Designer.cs @@ -10,7 +10,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Jellyfin.Server.Implementations.Migrations { [DbContext(typeof(JellyfinDb))] - [Migration("20201203203707_AddCustomDisplayPreferences")] + [Migration("20201204223655_AddCustomDisplayPreferences")] partial class AddCustomDisplayPreferences { protected override void BuildTargetModel(ModelBuilder modelBuilder) @@ -102,6 +102,9 @@ namespace Jellyfin.Server.Implementations.Migrations .HasMaxLength(32) .HasColumnType("TEXT"); + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + b.Property<string>("Key") .IsRequired() .HasColumnType("TEXT"); @@ -117,7 +120,7 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasIndex("UserId"); - b.HasIndex("UserId", "Client", "Key") + b.HasIndex("UserId", "ItemId", "Client", "Key") .IsUnique(); b.ToTable("CustomItemDisplayPreferences"); @@ -147,6 +150,9 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<int?>("IndexBy") .HasColumnType("INTEGER"); + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + b.Property<int>("ScrollDirection") .HasColumnType("INTEGER"); @@ -173,7 +179,7 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasIndex("UserId"); - b.HasIndex("UserId", "Client") + b.HasIndex("UserId", "ItemId", "Client") .IsUnique(); b.ToTable("DisplayPreferences"); diff --git a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs similarity index 60% rename from Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs rename to Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs index a07b265928..fbc0bffa97 100644 --- a/Jellyfin.Server.Implementations/Migrations/20201203203707_AddCustomDisplayPreferences.cs +++ b/Jellyfin.Server.Implementations/Migrations/20201204223655_AddCustomDisplayPreferences.cs @@ -9,6 +9,11 @@ namespace Jellyfin.Server.Implementations.Migrations { protected override void Up(MigrationBuilder migrationBuilder) { + migrationBuilder.DropIndex( + name: "IX_DisplayPreferences_UserId_Client", + schema: "jellyfin", + table: "DisplayPreferences"); + migrationBuilder.AlterColumn<int>( name: "MaxActiveSessions", schema: "jellyfin", @@ -20,6 +25,14 @@ namespace Jellyfin.Server.Implementations.Migrations oldType: "INTEGER", oldNullable: true); + migrationBuilder.AddColumn<Guid>( + name: "ItemId", + schema: "jellyfin", + table: "DisplayPreferences", + type: "TEXT", + nullable: false, + defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); + migrationBuilder.CreateTable( name: "CustomItemDisplayPreferences", schema: "jellyfin", @@ -28,6 +41,7 @@ namespace Jellyfin.Server.Implementations.Migrations Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<Guid>(type: "TEXT", nullable: false), + ItemId = table.Column<Guid>(type: "TEXT", nullable: false), Client = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false), Key = table.Column<string>(type: "TEXT", nullable: false), Value = table.Column<string>(type: "TEXT", nullable: false) @@ -37,6 +51,13 @@ namespace Jellyfin.Server.Implementations.Migrations table.PrimaryKey("PK_CustomItemDisplayPreferences", x => x.Id); }); + migrationBuilder.CreateIndex( + name: "IX_DisplayPreferences_UserId_ItemId_Client", + schema: "jellyfin", + table: "DisplayPreferences", + columns: new[] { "UserId", "ItemId", "Client" }, + unique: true); + migrationBuilder.CreateIndex( name: "IX_CustomItemDisplayPreferences_UserId", schema: "jellyfin", @@ -44,10 +65,10 @@ namespace Jellyfin.Server.Implementations.Migrations column: "UserId"); migrationBuilder.CreateIndex( - name: "IX_CustomItemDisplayPreferences_UserId_Client_Key", + name: "IX_CustomItemDisplayPreferences_UserId_ItemId_Client_Key", schema: "jellyfin", table: "CustomItemDisplayPreferences", - columns: new[] { "UserId", "Client", "Key" }, + columns: new[] { "UserId", "ItemId", "Client", "Key" }, unique: true); } @@ -57,6 +78,16 @@ namespace Jellyfin.Server.Implementations.Migrations name: "CustomItemDisplayPreferences", schema: "jellyfin"); + migrationBuilder.DropIndex( + name: "IX_DisplayPreferences_UserId_ItemId_Client", + schema: "jellyfin", + table: "DisplayPreferences"); + + migrationBuilder.DropColumn( + name: "ItemId", + schema: "jellyfin", + table: "DisplayPreferences"); + migrationBuilder.AlterColumn<int>( name: "MaxActiveSessions", schema: "jellyfin", @@ -65,6 +96,13 @@ namespace Jellyfin.Server.Implementations.Migrations nullable: true, oldClrType: typeof(int), oldType: "INTEGER"); + + migrationBuilder.CreateIndex( + name: "IX_DisplayPreferences_UserId_Client", + schema: "jellyfin", + table: "DisplayPreferences", + columns: new[] { "UserId", "Client" }, + unique: true); } } } diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs index 3b85c911cd..1614a88efb 100644 --- a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs +++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs @@ -99,6 +99,9 @@ namespace Jellyfin.Server.Implementations.Migrations .HasMaxLength(32) .HasColumnType("TEXT"); + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + b.Property<string>("Key") .IsRequired() .HasColumnType("TEXT"); @@ -114,7 +117,7 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasIndex("UserId"); - b.HasIndex("UserId", "Client", "Key") + b.HasIndex("UserId", "ItemId", "Client", "Key") .IsUnique(); b.ToTable("CustomItemDisplayPreferences"); @@ -144,6 +147,9 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property<int?>("IndexBy") .HasColumnType("INTEGER"); + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + b.Property<int>("ScrollDirection") .HasColumnType("INTEGER"); @@ -170,7 +176,7 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasIndex("UserId"); - b.HasIndex("UserId", "Client") + b.HasIndex("UserId", "ItemId", "Client") .IsUnique(); b.ToTable("DisplayPreferences"); diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs index 1f3b4ff17d..c8a589cabc 100644 --- a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs +++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs @@ -26,16 +26,16 @@ namespace Jellyfin.Server.Implementations.Users } /// <inheritdoc /> - public DisplayPreferences GetDisplayPreferences(Guid userId, string client) + public DisplayPreferences GetDisplayPreferences(Guid userId, Guid itemId, string client) { var prefs = _dbContext.DisplayPreferences .Include(pref => pref.HomeSections) .FirstOrDefault(pref => - pref.UserId == userId && string.Equals(pref.Client, client)); + pref.UserId == userId && string.Equals(pref.Client, client) && pref.ItemId == itemId); if (prefs == null) { - prefs = new DisplayPreferences(userId, client); + prefs = new DisplayPreferences(userId, itemId, client); _dbContext.DisplayPreferences.Add(prefs); } @@ -67,26 +67,30 @@ namespace Jellyfin.Server.Implementations.Users } /// <inheritdoc /> - public IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, string client) + public IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client) { return _dbContext.CustomItemDisplayPreferences .AsQueryable() - .Where(prefs => prefs.UserId == userId && string.Equals(prefs.Client, client)) + .Where(prefs => prefs.UserId == userId + && prefs.ItemId == itemId + && string.Equals(prefs.Client, client)) .ToDictionary(prefs => prefs.Key, prefs => prefs.Value); } /// <inheritdoc /> - public void SetCustomItemDisplayPreferences(Guid userId, string client, Dictionary<string, string> customPreferences) + public void SetCustomItemDisplayPreferences(Guid userId, Guid itemId, string client, Dictionary<string, string> customPreferences) { var existingPrefs = _dbContext.CustomItemDisplayPreferences .AsQueryable() - .Where(prefs => prefs.UserId == userId && string.Equals(prefs.Client, client)); + .Where(prefs => prefs.UserId == userId + && prefs.ItemId == itemId + && string.Equals(prefs.Client, client)); _dbContext.CustomItemDisplayPreferences.RemoveRange(existingPrefs); foreach (var (key, value) in customPreferences) { _dbContext.CustomItemDisplayPreferences - .Add(new CustomItemDisplayPreferences(userId, client, key, value)); + .Add(new CustomItemDisplayPreferences(userId, itemId, client, key, value)); } } diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 7b79184fc0..1a037053f2 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -8,6 +8,7 @@ using System.Text.Json.Serialization; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Server.Implementations; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; @@ -80,6 +81,7 @@ namespace Jellyfin.Server.Migrations.Routines { "unstable", ChromecastVersion.Unstable } }; + var defaultDisplayPrefsId = "usersettings".GetMD5(); var dbFilePath = Path.Combine(_paths.DataPath, DbFilename); using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null)) { @@ -94,6 +96,12 @@ namespace Jellyfin.Server.Migrations.Routines continue; } + var itemId = new Guid(result[1].ToBlob()); + if (itemId == defaultDisplayPrefsId) + { + itemId = Guid.Empty; + } + var dtoUserId = new Guid(result[1].ToBlob()); var existingUser = _userManager.GetUserById(dtoUserId); if (existingUser == null) @@ -107,7 +115,7 @@ namespace Jellyfin.Server.Migrations.Routines : ChromecastVersion.Stable; dto.CustomPrefs.Remove("chromecastVersion"); - var displayPreferences = new DisplayPreferences(dtoUserId, result[2].ToString()) + var displayPreferences = new DisplayPreferences(dtoUserId, itemId, result[2].ToString()) { IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null, ShowBackdrop = dto.ShowBackdrop, @@ -159,12 +167,12 @@ namespace Jellyfin.Server.Migrations.Routines foreach (var key in dto.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.Ordinal))) { - if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var itemId)) + if (!Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var landingItemId)) { continue; } - var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client) + var libraryDisplayPreferences = new ItemDisplayPreferences(displayPreferences.UserId, landingItemId, displayPreferences.Client) { SortBy = dto.SortBy ?? "SortName", SortOrder = dto.SortOrder, @@ -183,7 +191,7 @@ namespace Jellyfin.Server.Migrations.Routines foreach (var (key, value) in dto.CustomPrefs) { - dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, displayPreferences.Client, key, value)); + dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client, key, value)); } dbContext.Add(displayPreferences); diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index 97176eb92c..041eeea62a 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -16,9 +16,10 @@ namespace MediaBrowser.Controller /// This will create the display preferences if it does not exist, but it will not save automatically. /// </remarks> /// <param name="userId">The user's id.</param> + /// <param name="itemId">The item id.</param> /// <param name="client">The client string.</param> /// <returns>The associated display preferences.</returns> - DisplayPreferences GetDisplayPreferences(Guid userId, string client); + DisplayPreferences GetDisplayPreferences(Guid userId, Guid itemId, string client); /// <summary> /// Gets the default item display preferences for the user and client. @@ -44,17 +45,19 @@ namespace MediaBrowser.Controller /// Gets all of the custom item display preferences for the user and client. /// </summary> /// <param name="userId">The user id.</param> + /// <param name="itemId">The item id.</param> /// <param name="client">The client string.</param> /// <returns>The dictionary of custom item display preferences.</returns> - IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, string client); + IDictionary<string, string> ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client); /// <summary> /// Sets the custom item display preference for the user and client. /// </summary> /// <param name="userId">The user id.</param> + /// <param name="itemId">The item id.</param> /// <param name="client">The client id.</param> /// <param name="customPreferences">A dictionary of custom item display preferences.</param> - void SetCustomItemDisplayPreferences(Guid userId, string client, Dictionary<string, string> customPreferences); + void SetCustomItemDisplayPreferences(Guid userId, Guid itemId, string client, Dictionary<string, string> customPreferences); /// <summary> /// Saves changes made to the database. From 76250a88959fa54646b45bbbb412dfeda30d556d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 4 Dec 2020 16:27:31 -0700 Subject: [PATCH 0644/1930] Use md5 Guid for legacy compat --- .../Controllers/DisplayPreferencesController.cs | 13 +++++++++++-- .../Routines/MigrateDisplayPreferencesDb.cs | 6 ------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 7e67dfe948..8b8f63015e 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -6,6 +6,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; using MediaBrowser.Model.Entities; using Microsoft.AspNetCore.Authorization; @@ -47,7 +48,11 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] Guid userId, [FromQuery, Required] string client) { - _ = Guid.TryParse(displayPreferencesId, out var itemId); + if (!Guid.TryParse(displayPreferencesId, out var itemId)) + { + itemId = displayPreferencesId.GetMD5(); + } + var displayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client); var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client); itemPreferences.ItemId = itemId; @@ -127,7 +132,11 @@ namespace Jellyfin.Api.Controllers HomeSectionType.LatestMedia, HomeSectionType.None, }; - _ = Guid.TryParse(displayPreferencesId, out var itemId); + if (!Guid.TryParse(displayPreferencesId, out var itemId)) + { + itemId = displayPreferencesId.GetMD5(); + } + var existingDisplayPreferences = _displayPreferencesManager.GetDisplayPreferences(userId, itemId, client); existingDisplayPreferences.IndexBy = Enum.TryParse<IndexingKind>(displayPreferences.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null; existingDisplayPreferences.ShowBackdrop = displayPreferences.ShowBackdrop; diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 1a037053f2..af4be5a263 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -81,7 +81,6 @@ namespace Jellyfin.Server.Migrations.Routines { "unstable", ChromecastVersion.Unstable } }; - var defaultDisplayPrefsId = "usersettings".GetMD5(); var dbFilePath = Path.Combine(_paths.DataPath, DbFilename); using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null)) { @@ -97,11 +96,6 @@ namespace Jellyfin.Server.Migrations.Routines } var itemId = new Guid(result[1].ToBlob()); - if (itemId == defaultDisplayPrefsId) - { - itemId = Guid.Empty; - } - var dtoUserId = new Guid(result[1].ToBlob()); var existingUser = _userManager.GetUserById(dtoUserId); if (existingUser == null) From 495c0ba1f19968ca293a835e31682f429df9f2bd Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 4 Dec 2020 21:53:48 -0500 Subject: [PATCH 0645/1930] Fix bad do in bump_version --- bump_version | 1 - 1 file changed, 1 deletion(-) diff --git a/bump_version b/bump_version index d2de5a0bdc..8012ec07f1 100755 --- a/bump_version +++ b/bump_version @@ -49,7 +49,6 @@ sed -i "s/${old_version_sed}/${new_version}/g" ${build_file} # update nuget package version for subproject in ${jellyfin_subprojects[@]}; do -do echo ${subproject} # Parse the version from the *.csproj file old_version="$( From 5f2cd11199875fb6c4698b89d235703cda86021f Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 4 Dec 2020 21:55:32 -0500 Subject: [PATCH 0646/1930] Bump version to 10.8.0 for next release --- Emby.Naming/Emby.Naming.csproj | 2 +- Jellyfin.Data/Jellyfin.Data.csproj | 2 +- MediaBrowser.Common/MediaBrowser.Common.csproj | 2 +- MediaBrowser.Controller/MediaBrowser.Controller.csproj | 2 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- SharedVersion.cs | 4 ++-- build.yaml | 2 +- debian/changelog | 6 ++++++ debian/metapackage/jellyfin | 2 +- fedora/jellyfin.spec | 4 +++- 10 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 24c15759d4..b43203e9dd 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -33,7 +33,7 @@ <PropertyGroup> <Authors>Jellyfin Contributors</Authors> <PackageId>Jellyfin.Naming</PackageId> - <VersionPrefix>10.7.0</VersionPrefix> + <VersionPrefix>10.8.0</VersionPrefix> <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> </PropertyGroup> diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 89d6f4d9b7..4496069ab1 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -19,7 +19,7 @@ <PropertyGroup> <Authors>Jellyfin Contributors</Authors> <PackageId>Jellyfin.Data</PackageId> - <VersionPrefix>10.7.0</VersionPrefix> + <VersionPrefix>10.8.0</VersionPrefix> <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> </PropertyGroup> diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index be5e7f5b45..3222466c10 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -8,7 +8,7 @@ <PropertyGroup> <Authors>Jellyfin Contributors</Authors> <PackageId>Jellyfin.Common</PackageId> - <VersionPrefix>10.7.0</VersionPrefix> + <VersionPrefix>10.8.0</VersionPrefix> <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> </PropertyGroup> diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 5f75df54eb..6b1c096acb 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -8,7 +8,7 @@ <PropertyGroup> <Authors>Jellyfin Contributors</Authors> <PackageId>Jellyfin.Controller</PackageId> - <VersionPrefix>10.7.0</VersionPrefix> + <VersionPrefix>10.8.0</VersionPrefix> <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> </PropertyGroup> diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index b86187f9be..c24b9b613b 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -8,7 +8,7 @@ <PropertyGroup> <Authors>Jellyfin Contributors</Authors> <PackageId>Jellyfin.Model</PackageId> - <VersionPrefix>10.7.0</VersionPrefix> + <VersionPrefix>10.8.0</VersionPrefix> <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> </PropertyGroup> diff --git a/SharedVersion.cs b/SharedVersion.cs index d17074fc0d..5e2f151a22 100644 --- a/SharedVersion.cs +++ b/SharedVersion.cs @@ -1,4 +1,4 @@ using System.Reflection; -[assembly: AssemblyVersion("10.7.0")] -[assembly: AssemblyFileVersion("10.7.0")] +[assembly: AssemblyVersion("10.8.0")] +[assembly: AssemblyFileVersion("10.8.0")] diff --git a/build.yaml b/build.yaml index 7c32d955c1..18434ee003 100644 --- a/build.yaml +++ b/build.yaml @@ -1,7 +1,7 @@ --- # We just wrap `build` so this is really it name: "jellyfin" -version: "10.7.0" +version: "10.8.0" packages: - debian.amd64 - debian.arm64 diff --git a/debian/changelog b/debian/changelog index 184143fe9a..430594cac2 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +jellyfin-server (10.8.0-1) unstable; urgency=medium + + * Forthcoming stable release + + -- Jellyfin Packaging Team <packaging@jellyfin.org> Fri, 04 Dec 2020 21:55:12 -0500 + jellyfin-server (10.7.0-1) unstable; urgency=medium * Forthcoming stable release diff --git a/debian/metapackage/jellyfin b/debian/metapackage/jellyfin index 026fcb8217..a9a0ae5b01 100644 --- a/debian/metapackage/jellyfin +++ b/debian/metapackage/jellyfin @@ -5,7 +5,7 @@ Homepage: https://jellyfin.org Standards-Version: 3.9.2 Package: jellyfin -Version: 10.7.0 +Version: 10.8.0 Maintainer: Jellyfin Packaging Team <packaging@jellyfin.org> Depends: jellyfin-server, jellyfin-web Description: Provides the Jellyfin Free Software Media System diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 197126ee56..ebecb701be 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -7,7 +7,7 @@ %endif Name: jellyfin -Version: 10.7.0 +Version: 10.8.0 Release: 1%{?dist} Summary: The Free Software Media System License: GPLv3 @@ -137,6 +137,8 @@ fi %systemd_postun_with_restart jellyfin.service %changelog +* Fri Dec 04 2020 Jellyfin Packaging Team <packaging@jellyfin.org> +- Forthcoming stable release * Mon Jul 27 2020 Jellyfin Packaging Team <packaging@jellyfin.org> - Forthcoming stable release * Mon Mar 23 2020 Jellyfin Packaging Team <packaging@jellyfin.org> From d838a27e6d2f771bfbd31a3af1e410299d7b8bba Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Fri, 4 Dec 2020 22:05:37 -0500 Subject: [PATCH 0647/1930] Make me codeowner of the .ci dir I need to know when stuff changes. --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e902dc7124..e1900d5833 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,3 +1,4 @@ # Joshua must review all changes to deployment and build.sh +.ci/* @joshuaboniface deployment/* @joshuaboniface build.sh @joshuaboniface From c9832bb98afc24ac94f069405b9c3f9bac34d003 Mon Sep 17 00:00:00 2001 From: Anthony Lavado <anthony@lavado.ca> Date: Fri, 4 Dec 2020 22:36:11 -0500 Subject: [PATCH 0648/1930] Fix the NPM publish scope to public --- .ci/azure-pipelines-api-client.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml index 1c447fd977..b85932b0c1 100644 --- a/.ci/azure-pipelines-api-client.yml +++ b/.ci/azure-pipelines-api-client.yml @@ -52,7 +52,7 @@ jobs: - task: Npm@1 displayName: 'Publish stable typescript axios client' inputs: - command: publish + command: publish --access public publishRegistry: useExternalRegistry publishEndpoint: 'jellyfin-bot for NPM' workingDir: ./apiclient/generated/typescript/axios From 599f36f57f1f696913d5252bbe415830d3861f66 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sat, 5 Dec 2020 01:21:52 -0500 Subject: [PATCH 0649/1930] Remove obsolete erroring command This is not required for stable pushes. --- .ci/azure-pipelines-package.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index d478516b83..47477ba602 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -221,12 +221,6 @@ jobs: pathToPublish: $(Build.ArtifactStagingDirectory) artifactName: Jellyfin Nuget Packages - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to stable Nuget feed' - condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') - inputs: - nuGetServiceConnections: 'NugetOrg' - - task: NuGetCommand@2 displayName: 'Push Nuget packages to stable feed' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') From 048de2f3b74f1d3bbbbc372987560bdb31b32e95 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Sat, 5 Dec 2020 07:25:41 +0100 Subject: [PATCH 0650/1930] Fix NPM command in CI --- .ci/azure-pipelines-api-client.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml index b85932b0c1..177f78889c 100644 --- a/.ci/azure-pipelines-api-client.yml +++ b/.ci/azure-pipelines-api-client.yml @@ -52,7 +52,8 @@ jobs: - task: Npm@1 displayName: 'Publish stable typescript axios client' inputs: - command: publish --access public + command: custom + customCommand: publish --access public publishRegistry: useExternalRegistry publishEndpoint: 'jellyfin-bot for NPM' workingDir: ./apiclient/generated/typescript/axios From 41cd4d0a39a73c02b18848acbc7843c8e36d691b Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 5 Dec 2020 10:18:56 +0100 Subject: [PATCH 0651/1930] Clear KnownNetworks and KnownProxies if none are configured explicitly --- .../Extensions/ApiServiceCollectionExtensions.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 618a4e92b4..cf10f3e53d 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -152,11 +152,19 @@ namespace Jellyfin.Server.Extensions .Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; - for (var i = 0; i < knownProxies.Count; i++) + if (knownProxies.Count == 0) { - if (IPAddress.TryParse(knownProxies[i], out var address)) + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + } + else + { + for (var i = 0; i < knownProxies.Count; i++) { - options.KnownProxies.Add(address); + if (IPAddress.TryParse(knownProxies[i], out var address)) + { + options.KnownProxies.Add(address); + } } } }) From ba7a1c8b7b69692b0decae0d746b5e922ebabb33 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sat, 5 Dec 2020 13:54:19 +0100 Subject: [PATCH 0652/1930] Fix MergeVersions endpoint --- Jellyfin.Api/Controllers/VideosController.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index d8bc9df1f5..44dc639523 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Merges videos into a single record. /// </summary> - /// <param name="itemIds">Item id list. This allows multiple, comma delimited.</param> + /// <param name="ids">Item id list. This allows multiple, comma delimited.</param> /// <response code="204">Videos merged.</response> /// <response code="400">Supply at least 2 video ids.</response> /// <returns>A <see cref="NoContentResult"/> indicating success, or a <see cref="BadRequestResult"/> if less than two ids were supplied.</returns> @@ -204,9 +204,9 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] - public async Task<ActionResult> MergeVersions([FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds) + public async Task<ActionResult> MergeVersions([FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids) { - var items = itemIds + var items = ids .Select(i => _libraryManager.GetItemById(i)) .OfType<Video>() .OrderBy(i => i.Id) From 1a44d34f50834003306ffd7b7687d5e9ef20b708 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 5 Dec 2020 16:00:34 +0000 Subject: [PATCH 0653/1930] Update ApiServiceCollectionExtensions.cs --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 74e7bb4b15..4995fe6a3f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -24,6 +24,7 @@ using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; using MediaBrowser.Common.Json; +using MediaBrowser.Common.Net; using MediaBrowser.Model.Entities; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; @@ -171,9 +172,9 @@ namespace Jellyfin.Server.Extensions options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; for (var i = 0; i < knownProxies.Count; i++) { - if (IPAddress.TryParse(knownProxies[i], out var address)) + if (IPHost.TryParse(knownProxies[i], out var host)) { - options.KnownProxies.Add(address); + options.KnownProxies.Add(host.Address); } } }) From abacae4520028bead5436405996d855b8c6743ac Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 5 Dec 2020 16:28:14 +0000 Subject: [PATCH 0654/1930] Update NetworkManager.cs Changed logging type. --- Jellyfin.Networking/Manager/NetworkManager.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 85da927fb4..43f2f7add6 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1314,9 +1314,7 @@ namespace Jellyfin.Networking.Manager return true; } - // Have to return something, so return an internal address - - _logger.LogWarning("{Source}: External request received, however, no WAN interface found.", source); + _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source); return false; } } From 4d56afa712a15716d88b29029e2ec2dc5a895b9d Mon Sep 17 00:00:00 2001 From: rwctrjotovxqqqyqod <rwctrjotovxqqqyqod@wqcefp.com> Date: Sat, 5 Dec 2020 06:14:54 +0000 Subject: [PATCH 0655/1930] Translated using Weblate (French (Canada)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr_CA/ --- Emby.Server.Implementations/Localization/Core/fr-CA.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr-CA.json b/Emby.Server.Implementations/Localization/Core/fr-CA.json index 5aa65a5257..0c19a01524 100644 --- a/Emby.Server.Implementations/Localization/Core/fr-CA.json +++ b/Emby.Server.Implementations/Localization/Core/fr-CA.json @@ -15,8 +15,8 @@ "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes de l'album", - "HeaderContinueWatching": "Continuer à regarder", + "HeaderAlbumArtists": "Artistes", + "HeaderContinueWatching": "Reprendre le visionnement", "HeaderFavoriteAlbums": "Albums favoris", "HeaderFavoriteArtists": "Artistes favoris", "HeaderFavoriteEpisodes": "Épisodes favoris", From 34cd89058aca7e2de4b787730c459565c41b98fc Mon Sep 17 00:00:00 2001 From: Saman Dadmand <saman.dadmand@gmail.com> Date: Sat, 5 Dec 2020 20:42:47 +0000 Subject: [PATCH 0656/1930] Translated using Weblate (Persian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fa/ --- Emby.Server.Implementations/Localization/Core/fa.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fa.json b/Emby.Server.Implementations/Localization/Core/fa.json index 1986decf03..7eb8e36e7e 100644 --- a/Emby.Server.Implementations/Localization/Core/fa.json +++ b/Emby.Server.Implementations/Localization/Core/fa.json @@ -113,5 +113,7 @@ "TasksChannelsCategory": "کانال‌های داخلی", "TasksApplicationCategory": "برنامه", "TasksLibraryCategory": "کتابخانه", - "TasksMaintenanceCategory": "تعمیر" + "TasksMaintenanceCategory": "تعمیر", + "Forced": "اجباری", + "Default": "پیشفرض" } From b9107e847ab0812b6d7809cae88e4ee97a3c26e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Art=C5=ABrs=20J=C4=81nis=20=C5=85ikitins?= <ajnikitins@gmail.com> Date: Sat, 5 Dec 2020 20:20:42 +0000 Subject: [PATCH 0657/1930] Translated using Weblate (Latvian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/lv/ --- Emby.Server.Implementations/Localization/Core/lv.json | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/lv.json b/Emby.Server.Implementations/Localization/Core/lv.json index 5e3acfbe96..4eb11a53b4 100644 --- a/Emby.Server.Implementations/Localization/Core/lv.json +++ b/Emby.Server.Implementations/Localization/Core/lv.json @@ -15,7 +15,7 @@ "NotificationOptionUserLockedOut": "Lietotājs bloķēts", "LabelRunningTimeValue": "Garums: {0}", "Inherit": "Mantot", - "AppDeviceValues": "Lietotne:{0}, Ierīce:{1}", + "AppDeviceValues": "Lietotne: {0}, Ierīce: {1}", "VersionNumber": "Versija {0}", "ValueHasBeenAddedToLibrary": "{0} ir ticis pievienots tavai multvides bibliotēkai", "UserStoppedPlayingItemWithValues": "{0} ir beidzis atskaņot {1} uz {2}", @@ -112,5 +112,10 @@ "TaskRefreshChapterImagesDescription": "Izveido sīktēlus priekš video ar sadaļām.", "TaskCleanCache": "Iztīrīt Kešošanas Mapi", "TasksChannelsCategory": "Interneta Kanāli", - "TasksMaintenanceCategory": "Apkope" + "TasksMaintenanceCategory": "Apkope", + "Forced": "Piespiests", + "TaskCleanActivityLogDescription": "Nodzēš darbību žurnāla ierakstus, kuri ir vecāki par doto vecumu.", + "TaskCleanActivityLog": "Notīrīt Darbību Žurnālu", + "Undefined": "Nenoteikts", + "Default": "Noklusējums" } From a7b461adb472eb4591922e921e683b26ded87251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Art=C5=ABrs=20J=C4=81nis=20=C5=85ikitins?= <ajnikitins@gmail.com> Date: Sun, 6 Dec 2020 12:50:01 +0000 Subject: [PATCH 0658/1930] Translated using Weblate (Latvian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/lv/ --- Emby.Server.Implementations/Localization/Core/lv.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/lv.json b/Emby.Server.Implementations/Localization/Core/lv.json index 4eb11a53b4..a46bdc3ded 100644 --- a/Emby.Server.Implementations/Localization/Core/lv.json +++ b/Emby.Server.Implementations/Localization/Core/lv.json @@ -17,7 +17,7 @@ "Inherit": "Mantot", "AppDeviceValues": "Lietotne: {0}, Ierīce: {1}", "VersionNumber": "Versija {0}", - "ValueHasBeenAddedToLibrary": "{0} ir ticis pievienots tavai multvides bibliotēkai", + "ValueHasBeenAddedToLibrary": "{0} ir ticis pievienots jūsu multvides bibliotēkai", "UserStoppedPlayingItemWithValues": "{0} ir beidzis atskaņot {1} uz {2}", "UserStartedPlayingItemWithValues": "{0} atskaņo {1} uz {2}", "UserPasswordChangedWithName": "Parole nomainīta lietotājam {0}", @@ -95,7 +95,7 @@ "TaskRefreshChapterImages": "Izvilkt Nodaļu Attēlus", "TasksApplicationCategory": "Lietotne", "TasksLibraryCategory": "Bibliotēka", - "TaskDownloadMissingSubtitlesDescription": "Internetā meklē trūkstošus subtitrus pēc metadatu uzstādījumiem.", + "TaskDownloadMissingSubtitlesDescription": "Internetā meklē trūkstošus subtitrus balstoties uz metadatu uzstādījumiem.", "TaskDownloadMissingSubtitles": "Lejupielādēt trūkstošus subtitrus", "TaskRefreshChannelsDescription": "Atjauno interneta kanālu informāciju.", "TaskRefreshChannels": "Atjaunot Kanālus", @@ -103,12 +103,12 @@ "TaskCleanTranscode": "Iztīrīt Trans-kodēšanas Mapi", "TaskUpdatePluginsDescription": "Lejupielādē un uzstāda atjauninājumus paplašinājumiem, kam ir uzstādīta automātiskā atjaunināšana.", "TaskUpdatePlugins": "Atjaunot Paplašinājumus", - "TaskRefreshPeopleDescription": "Atjauno metadatus priekš aktieriem un direktoriem tavā mediju bibliotēkā.", + "TaskRefreshPeopleDescription": "Atjauno metadatus aktieriem un direktoriem jūsu multivides bibliotēkā.", "TaskRefreshPeople": "Atjaunot Cilvēkus", "TaskCleanLogsDescription": "Nodzēš log datnes, kas ir vairāk par {0} dienām vecas.", "TaskCleanLogs": "Iztīrīt Logdatņu Mapi", - "TaskRefreshLibraryDescription": "Skenē tavas mediju bibliotēkas priekš jaunām datnēm un atjauno metadatus.", - "TaskRefreshLibrary": "Skanēt Mediju Bibliotēku", + "TaskRefreshLibraryDescription": "Skenē jūsu multivides bibliotēku, lai atrastu jaunas datnes, un atsvaidzina metadatus.", + "TaskRefreshLibrary": "Skenēt Multivides Bibliotēku", "TaskRefreshChapterImagesDescription": "Izveido sīktēlus priekš video ar sadaļām.", "TaskCleanCache": "Iztīrīt Kešošanas Mapi", "TasksChannelsCategory": "Interneta Kanāli", From eefe87f537641366d44d6bfb4c7fc3b9e9783527 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 6 Dec 2020 09:11:00 -0700 Subject: [PATCH 0659/1930] Remove CustomItemDisplayPreferences unique key collision --- .../Migrations/Routines/MigrateDisplayPreferencesDb.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index af4be5a263..dd005b7f47 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -81,6 +81,7 @@ namespace Jellyfin.Server.Migrations.Routines { "unstable", ChromecastVersion.Unstable } }; + var customDisplayPrefs = new HashSet<string>(); var dbFilePath = Path.Combine(_paths.DataPath, DbFilename); using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null)) { @@ -185,7 +186,13 @@ namespace Jellyfin.Server.Migrations.Routines foreach (var (key, value) in dto.CustomPrefs) { - dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client, key, value)); + // Custom display preferences can have a key collision. + var indexKey = $"{displayPreferences.UserId}|{itemId}|{displayPreferences.Client}|{key}"; + if (!customDisplayPrefs.Contains(indexKey)) + { + dbContext.Add(new CustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client, key, value)); + customDisplayPrefs.Add(indexKey); + } } dbContext.Add(displayPreferences); From 8df2213d6b91085b4bb3982b79592c2faa7a2ab1 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 6 Dec 2020 10:13:08 -0700 Subject: [PATCH 0660/1930] Don't return plugin versions that target newer Jellyfin version --- .../Updates/InstallationManager.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index ef346dd5d6..ce9ffe42b1 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -12,7 +12,6 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; -using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; @@ -190,6 +189,22 @@ namespace Emby.Server.Implementations.Updates continue; } + for (var i = package.versions.Count - 1; i >= 0; i--) + { + // Remove versions with a target abi that is greater then the current application version. + if (Version.TryParse(package.versions[i].targetAbi, out var targetAbi) + && _applicationHost.ApplicationVersion < targetAbi) + { + package.versions.RemoveAt(i); + } + } + + // Don't add a package that doesn't have any compatible versions. + if (package.versions.Count == 0) + { + continue; + } + var existing = FilterPackages(result, package.name, packageGuid).FirstOrDefault(); if (existing != null) { From a0fbf0f539a4d6376b864ff303f2e56c8f4a81e9 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Sun, 6 Dec 2020 22:49:00 +0100 Subject: [PATCH 0661/1930] Only apply series image aspect ratio if episode/season has no primary image --- Emby.Server.Implementations/Dto/DtoService.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index f3e3a6397f..686944a286 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1138,7 +1138,10 @@ namespace Emby.Server.Implementations.Dto if (episodeSeries != null) { dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary); - AttachPrimaryImageAspectRatio(dto, episodeSeries); + if (!dto.ImageTags.ContainsKey(ImageType.Primary)) + { + AttachPrimaryImageAspectRatio(dto, episodeSeries); + } } } @@ -1185,7 +1188,10 @@ namespace Emby.Server.Implementations.Dto if (series != null) { dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary); - AttachPrimaryImageAspectRatio(dto, series); + if (!dto.ImageTags.ContainsKey(ImageType.Primary)) + { + AttachPrimaryImageAspectRatio(dto, series); + } } } } From 0825ce687decbe1ad6bbc3b3e796d3763f3c4447 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 7 Dec 2020 01:04:48 +0100 Subject: [PATCH 0662/1930] Add SessionControllerConnected event --- .../Session/SessionManager.cs | 16 ++++++++++++++++ .../Session/SessionWebSocketListener.cs | 2 ++ .../SyncPlay/SyncPlayManager.cs | 6 +++--- .../Session/ISessionManager.cs | 11 +++++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index b3965fccad..885f65c64e 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -128,6 +128,9 @@ namespace Emby.Server.Implementations.Session /// <inheritdoc /> public event EventHandler<SessionEventArgs> SessionActivity; + /// <inheritdoc /> + public event EventHandler<SessionEventArgs> SessionControllerConnected; + /// <summary> /// Gets all connections. /// </summary> @@ -312,6 +315,19 @@ namespace Emby.Server.Implementations.Session return session; } + /// <inheritdoc /> + public void OnSessionControllerConnected(SessionInfo info) + { + EventHelper.QueueEventIfNotNull( + SessionControllerConnected, + this, + new SessionEventArgs + { + SessionInfo = info + }, + _logger); + } + /// <inheritdoc /> public void CloseIfNeeded(SessionInfo session) { diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 169eaefd8b..39c369a01d 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -133,6 +133,8 @@ namespace Emby.Server.Implementations.Session var controller = (WebSocketController)controllerInfo.Item1; controller.AddWebSocket(connection); + + _sessionManager.OnSessionControllerConnected(session); } /// <summary> diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 348213ee15..1d87036a27 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -81,7 +81,7 @@ namespace Emby.Server.Implementations.SyncPlay _sessionManager = sessionManager; _libraryManager = libraryManager; _logger = loggerFactory.CreateLogger<SyncPlayManager>(); - _sessionManager.SessionStarted += OnSessionManagerSessionStarted; + _sessionManager.SessionControllerConnected += OnSessionControllerConnected; } /// <inheritdoc /> @@ -329,11 +329,11 @@ namespace Emby.Server.Implementations.SyncPlay return; } - _sessionManager.SessionStarted -= OnSessionManagerSessionStarted; + _sessionManager.SessionControllerConnected -= OnSessionControllerConnected; _disposed = true; } - private void OnSessionManagerSessionStarted(object sender, SessionEventArgs e) + private void OnSessionControllerConnected(object sender, SessionEventArgs e) { var session = e.SessionInfo; diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 9ad8557ce6..6c06dcad58 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -46,6 +46,11 @@ namespace MediaBrowser.Controller.Session event EventHandler<SessionEventArgs> SessionActivity; + /// <summary> + /// Occurs when [session controller connected]. + /// </summary> + event EventHandler<SessionEventArgs> SessionControllerConnected; + /// <summary> /// Occurs when [capabilities changed]. /// </summary> @@ -78,6 +83,12 @@ namespace MediaBrowser.Controller.Session /// <param name="user">The user.</param> SessionInfo LogSessionActivity(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Jellyfin.Data.Entities.User user); + /// <summary> + /// Used to report that a session controller has connected. + /// </summary> + /// <param name="session">The session.</param> + void OnSessionControllerConnected(SessionInfo session); + void UpdateDeviceName(string sessionId, string reportedDeviceName); /// <summary> From 391870ebae9085335cb404154e03ad17b0b25d3d Mon Sep 17 00:00:00 2001 From: Patrick Barron <barronpm@gmail.com> Date: Sun, 6 Dec 2020 20:05:55 -0500 Subject: [PATCH 0663/1930] Add required attributes to parameters --- Jellyfin.Api/Controllers/UserController.cs | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 0f7c25d0e4..ff047c68a0 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -267,7 +267,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> UpdateUserPassword( [FromRoute, Required] Guid userId, - [FromBody] UpdateUserPassword request) + [FromBody, Required] UpdateUserPassword request) { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { @@ -325,7 +325,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult UpdateUserEasyPassword( [FromRoute, Required] Guid userId, - [FromBody] UpdateUserEasyPassword request) + [FromBody, Required] UpdateUserEasyPassword request) { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { @@ -367,13 +367,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task<ActionResult> UpdateUser( [FromRoute, Required] Guid userId, - [FromBody] UserDto updateUser) + [FromBody, Required] UserDto updateUser) { - if (updateUser == null) - { - return BadRequest(); - } - if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false)) { return Forbid("User update not allowed."); @@ -407,13 +402,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task<ActionResult> UpdateUserPolicy( [FromRoute, Required] Guid userId, - [FromBody] UserPolicy newPolicy) + [FromBody, Required] UserPolicy newPolicy) { - if (newPolicy == null) - { - return BadRequest(); - } - var user = _userManager.GetUserById(userId); // If removing admin access @@ -462,7 +452,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)] public async Task<ActionResult> UpdateUserConfiguration( [FromRoute, Required] Guid userId, - [FromBody] UserConfiguration userConfig) + [FromBody, Required] UserConfiguration userConfig) { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false)) { @@ -483,7 +473,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("New")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task<ActionResult<UserDto>> CreateUserByName([FromBody] CreateUserByName request) + public async Task<ActionResult<UserDto>> CreateUserByName([FromBody, Required] CreateUserByName request) { var newUser = await _userManager.CreateUserAsync(request.Name).ConfigureAwait(false); From d65e8d70442ecc2c03372abf5f81c65c6ab189a6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 6 Dec 2020 19:40:43 -0700 Subject: [PATCH 0664/1930] Redirect robots.txt if hosting web content --- .../ApiApplicationBuilderExtensions.cs | 10 ++++ .../Middleware/RobotsRedirectionMiddleware.cs | 47 +++++++++++++++++++ Jellyfin.Server/Startup.cs | 2 + 3 files changed, 59 insertions(+) create mode 100644 Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 6bf6f383fc..a56e159590 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -107,5 +107,15 @@ namespace Jellyfin.Server.Extensions { return appBuilder.UseMiddleware<WebSocketHandlerMiddleware>(); } + + /// <summary> + /// Adds robots.txt redirection to the application pipeline. + /// </summary> + /// <param name="appBuilder">The application builder.</param> + /// <returns>The updated application builder.</returns> + public static IApplicationBuilder UseRobotsRedirection(this IApplicationBuilder appBuilder) + { + return appBuilder.UseMiddleware<RobotsRedirectionMiddleware>(); + } } } diff --git a/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs new file mode 100644 index 0000000000..9d40d74fe9 --- /dev/null +++ b/Jellyfin.Server/Middleware/RobotsRedirectionMiddleware.cs @@ -0,0 +1,47 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Middleware +{ + /// <summary> + /// Redirect requests to robots.txt to web/robots.txt. + /// </summary> + public class RobotsRedirectionMiddleware + { + private readonly RequestDelegate _next; + private readonly ILogger<RobotsRedirectionMiddleware> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="RobotsRedirectionMiddleware"/> class. + /// </summary> + /// <param name="next">The next delegate in the pipeline.</param> + /// <param name="logger">The logger.</param> + public RobotsRedirectionMiddleware( + RequestDelegate next, + ILogger<RobotsRedirectionMiddleware> logger) + { + _next = next; + _logger = logger; + } + + /// <summary> + /// Executes the middleware action. + /// </summary> + /// <param name="httpContext">The current HTTP context.</param> + /// <returns>The async task.</returns> + public async Task Invoke(HttpContext httpContext) + { + var localPath = httpContext.Request.Path.ToString(); + if (string.Equals(localPath, "/robots.txt", StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("Redirecting robots.txt request to web/robots.txt"); + httpContext.Response.Redirect("web/robots.txt"); + return; + } + + await _next(httpContext).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index aa3ef53500..306a52ce8f 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -142,6 +142,8 @@ namespace Jellyfin.Server RequestPath = "/web", ContentTypeProvider = extensionProvider }); + + mainApp.UseRobotsRedirection(); } mainApp.UseAuthentication(); From 66a1880a580b25db7add41ed3947166b10415f37 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 6 Dec 2020 20:26:21 -0700 Subject: [PATCH 0665/1930] Add number to bool json converter --- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +++ .../Converters/JsonBoolNumberConverter.cs | 33 +++++++++++++++++++ .../Json/JsonBoolNumberTests.cs | 23 +++++++++++++ .../Models/BoolTypeModel.cs | 17 ++++++++++ 4 files changed, 77 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs create mode 100644 tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index b6444b172a..0f296d9894 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -8,10 +8,12 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -340,8 +342,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public string URL { get; set; } + [JsonConverter(typeof(JsonBoolNumberConverter))] public bool Favorite { get; set; } + [JsonConverter(typeof(JsonBoolNumberConverter))] public bool DRM { get; set; } public int HD { get; set; } diff --git a/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs new file mode 100644 index 0000000000..f73ca344ca --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a number to a boolean. + /// This is needed for HDHomerun. + /// </summary> + /// <remarks> + /// Adding this to the JsonConverter list causes recursion. + /// </remarks> + public class JsonBoolNumberConverter : JsonConverter<bool> + { + /// <inheritdoc /> + public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Number) + { + return Convert.ToBoolean(reader.GetInt32()); + } + + return JsonSerializer.Deserialize<bool>(ref reader, options); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, value, options); + } + } +} \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs new file mode 100644 index 0000000000..1cae5b8491 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs @@ -0,0 +1,23 @@ +using System.Text.Json; +using Jellyfin.Common.Tests.Models; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public static class JsonBoolNumberTests + { + [Theory] + [InlineData("1", true)] + [InlineData("0", false)] + [InlineData("2", true)] + [InlineData("true", true)] + [InlineData("false", false)] + public static void Deserialize_Number_Valid_Success(string input, bool? output) + { + var inputJson = $"{{ \"Value\": {input} }}"; + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize<BoolTypeModel>(inputJson, options); + Assert.Equal(value?.Value, output); + } + } +} \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs b/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs new file mode 100644 index 0000000000..feb952efc5 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs @@ -0,0 +1,17 @@ +using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; + +namespace Jellyfin.Common.Tests.Models +{ + /// <summary> + /// The bool type model. + /// </summary> + public class BoolTypeModel + { + /// <summary> + /// Gets or sets a value indicating whether the value is true or false. + /// </summary> + [JsonConverter(typeof(JsonBoolNumberConverter))] + public bool Value { get; set; } + } +} \ No newline at end of file From 499f3ee9505437a5b38c315201ccc832561be715 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 7 Dec 2020 10:33:15 +0100 Subject: [PATCH 0666/1930] Update authorization policies for SyncPlay --- .../SyncPlay/SyncPlayManager.cs | 44 +++++++++++++++ .../SyncPlayAccessHandler.cs | 53 +++++++++++++++++-- .../SyncPlayAccessRequirement.cs | 14 ++--- Jellyfin.Api/Constants/Policies.cs | 18 +++++-- .../Controllers/SyncPlayController.cs | 25 +++++++-- Jellyfin.Data/Entities/User.cs | 4 +- .../Enums/SyncPlayAccessRequirementType.cs | 28 ++++++++++ ...layAccess.cs => SyncPlayUserAccessType.cs} | 4 +- .../ApiServiceCollectionExtensions.cs | 22 ++++++-- .../SyncPlay/ISyncPlayManager.cs | 7 +++ MediaBrowser.Model/Users/UserPolicy.cs | 4 +- 11 files changed, 191 insertions(+), 32 deletions(-) create mode 100644 Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs rename Jellyfin.Data/Enums/{SyncPlayAccess.cs => SyncPlayUserAccessType.cs} (85%) diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 348213ee15..2f5dcdf3d6 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -41,6 +41,12 @@ namespace Emby.Server.Implementations.SyncPlay /// </summary> private readonly ILibraryManager _libraryManager; + /// <summary> + /// The map between users and counter of active sessions. + /// </summary> + private readonly ConcurrentDictionary<Guid, int> _activeUsers = + new ConcurrentDictionary<Guid, int>(); + /// <summary> /// The map between sessions and groups. /// </summary> @@ -122,6 +128,7 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Could not add session to group!"); } + UpdateSessionsCounter(session.UserId, 1); group.CreateGroup(session, request, cancellationToken); } } @@ -172,6 +179,7 @@ namespace Emby.Server.Implementations.SyncPlay if (existingGroup.GroupId.Equals(request.GroupId)) { // Restore session. + UpdateSessionsCounter(session.UserId, 1); group.SessionJoin(session, request, cancellationToken); return; } @@ -185,6 +193,7 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Could not add session to group!"); } + UpdateSessionsCounter(session.UserId, 1); group.SessionJoin(session, request, cancellationToken); } } @@ -223,6 +232,7 @@ namespace Emby.Server.Implementations.SyncPlay throw new InvalidOperationException("Could not remove session from group!"); } + UpdateSessionsCounter(session.UserId, -1); group.SessionLeave(session, request, cancellationToken); if (group.IsGroupEmpty()) @@ -318,6 +328,19 @@ namespace Emby.Server.Implementations.SyncPlay } } + /// <inheritdoc /> + public bool IsUserActive(Guid userId) + { + if (_activeUsers.TryGetValue(userId, out var sessionsCounter)) + { + return sessionsCounter > 0; + } + else + { + return false; + } + } + /// <summary> /// Releases unmanaged and optionally managed resources. /// </summary> @@ -343,5 +366,26 @@ namespace Emby.Server.Implementations.SyncPlay JoinGroup(session, request, CancellationToken.None); } } + + private void UpdateSessionsCounter(Guid userId, int toAdd) + { + // Update sessions counter. + var newSessionsCounter = _activeUsers.AddOrUpdate( + userId, + 1, + (key, sessionsCounter) => sessionsCounter + toAdd); + + // Should never happen. + if (newSessionsCounter < 0) + { + throw new InvalidOperationException("Sessions counter is negative!"); + } + + // Clean record if user has no more active sessions. + if (newSessionsCounter == 0) + { + _activeUsers.TryRemove(new KeyValuePair<Guid, int>(userId, newSessionsCounter)); + } + } } } diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs index b5932ea6b4..fd8286b1df 100644 --- a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs @@ -3,6 +3,7 @@ using Jellyfin.Api.Helpers; using Jellyfin.Data.Enums; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.SyncPlay; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -13,20 +14,24 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy /// </summary> public class SyncPlayAccessHandler : BaseAuthorizationHandler<SyncPlayAccessRequirement> { + private readonly ISyncPlayManager _syncPlayManager; private readonly IUserManager _userManager; /// <summary> /// Initializes a new instance of the <see cref="SyncPlayAccessHandler"/> class. /// </summary> + /// <param name="syncPlayManager">Instance of the <see cref="ISyncPlayManager"/> interface.</param> /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param> /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param> public SyncPlayAccessHandler( + ISyncPlayManager syncPlayManager, IUserManager userManager, INetworkManager networkManager, IHttpContextAccessor httpContextAccessor) : base(userManager, networkManager, httpContextAccessor) { + _syncPlayManager = syncPlayManager; _userManager = userManager; } @@ -42,10 +47,52 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy var userId = ClaimHelpers.GetUserId(context.User); var user = _userManager.GetUserById(userId!.Value); - if ((requirement.RequiredAccess.HasValue && user.SyncPlayAccess == requirement.RequiredAccess) - || user.SyncPlayAccess == SyncPlayAccess.CreateAndJoinGroups) + if (requirement.RequiredAccess == SyncPlayAccessRequirementType.HasAccess) { - context.Succeed(requirement); + if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups || + user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups || + _syncPlayManager.IsUserActive(userId!.Value)) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + } + else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.CreateGroup) + { + if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + } + else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.JoinGroup) + { + if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups || + user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + } + else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.IsInGroup) + { + if (_syncPlayManager.IsUserActive(userId!.Value)) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } } else { diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs index 7fcaf69f6e..6fab4c0ad8 100644 --- a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessRequirement.cs @@ -11,23 +11,15 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy /// <summary> /// Initializes a new instance of the <see cref="SyncPlayAccessRequirement"/> class. /// </summary> - /// <param name="requiredAccess">A value of <see cref="SyncPlayAccess"/>.</param> - public SyncPlayAccessRequirement(SyncPlayAccess requiredAccess) + /// <param name="requiredAccess">A value of <see cref="SyncPlayAccessRequirementType"/>.</param> + public SyncPlayAccessRequirement(SyncPlayAccessRequirementType requiredAccess) { RequiredAccess = requiredAccess; } - /// <summary> - /// Initializes a new instance of the <see cref="SyncPlayAccessRequirement"/> class. - /// </summary> - public SyncPlayAccessRequirement() - { - RequiredAccess = null; - } - /// <summary> /// Gets the required SyncPlay access. /// </summary> - public SyncPlayAccess? RequiredAccess { get; } + public SyncPlayAccessRequirementType RequiredAccess { get; } } } diff --git a/Jellyfin.Api/Constants/Policies.cs b/Jellyfin.Api/Constants/Policies.cs index b35ceea1a3..632dedb3cd 100644 --- a/Jellyfin.Api/Constants/Policies.cs +++ b/Jellyfin.Api/Constants/Policies.cs @@ -51,13 +51,23 @@ namespace Jellyfin.Api.Constants public const string FirstTimeSetupOrIgnoreParentalControl = "FirstTimeSetupOrIgnoreParentalControl"; /// <summary> - /// Policy name for requiring access to SyncPlay. + /// Policy name for accessing SyncPlay. /// </summary> - public const string SyncPlayAccess = "SyncPlayAccess"; + public const string SyncPlayHasAccess = "SyncPlayHasAccess"; /// <summary> - /// Policy name for requiring group creation access to SyncPlay. + /// Policy name for creating a SyncPlay group. /// </summary> - public const string SyncPlayCreateGroupAccess = "SyncPlayCreateGroupAccess"; + public const string SyncPlayCreateGroup = "SyncPlayCreateGroup"; + + /// <summary> + /// Policy name for joining a SyncPlay group. + /// </summary> + public const string SyncPlayJoinGroup = "SyncPlayJoinGroup"; + + /// <summary> + /// Policy name for accessing a SyncPlay group. + /// </summary> + public const string SyncPlayIsInGroup = "SyncPlayIsInGroup"; } } diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 471c9180da..82cbe58df2 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -20,7 +20,7 @@ namespace Jellyfin.Api.Controllers /// <summary> /// The sync play controller. /// </summary> - [Authorize(Policy = Policies.SyncPlayAccess)] + [Authorize(Policy = Policies.SyncPlayHasAccess)] public class SyncPlayController : BaseJellyfinApiController { private readonly ISessionManager _sessionManager; @@ -51,7 +51,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("New")] [ProducesResponseType(StatusCodes.Status204NoContent)] - [Authorize(Policy = Policies.SyncPlayCreateGroupAccess)] + [Authorize(Policy = Policies.SyncPlayCreateGroup)] public ActionResult SyncPlayCreateGroup( [FromBody, Required] NewGroupRequestDto requestData) { @@ -69,7 +69,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Join")] [ProducesResponseType(StatusCodes.Status204NoContent)] - [Authorize(Policy = Policies.SyncPlayAccess)] + [Authorize(Policy = Policies.SyncPlayJoinGroup)] public ActionResult SyncPlayJoinGroup( [FromBody, Required] JoinGroupRequestDto requestData) { @@ -86,6 +86,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Leave")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayLeaveGroup() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -101,7 +102,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="IEnumerable{GroupInfoView}"/> containing the available SyncPlay groups.</returns> [HttpGet("List")] [ProducesResponseType(StatusCodes.Status200OK)] - [Authorize(Policy = Policies.SyncPlayAccess)] + [Authorize(Policy = Policies.SyncPlayJoinGroup)] public ActionResult<IEnumerable<GroupInfoDto>> SyncPlayGetGroups() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -117,6 +118,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetNewQueue")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySetNewQueue( [FromBody, Required] PlayRequestDto requestData) { @@ -137,6 +139,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetPlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySetPlaylistItem( [FromBody, Required] SetPlaylistItemRequestDto requestData) { @@ -154,6 +157,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("RemoveFromPlaylist")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayRemoveFromPlaylist( [FromBody, Required] RemoveFromPlaylistRequestDto requestData) { @@ -171,6 +175,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("MovePlaylistItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayMovePlaylistItem( [FromBody, Required] MovePlaylistItemRequestDto requestData) { @@ -188,6 +193,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Queue")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayQueue( [FromBody, Required] QueueRequestDto requestData) { @@ -204,6 +210,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Unpause")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayUnpause() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -219,6 +226,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Pause")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayPause() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -234,6 +242,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Stop")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayStop() { var currentSession = RequestHelpers.GetSession(_sessionManager, _authorizationContext, Request); @@ -250,6 +259,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Seek")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySeek( [FromBody, Required] SeekRequestDto requestData) { @@ -267,6 +277,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Buffering")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayBuffering( [FromBody, Required] BufferRequestDto requestData) { @@ -288,6 +299,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("Ready")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayReady( [FromBody, Required] ReadyRequestDto requestData) { @@ -309,6 +321,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetIgnoreWait")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySetIgnoreWait( [FromBody, Required] IgnoreWaitRequestDto requestData) { @@ -326,6 +339,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("NextItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayNextItem( [FromBody, Required] NextItemRequestDto requestData) { @@ -343,6 +357,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("PreviousItem")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlayPreviousItem( [FromBody, Required] PreviousItemRequestDto requestData) { @@ -360,6 +375,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetRepeatMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySetRepeatMode( [FromBody, Required] SetRepeatModeRequestDto requestData) { @@ -377,6 +393,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="NoContentResult"/> indicating success.</returns> [HttpPost("SetShuffleMode")] [ProducesResponseType(StatusCodes.Status204NoContent)] + [Authorize(Policy = Policies.SyncPlayIsInGroup)] public ActionResult SyncPlaySetShuffleMode( [FromBody, Required] SetShuffleModeRequestDto requestData) { diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 6d46819143..0fd8cb224f 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -71,7 +71,7 @@ namespace Jellyfin.Data.Entities EnableAutoLogin = false; PlayDefaultAudioTrack = true; SubtitleMode = SubtitlePlaybackMode.Default; - SyncPlayAccess = SyncPlayAccess.CreateAndJoinGroups; + SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups; AddDefaultPermissions(); AddDefaultPreferences(); @@ -326,7 +326,7 @@ namespace Jellyfin.Data.Entities /// <summary> /// Gets or sets the level of sync play permissions this user has. /// </summary> - public SyncPlayAccess SyncPlayAccess { get; set; } + public SyncPlayUserAccessType SyncPlayAccess { get; set; } /// <summary> /// Gets or sets the row version. diff --git a/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs b/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs new file mode 100644 index 0000000000..8c3e6cb17e --- /dev/null +++ b/Jellyfin.Data/Enums/SyncPlayAccessRequirementType.cs @@ -0,0 +1,28 @@ +namespace Jellyfin.Data.Enums +{ + /// <summary> + /// Enum SyncPlayAccessRequirementType. + /// </summary> + public enum SyncPlayAccessRequirementType + { + /// <summary> + /// User must have access to SyncPlay, in some form. + /// </summary> + HasAccess = 0, + + /// <summary> + /// User must be able to create groups. + /// </summary> + CreateGroup = 1, + + /// <summary> + /// User must be able to join groups. + /// </summary> + JoinGroup = 2, + + /// <summary> + /// User must be in a group. + /// </summary> + IsInGroup = 3 + } +} diff --git a/Jellyfin.Data/Enums/SyncPlayAccess.cs b/Jellyfin.Data/Enums/SyncPlayUserAccessType.cs similarity index 85% rename from Jellyfin.Data/Enums/SyncPlayAccess.cs rename to Jellyfin.Data/Enums/SyncPlayUserAccessType.cs index 8c13b37a13..030d16fb90 100644 --- a/Jellyfin.Data/Enums/SyncPlayAccess.cs +++ b/Jellyfin.Data/Enums/SyncPlayUserAccessType.cs @@ -1,9 +1,9 @@ namespace Jellyfin.Data.Enums { /// <summary> - /// Enum SyncPlayAccess. + /// Enum SyncPlayUserAccessType. /// </summary> - public enum SyncPlayAccess + public enum SyncPlayUserAccessType { /// <summary> /// User can create groups and join them. diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index b256c869cf..f38beb7f9f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -127,18 +127,32 @@ namespace Jellyfin.Server.Extensions policy.AddRequirements(new RequiresElevationRequirement()); }); options.AddPolicy( - Policies.SyncPlayAccess, + Policies.SyncPlayHasAccess, policy => { policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); - policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccess.JoinGroups)); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.HasAccess)); }); options.AddPolicy( - Policies.SyncPlayCreateGroupAccess, + Policies.SyncPlayCreateGroup, policy => { policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); - policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccess.CreateAndJoinGroups)); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.CreateGroup)); + }); + options.AddPolicy( + Policies.SyncPlayJoinGroup, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.JoinGroup)); + }); + options.AddPolicy( + Policies.SyncPlayIsInGroup, + policy => + { + policy.AddAuthenticationSchemes(AuthenticationSchemes.CustomAuthentication); + policy.AddRequirements(new SyncPlayAccessRequirement(SyncPlayAccessRequirementType.IsInGroup)); }); }); } diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index d0244563a4..1c954828c3 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -51,5 +51,12 @@ namespace MediaBrowser.Controller.SyncPlay /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> void HandleRequest(SessionInfo session, IGroupPlaybackRequest request, CancellationToken cancellationToken); + + /// <summary> + /// Checks whether a user has an active session using SyncPlay. + /// </summary> + /// <param name="userId">The user identifier to check.</param> + /// <returns><c>true</c> if the user is using SyncPlay; <c>false</c> otherwise.</returns> + bool IsUserActive(Guid userId); } } diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs index 363b2633fd..37da04adf7 100644 --- a/MediaBrowser.Model/Users/UserPolicy.cs +++ b/MediaBrowser.Model/Users/UserPolicy.cs @@ -111,7 +111,7 @@ namespace MediaBrowser.Model.Users /// Gets or sets a value indicating what SyncPlay features the user can access. /// </summary> /// <value>Access level to SyncPlay features.</value> - public SyncPlayAccess SyncPlayAccess { get; set; } + public SyncPlayUserAccessType SyncPlayAccess { get; set; } public UserPolicy() { @@ -160,7 +160,7 @@ namespace MediaBrowser.Model.Users EnableContentDownloading = true; EnablePublicSharing = true; EnableRemoteAccess = true; - SyncPlayAccess = SyncPlayAccess.CreateAndJoinGroups; + SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups; } } } From f97182c768d836afe376583921fdc1a4cb159786 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Mon, 7 Dec 2020 13:21:50 +0100 Subject: [PATCH 0667/1930] Add log level parameter to ActivityLog constructor --- Jellyfin.Data/Entities/ActivityLog.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Data/Entities/ActivityLog.cs b/Jellyfin.Data/Entities/ActivityLog.cs index 620e828306..e2d5c71879 100644 --- a/Jellyfin.Data/Entities/ActivityLog.cs +++ b/Jellyfin.Data/Entities/ActivityLog.cs @@ -18,7 +18,8 @@ namespace Jellyfin.Data.Entities /// <param name="name">The name.</param> /// <param name="type">The type.</param> /// <param name="userId">The user id.</param> - public ActivityLog(string name, string type, Guid userId) + /// <param name="logLevel">The log level.</param> + public ActivityLog(string name, string type, Guid userId, LogLevel logLevel = LogLevel.Information) { if (string.IsNullOrEmpty(name)) { @@ -34,7 +35,7 @@ namespace Jellyfin.Data.Entities Type = type; UserId = userId; DateCreated = DateTime.UtcNow; - LogSeverity = LogLevel.Trace; + LogSeverity = logLevel; } /// <summary> From fbeb0228a2cae833a8a5017edeaf97f89b5acfb3 Mon Sep 17 00:00:00 2001 From: Ionut Andrei Oanca <oancaionutandrei@gmail.com> Date: Mon, 7 Dec 2020 16:15:56 +0100 Subject: [PATCH 0668/1930] Minor code style related change --- .../Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs index fd8286b1df..b898ac76c8 100644 --- a/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs +++ b/Jellyfin.Api/Auth/SyncPlayAccessPolicy/SyncPlayAccessHandler.cs @@ -49,9 +49,9 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy if (requirement.RequiredAccess == SyncPlayAccessRequirementType.HasAccess) { - if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups || - user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups || - _syncPlayManager.IsUserActive(userId!.Value)) + if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups + || user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups + || _syncPlayManager.IsUserActive(userId!.Value)) { context.Succeed(requirement); } @@ -73,8 +73,8 @@ namespace Jellyfin.Api.Auth.SyncPlayAccessPolicy } else if (requirement.RequiredAccess == SyncPlayAccessRequirementType.JoinGroup) { - if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups || - user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups) + if (user.SyncPlayAccess == SyncPlayUserAccessType.CreateAndJoinGroups + || user.SyncPlayAccess == SyncPlayUserAccessType.JoinGroups) { context.Succeed(requirement); } From 5150598c6d3d0ddb4435d73d5bea80d4b1fd2769 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 7 Dec 2020 08:55:42 -0700 Subject: [PATCH 0669/1930] Fix API forbidden response --- Jellyfin.Api/Controllers/ImageController.cs | 8 ++++---- .../Controllers/QuickConnectController.cs | 4 ++-- Jellyfin.Api/Controllers/UserController.cs | 18 +++++++++--------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 65de81d7a6..e828a0801b 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -98,7 +98,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to update the image."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image."); } var user = _userManager.GetUserById(userId); @@ -144,7 +144,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to update the image."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the image."); } var user = _userManager.GetUserById(userId); @@ -190,7 +190,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to delete the image."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image."); } var user = _userManager.GetUserById(userId); @@ -229,7 +229,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to delete the image."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to delete the image."); } var user = _userManager.GetUserById(userId); diff --git a/Jellyfin.Api/Controllers/QuickConnectController.cs b/Jellyfin.Api/Controllers/QuickConnectController.cs index 73da2f906a..4ac8491815 100644 --- a/Jellyfin.Api/Controllers/QuickConnectController.cs +++ b/Jellyfin.Api/Controllers/QuickConnectController.cs @@ -88,7 +88,7 @@ namespace Jellyfin.Api.Controllers { if (_quickConnect.State == QuickConnectState.Unavailable) { - return Forbid("Quick connect is unavailable"); + return StatusCode(StatusCodes.Status403Forbidden, "Quick connect is unavailable"); } _quickConnect.Activate(); @@ -126,7 +126,7 @@ namespace Jellyfin.Api.Controllers var userId = ClaimHelpers.GetUserId(Request.HttpContext.User); if (!userId.HasValue) { - return Forbid("Unknown user id"); + return StatusCode(StatusCodes.Status403Forbidden, "Unknown user id"); } return _quickConnect.AuthorizeRequest(userId.Value, code); diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 9805b84b1a..4cf8a90951 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -169,7 +169,7 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(password) && string.IsNullOrEmpty(pw)) { - return Forbid("Only sha1 password is not allowed."); + return StatusCode(StatusCodes.Status403Forbidden, "Only sha1 password is not allowed."); } // Password should always be null @@ -271,7 +271,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to update the password."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the password."); } var user = _userManager.GetUserById(userId); @@ -296,7 +296,7 @@ namespace Jellyfin.Api.Controllers if (success == null) { - return Forbid("Invalid user or password entered."); + return StatusCode(StatusCodes.Status403Forbidden, "Invalid user or password entered."); } await _userManager.ChangePassword(user, request.NewPw).ConfigureAwait(false); @@ -329,7 +329,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, true)) { - return Forbid("User is not allowed to update the easy password."); + return StatusCode(StatusCodes.Status403Forbidden, "User is not allowed to update the easy password."); } var user = _userManager.GetUserById(userId); @@ -376,7 +376,7 @@ namespace Jellyfin.Api.Controllers if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false)) { - return Forbid("User update not allowed."); + return StatusCode(StatusCodes.Status403Forbidden, "User update not allowed."); } var user = _userManager.GetUserById(userId); @@ -421,14 +421,14 @@ namespace Jellyfin.Api.Controllers { if (_userManager.Users.Count(i => i.HasPermission(PermissionKind.IsAdministrator)) == 1) { - return Forbid("There must be at least one user in the system with administrative access."); + return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one user in the system with administrative access."); } } // If disabling if (newPolicy.IsDisabled && user.HasPermission(PermissionKind.IsAdministrator)) { - return Forbid("Administrators cannot be disabled."); + return StatusCode(StatusCodes.Status403Forbidden, "Administrators cannot be disabled."); } // If disabling @@ -436,7 +436,7 @@ namespace Jellyfin.Api.Controllers { if (_userManager.Users.Count(i => !i.HasPermission(PermissionKind.IsDisabled)) == 1) { - return Forbid("There must be at least one enabled user in the system."); + return StatusCode(StatusCodes.Status403Forbidden, "There must be at least one enabled user in the system."); } var currentToken = _authContext.GetAuthorizationInfo(Request).Token; @@ -466,7 +466,7 @@ namespace Jellyfin.Api.Controllers { if (!RequestHelpers.AssertCanUpdateUser(_authContext, HttpContext.Request, userId, false)) { - return Forbid("User configuration update not allowed"); + return StatusCode(StatusCodes.Status403Forbidden, "User configuration update not allowed"); } await _userManager.UpdateConfigurationAsync(userId, userConfig).ConfigureAwait(false); From d14d8145d5d8f233ad91be1ee3a97717dc10094b Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 18:27:22 +0000 Subject: [PATCH 0670/1930] Fixed createPlayList --- Emby.Dlna/PlayTo/PlayToController.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index b7cd91a5c4..a7cb7125bc 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -340,10 +340,19 @@ namespace Emby.Dlna.PlayTo } var playlist = new PlaylistItem[len]; - playlist[0] = CreatePlaylistItem(items[0], user, command.StartPositionTicks.Value, command.MediaSourceId, command.AudioStreamIndex, command.SubtitleStreamIndex); + + // Not nullable enabled - so this is required. + playlist[0] = CreatePlaylistItem( + items[0], + user, + (command.StartPositionTicks == null) ? 0 : command.StartPositionTicks.Value, + command.MediaSourceId ?? string.Empty, + command.AudioStreamIndex, + command.SubtitleStreamIndex); + for (int i = 1; i < len; i++) { - playlist[i] = CreatePlaylistItem(items[i], user, 0, null, null, null); + playlist[i] = CreatePlaylistItem(items[i], user, 0, string.Empty, null, null); } _logger.LogDebug("{0} - Playlist created", _session.DeviceName); From 8999871b683b326f5ac304ea3d395266741b83c2 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 18:31:45 +0000 Subject: [PATCH 0671/1930] cleaned change --- Emby.Dlna/PlayTo/PlayToController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index a7cb7125bc..4861093044 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -345,7 +345,7 @@ namespace Emby.Dlna.PlayTo playlist[0] = CreatePlaylistItem( items[0], user, - (command.StartPositionTicks == null) ? 0 : command.StartPositionTicks.Value, + command.StartPositionTicks ?? 0, command.MediaSourceId ?? string.Empty, command.AudioStreamIndex, command.SubtitleStreamIndex); From b4855205373365a07745775ac8c7704855fa72e3 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 20:25:41 +0000 Subject: [PATCH 0672/1930] Update ApplicationHost.cs Added X509KeyStorageFlags.UserKeySet --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d74ea03520..04bd01abf0 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -714,7 +714,7 @@ namespace Emby.Server.Implementations // Don't use an empty string password var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password; - var localCert = new X509Certificate2(certificateLocation, password); + var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet); // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { From 6e9837844738de7bc55dae9994538535e62ed888 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 7 Dec 2020 14:58:27 -0700 Subject: [PATCH 0673/1930] Simplify converter --- .../Json/Converters/JsonBoolNumberConverter.cs | 5 +---- MediaBrowser.Common/Json/JsonDefaults.cs | 1 + .../Json/JsonBoolNumberTests.cs | 8 ++++---- .../Models/BoolTypeModel.cs | 17 ----------------- 4 files changed, 6 insertions(+), 25 deletions(-) delete mode 100644 tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs index f73ca344ca..cb2047049e 100644 --- a/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs @@ -8,9 +8,6 @@ namespace MediaBrowser.Common.Json.Converters /// Converts a number to a boolean. /// This is needed for HDHomerun. /// </summary> - /// <remarks> - /// Adding this to the JsonConverter list causes recursion. - /// </remarks> public class JsonBoolNumberConverter : JsonConverter<bool> { /// <inheritdoc /> @@ -21,7 +18,7 @@ namespace MediaBrowser.Common.Json.Converters return Convert.ToBoolean(reader.GetInt32()); } - return JsonSerializer.Deserialize<bool>(ref reader, options); + return reader.GetBoolean(); } /// <inheritdoc /> diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index c5050a21db..b76edd2bc7 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -43,6 +43,7 @@ namespace MediaBrowser.Common.Json options.Converters.Add(new JsonVersionConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new JsonNullableStructConverterFactory()); + options.Converters.Add(new JsonBoolNumberConverter()); return options; } diff --git a/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs index 1cae5b8491..3779e2d0ae 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs @@ -1,5 +1,5 @@ using System.Text.Json; -using Jellyfin.Common.Tests.Models; +using MediaBrowser.Common.Json.Converters; using Xunit; namespace Jellyfin.Common.Tests.Json @@ -14,10 +14,10 @@ namespace Jellyfin.Common.Tests.Json [InlineData("false", false)] public static void Deserialize_Number_Valid_Success(string input, bool? output) { - var inputJson = $"{{ \"Value\": {input} }}"; var options = new JsonSerializerOptions(); - var value = JsonSerializer.Deserialize<BoolTypeModel>(inputJson, options); - Assert.Equal(value?.Value, output); + options.Converters.Add(new JsonBoolNumberConverter()); + var value = JsonSerializer.Deserialize<bool>(input, options); + Assert.Equal(value, output); } } } \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs b/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs deleted file mode 100644 index feb952efc5..0000000000 --- a/tests/Jellyfin.Common.Tests/Models/BoolTypeModel.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Text.Json.Serialization; -using MediaBrowser.Common.Json.Converters; - -namespace Jellyfin.Common.Tests.Models -{ - /// <summary> - /// The bool type model. - /// </summary> - public class BoolTypeModel - { - /// <summary> - /// Gets or sets a value indicating whether the value is true or false. - /// </summary> - [JsonConverter(typeof(JsonBoolNumberConverter))] - public bool Value { get; set; } - } -} \ No newline at end of file From d69f2d7d7fd4209652878d84f811051e69fb45b2 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 22:06:28 +0000 Subject: [PATCH 0674/1930] DNLA over HTTP only --- Emby.Dlna/Main/DlnaEntryPoint.cs | 23 +++++++++++++++++-- .../ApplicationHost.cs | 6 ++--- .../Configuration/NetworkConfiguration.cs | 6 ++--- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 4 files changed, 28 insertions(+), 9 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index fb4454a343..ced56a7182 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; +using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; @@ -52,6 +53,8 @@ namespace Emby.Dlna.Main private readonly ISocketFactory _socketFactory; private readonly INetworkManager _networkManager; private readonly object _syncLock = new object(); + private readonly NetworkConfiguration _netConfig; + private readonly bool _disabled; private PlayToManager _manager; private SsdpDevicePublisher _publisher; @@ -122,6 +125,13 @@ namespace Emby.Dlna.Main httpClientFactory, config); Current = this; + + _netConfig = config.GetConfiguration<NetworkConfiguration>("network"); + _disabled = appHost.ListenWithHttps && _netConfig.RequireHttps; + if (_disabled) + { + _logger.LogError("The DLNA specification does not support HTTPS."); + } } public static DlnaEntryPoint Current { get; private set; } @@ -136,6 +146,12 @@ namespace Emby.Dlna.Main { await ((DlnaManager)_dlnaManager).InitProfilesAsync().ConfigureAwait(false); + if (_disabled) + { + // No use starting as dlna won't work, as we're running purely on HTTPS. + return; + } + ReloadComponents(); _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated; @@ -290,12 +306,15 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); - var uri = new Uri(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); + var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); + // DLNA will only work over http, so we must reset to http:// : {port} + uri.Scheme = "http://"; + uri.Port = _netConfig.PublicPort; var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. - Location = uri, // Must point to the URL that serves your devices UPnP description document. + Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document. Address = address.Address, PrefixLength = address.PrefixLength, FriendlyName = "Jellyfin", diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d74ea03520..b6f63e5659 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -496,7 +496,7 @@ namespace Emby.Server.Implementations { var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); HttpPort = networkConfiguration.HttpServerPortNumber; - HttpsPort = networkConfiguration.HttpsPortNumber; + HttpsPort = networkConfiguration.HttpsServerPortNumber; // Safeguard against invalid configuration if (HttpPort == HttpsPort) @@ -714,7 +714,7 @@ namespace Emby.Server.Implementations // Don't use an empty string password var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password; - var localCert = new X509Certificate2(certificateLocation, password); + var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet); // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { @@ -919,7 +919,7 @@ namespace Emby.Server.Implementations var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); // Need to restart if ports have changed if (networkConfiguration.HttpServerPortNumber != HttpPort || - networkConfiguration.HttpsPortNumber != HttpsPort) + networkConfiguration.HttpsServerPortNumber != HttpsPort) { if (ServerConfigurationManager.Configuration.IsPortAuthorized) { diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index df420f48a2..8db3d3a9c1 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -16,7 +16,7 @@ namespace Jellyfin.Networking.Configuration public const int DefaultHttpPort = 8096; /// <summary> - /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsServerPortNumber"/>. /// </summary> public const int DefaultHttpsPort = 8920; @@ -76,7 +76,7 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets the HTTPS server port number. /// </summary> /// <value>The HTTPS server port number.</value> - public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + public int HttpsServerPortNumber { get; set; } = DefaultHttpsPort; /// <summary> /// Gets or sets a value indicating whether to use HTTPS. @@ -88,7 +88,7 @@ namespace Jellyfin.Networking.Configuration public bool EnableHttps { get; set; } /// <summary> - /// Gets or sets the public mapped port. + /// Gets or sets the Upublic mapped port. /// </summary> /// <value>The public mapped port.</value> public int PublicPort { get; set; } = DefaultHttpPort; diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 85da927fb4..a76ba49b6a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -784,7 +784,7 @@ namespace Jellyfin.Networking.Manager } else { - _logger.LogDebug("Invalid or unknown network {Token}.", token); + _logger.LogDebug("Invalid or unknown object {Token}.", token); } } From 57cb3a67bc12d6a7aa38e5a8b4df68bf631b5ffe Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 22:12:43 +0000 Subject: [PATCH 0675/1930] Update ApplicationHost.cs Removed previous change, use for testing. --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index b6f63e5659..086e6d7f94 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -714,7 +714,7 @@ namespace Emby.Server.Implementations // Don't use an empty string password var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password; - var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet); + var localCert = new X509Certificate2(certificateLocation, password); // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA; if (!localCert.HasPrivateKey) { From e34adc12d9ab15fa5126e0c0e3a625cea7940e7f Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 22:15:30 +0000 Subject: [PATCH 0676/1930] reverted change. --- Emby.Server.Implementations/ApplicationHost.cs | 4 ++-- Jellyfin.Networking/Configuration/NetworkConfiguration.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 086e6d7f94..d74ea03520 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -496,7 +496,7 @@ namespace Emby.Server.Implementations { var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); HttpPort = networkConfiguration.HttpServerPortNumber; - HttpsPort = networkConfiguration.HttpsServerPortNumber; + HttpsPort = networkConfiguration.HttpsPortNumber; // Safeguard against invalid configuration if (HttpPort == HttpsPort) @@ -919,7 +919,7 @@ namespace Emby.Server.Implementations var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); // Need to restart if ports have changed if (networkConfiguration.HttpServerPortNumber != HttpPort || - networkConfiguration.HttpsServerPortNumber != HttpsPort) + networkConfiguration.HttpsPortNumber != HttpsPort) { if (ServerConfigurationManager.Configuration.IsPortAuthorized) { diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 8db3d3a9c1..730fc498cd 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -16,7 +16,7 @@ namespace Jellyfin.Networking.Configuration public const int DefaultHttpPort = 8096; /// <summary> - /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsServerPortNumber"/>. + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. /// </summary> public const int DefaultHttpsPort = 8920; @@ -76,7 +76,7 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets the HTTPS server port number. /// </summary> /// <value>The HTTPS server port number.</value> - public int HttpsServerPortNumber { get; set; } = DefaultHttpsPort; + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; /// <summary> /// Gets or sets a value indicating whether to use HTTPS. From 6722fcec363a5f2e6ed85ac0609c250fb078155b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 7 Dec 2020 15:23:25 -0700 Subject: [PATCH 0677/1930] Revert #4568 --- .../Json/Converters/JsonGuidConverter.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs index 52e08d071a..ccf214e3ca 100644 --- a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs @@ -13,21 +13,13 @@ namespace MediaBrowser.Common.Json.Converters public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var guidStr = reader.GetString(); - return guidStr == null ? Guid.Empty : new Guid(guidStr); } /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) { - if (value == Guid.Empty) - { - writer.WriteNullValue(); - } - else - { - writer.WriteStringValue(value); - } + writer.WriteStringValue(value); } } } From 8517b28eba8c96f8b695a8137c7f9f0d22212400 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 7 Dec 2020 15:23:40 -0700 Subject: [PATCH 0678/1930] Make BaseItemDto Guids nullable --- Emby.Server.Implementations/LiveTv/LiveTvManager.cs | 4 ++-- MediaBrowser.Model/Dto/BaseItemDto.cs | 10 +++++----- .../Json/JsonGuidConverterTests.cs | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 8c9bb6ba01..7842be7164 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1928,7 +1928,7 @@ namespace Emby.Server.Implementations.LiveTv foreach (var programDto in currentProgramDtos) { - if (currentChannelsDict.TryGetValue(programDto.ChannelId, out BaseItemDto channelDto)) + if (programDto.ChannelId.HasValue && currentChannelsDict.TryGetValue(programDto.ChannelId.Value, out BaseItemDto channelDto)) { channelDto.CurrentProgram = programDto; } @@ -2018,7 +2018,7 @@ namespace Emby.Server.Implementations.LiveTv info.DayPattern = _tvDtoService.GetDayPattern(info.Days); info.Name = program.Name; - info.ChannelId = programDto.ChannelId; + info.ChannelId = programDto.ChannelId ?? Guid.Empty; info.ChannelName = programDto.ChannelName; info.StartDate = program.StartDate; info.Name = program.Name; diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs index fac7541773..3f7aac9cd8 100644 --- a/MediaBrowser.Model/Dto/BaseItemDto.cs +++ b/MediaBrowser.Model/Dto/BaseItemDto.cs @@ -152,7 +152,7 @@ namespace MediaBrowser.Model.Dto /// Gets or sets the channel identifier. /// </summary> /// <value>The channel identifier.</value> - public Guid ChannelId { get; set; } + public Guid? ChannelId { get; set; } public string ChannelName { get; set; } @@ -270,7 +270,7 @@ namespace MediaBrowser.Model.Dto /// Gets or sets the parent id. /// </summary> /// <value>The parent id.</value> - public Guid ParentId { get; set; } + public Guid? ParentId { get; set; } /// <summary> /// Gets or sets the type. @@ -344,13 +344,13 @@ namespace MediaBrowser.Model.Dto /// Gets or sets the series id. /// </summary> /// <value>The series id.</value> - public Guid SeriesId { get; set; } + public Guid? SeriesId { get; set; } /// <summary> /// Gets or sets the season identifier. /// </summary> /// <value>The season identifier.</value> - public Guid SeasonId { get; set; } + public Guid? SeasonId { get; set; } /// <summary> /// Gets or sets the special feature count. @@ -428,7 +428,7 @@ namespace MediaBrowser.Model.Dto /// Gets or sets the album id. /// </summary> /// <value>The album id.</value> - public Guid AlbumId { get; set; } + public Guid? AlbumId { get; set; } /// <summary> /// Gets or sets the album image tag. diff --git a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs index 3c94db4913..663cc3c78f 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs @@ -3,7 +3,7 @@ using System.Text.Json; using MediaBrowser.Common.Json.Converters; using Xunit; -namespace Jellyfin.Common.Tests.Extensions +namespace Jellyfin.Common.Tests.Json { public class JsonGuidConverterTests { @@ -44,9 +44,9 @@ namespace Jellyfin.Common.Tests.Extensions } [Fact] - public void Serialize_EmptyGuid_Null() + public void Serialize_EmptyGuid_EmptyGuid() { - Assert.Equal("null", JsonSerializer.Serialize(Guid.Empty, _options)); + Assert.Equal($"\"{Guid.Empty}\"", JsonSerializer.Serialize(Guid.Empty, _options)); } } } From acc45b7307d9b01a152ebc05e84f81e3672f2169 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 7 Dec 2020 22:29:19 +0000 Subject: [PATCH 0679/1930] Update Jellyfin.Networking/Configuration/NetworkConfiguration.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Networking/Configuration/NetworkConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 730fc498cd..df420f48a2 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -88,7 +88,7 @@ namespace Jellyfin.Networking.Configuration public bool EnableHttps { get; set; } /// <summary> - /// Gets or sets the Upublic mapped port. + /// Gets or sets the public mapped port. /// </summary> /// <value>The public mapped port.</value> public int PublicPort { get; set; } = DefaultHttpPort; From 2c947630a747b8f74557cbd03c520fe893f39c99 Mon Sep 17 00:00:00 2001 From: Matthew Bauer <sylk@protonmail.com> Date: Mon, 7 Dec 2020 16:04:20 -0700 Subject: [PATCH 0680/1930] Modified ReadMe with updated command line command Also removed old documentation about placing the built dist into the jellyfin-server directory --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index 1ab246f84f..29f9923499 100644 --- a/README.md +++ b/README.md @@ -105,12 +105,6 @@ There are three options to get the files for the web client. 2. Build them from source following the instructions on the [jellyfin-web repository](https://github.com/jellyfin/jellyfin-web) 3. Get the pre-built files from an existing installation of the server. For example, with a Windows server installation the client files are located at `C:\Program Files\Jellyfin\Server\jellyfin-web` -Once you have a copy of the built web client files, you need to copy them into a specific directory. - -> `<repository root>/Mediabrowser.WebDashboard/jellyfin-web` - -As part of the build process, this folder will be copied to the build output directory, where it can be accessed by the server. - ### Running The Server The following instructions will help you get the project up and running via the command line, or your preferred IDE. @@ -133,7 +127,7 @@ To run the server from the command line you can use the `dotnet run` command. Th ```bash cd jellyfin # Move into the repository directory -dotnet run --project Jellyfin.Server # Run the server startup project +dotnet run --project Jellyfin.Server --webdir /absolute/path/to/jellyfin-web/dist # Run the server startup project ``` A second option is to build the project and then run the resulting executable file directly. When running the executable directly you can easily add command line options. Add the `--help` flag to list details on all the supported command line options. From d12fa01d7ac999ea45eaea424b4b444e6ec88868 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 7 Dec 2020 19:10:35 -0700 Subject: [PATCH 0681/1930] Fix potential null reference --- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index e540e44713..e6c6050720 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -425,7 +425,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { var person = new PersonInfo { - Name = result.Director.Trim(), + Name = result.Writer.Trim(), Type = PersonType.Writer }; From 26e5aacb9096c448d6e545b1a2713972994f6418 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 8 Dec 2020 07:18:25 -0700 Subject: [PATCH 0682/1930] Fix JsonConverter recursion --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 2 -- .../Json/Converters/JsonBoolNumberConverter.cs | 2 +- .../Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs | 11 +++++++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 0f296d9894..48bc1efb1c 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -342,10 +342,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public string URL { get; set; } - [JsonConverter(typeof(JsonBoolNumberConverter))] public bool Favorite { get; set; } - [JsonConverter(typeof(JsonBoolNumberConverter))] public bool DRM { get; set; } public int HD { get; set; } diff --git a/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs index cb2047049e..b29e6a71a6 100644 --- a/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonBoolNumberConverter.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Common.Json.Converters /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) { - JsonSerializer.Serialize(writer, value, options); + writer.WriteBooleanValue(value); } } } \ No newline at end of file diff --git a/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs index 3779e2d0ae..9ded01f2b1 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonBoolNumberTests.cs @@ -19,5 +19,16 @@ namespace Jellyfin.Common.Tests.Json var value = JsonSerializer.Deserialize<bool>(input, options); Assert.Equal(value, output); } + + [Theory] + [InlineData(true, "true")] + [InlineData(false, "false")] + public static void Serialize_Bool_Success(bool input, string output) + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonBoolNumberConverter()); + var value = JsonSerializer.Serialize(input, options); + Assert.Equal(value, output); + } } } \ No newline at end of file From 020fe37dfe4f8b4c2bae61562369f8b234726d1f Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Tue, 8 Dec 2020 22:33:52 +0800 Subject: [PATCH 0683/1930] fix custom library order --- Emby.Server.Implementations/Library/UserViewManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index f51657c63b..e4221dd508 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -139,13 +139,13 @@ namespace Emby.Server.Implementations.Library return list .OrderBy(i => { - var index = orders.IndexOf(i.Id.ToString("N", CultureInfo.InvariantCulture)); + var index = orders.IndexOf(i.Id.ToString("D", CultureInfo.InvariantCulture)); if (index == -1 && i is UserView view && view.DisplayParentId != Guid.Empty) { - index = orders.IndexOf(view.DisplayParentId.ToString("N", CultureInfo.InvariantCulture)); + index = orders.IndexOf(view.DisplayParentId.ToString("D", CultureInfo.InvariantCulture)); } return index == -1 ? int.MaxValue : index; From e62124440539e814bb5036ffd646081528f1ca09 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 8 Dec 2020 08:28:19 -0700 Subject: [PATCH 0684/1930] Add missing EnsureSuccessStatusCode --- .../LiveTv/Listings/SchedulesDirect.cs | 11 +++++++++-- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 1 + .../Updates/InstallationManager.cs | 1 + 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 1084ddf744..2073b9ef1c 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -611,12 +611,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) { + HttpResponseMessage response = null; try { - return await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false); + response = await _httpClientFactory.CreateClient(NamedClient.Default) + .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + return response; } catch (HttpRequestException ex) { + response?.Dispose(); _tokens.Clear(); if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500) @@ -647,6 +652,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json); using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).ConfigureAwait(false); if (string.Equals(root.message, "OK", StringComparison.Ordinal)) @@ -701,6 +707,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings try { using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false); + httpResponse.EnsureSuccessStatusCode(); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var response = httpResponse.Content; var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(stream).ConfigureAwait(false); @@ -709,7 +716,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } catch (HttpRequestException ex) { - // Apparently we're supposed to swallow this + // SchedulesDirect returns 400 if no lineups are configured. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest) { return false; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 0f296d9894..55b0415149 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -131,6 +131,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/discover.json", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); + response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, cancellationToken: cancellationToken) .ConfigureAwait(false); diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index ef346dd5d6..ff32d9a7e9 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -407,6 +407,7 @@ namespace Emby.Server.Implementations.Updates using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .GetAsync(new Uri(package.SourceUrl), cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); // CA5351: Do Not Use Broken Cryptographic Algorithms From 7027561e195501a11e4417e3350b11fdc98a2c7f Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Tue, 8 Dec 2020 18:53:38 +0100 Subject: [PATCH 0685/1930] Add tests for HdHomerunHost.GetModelInfo --- .../TunerHosts/HdHomerun/DiscoverResponse.cs | 42 ++++++++++ .../TunerHosts/HdHomerun/HdHomerunHost.cs | 40 +--------- .../Properties/AssemblyInfo.cs | 2 + ...llyfin.Server.Implementations.Tests.csproj | 4 + .../LiveTv/HdHomerunHostTests.cs | 77 +++++++++++++++++++ .../LiveTv/discover.json | 1 + 6 files changed, 128 insertions(+), 38 deletions(-) create mode 100644 Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs new file mode 100644 index 0000000000..3d739f3089 --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs @@ -0,0 +1,42 @@ +#pragma warning disable CS1591 + +using System; + +namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun +{ + public class DiscoverResponse + { + public string FriendlyName { get; set; } + + public string ModelNumber { get; set; } + + public string FirmwareName { get; set; } + + public string FirmwareVersion { get; set; } + + public string DeviceID { get; set; } + + public string DeviceAuth { get; set; } + + public string BaseURL { get; set; } + + public string LineupURL { get; set; } + + public int TunerCount { get; set; } + + public bool SupportsTranscoding + { + get + { + var model = ModelNumber ?? string.Empty; + + if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1) + { + return true; + } + + return false; + } + } + } +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 0f296d9894..97ef189395 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -111,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun }).Cast<ChannelInfo>().ToList(); } - private async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken) + internal async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken) { var cacheKey = info.Id; @@ -129,7 +129,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun try { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/discover.json", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken) + .GetAsync(GetApiUrl(info) + "/discover.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, cancellationToken: cancellationToken) @@ -678,42 +678,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - public class DiscoverResponse - { - public string FriendlyName { get; set; } - - public string ModelNumber { get; set; } - - public string FirmwareName { get; set; } - - public string FirmwareVersion { get; set; } - - public string DeviceID { get; set; } - - public string DeviceAuth { get; set; } - - public string BaseURL { get; set; } - - public string LineupURL { get; set; } - - public int TunerCount { get; set; } - - public bool SupportsTranscoding - { - get - { - var model = ModelNumber ?? string.Empty; - - if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1) - { - return true; - } - - return false; - } - } - } - public async Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken) { lock (_modelCache) diff --git a/Emby.Server.Implementations/Properties/AssemblyInfo.cs b/Emby.Server.Implementations/Properties/AssemblyInfo.cs index a1933f66ef..cb7972173e 100644 --- a/Emby.Server.Implementations/Properties/AssemblyInfo.cs +++ b/Emby.Server.Implementations/Properties/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Resources; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -14,6 +15,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] +[assembly: InternalsVisibleTo("Jellyfin.Server.Implementations.Tests")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index fffbc6212a..08392b25ea 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -35,6 +35,10 @@ <ProjectReference Include="..\..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" /> </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="LiveTv\discover.json" /> + </ItemGroup> + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet> </PropertyGroup> diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs new file mode 100644 index 0000000000..c38d9ea4d8 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -0,0 +1,77 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun; +using MediaBrowser.Model.LiveTv; +using Moq; +using Moq.Protected; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.LiveTv +{ + public class HdHomerunHostTests + { + private const string TestIp = "http://192.168.1.182"; + + private readonly Fixture _fixture; + private readonly HdHomerunHost _hdHomerunHost; + + public HdHomerunHostTests() + { + const string ResourceName = "Jellyfin.Server.Implementations.Tests.LiveTv.discover.json"; + + var messageHandler = new Mock<HttpMessageHandler>(); + messageHandler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) + .Returns( + () => Task.FromResult(new HttpResponseMessage() + { + Content = new StreamContent(typeof(HdHomerunHostTests).Assembly.GetManifestResourceStream(ResourceName)!) + })); + + var http = new Mock<IHttpClientFactory>(); + http.Setup(x => x.CreateClient(It.IsAny<string>())) + .Returns(new HttpClient(messageHandler.Object)); + _fixture = new Fixture(); + _fixture.Customize(new AutoMoqCustomization + { + ConfigureMembers = true + }).Inject(http); + _hdHomerunHost = _fixture.Create<HdHomerunHost>(); + } + + [Fact] + public async Task GetModelInfo_Valid_Success() + { + var host = new TunerHostInfo() + { + Url = TestIp + }; + + var modelInfo = await _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None).ConfigureAwait(false); + Assert.Equal("HDHomeRun PRIME", modelInfo.FriendlyName); + Assert.Equal("HDHR3-CC", modelInfo.ModelNumber); + Assert.Equal("hdhomerun3_cablecard", modelInfo.FirmwareName); + Assert.Equal("20160630atest2", modelInfo.FirmwareVersion); + Assert.Equal("FFFFFFFF", modelInfo.DeviceID); + Assert.Equal("FFFFFFFF", modelInfo.DeviceAuth); + Assert.Equal(3, modelInfo.TunerCount); + Assert.Equal("http://192.168.1.182:80", modelInfo.BaseURL); + Assert.Equal("http://192.168.1.182:80/lineup.json", modelInfo.LineupURL); + } + + [Fact] + public async Task GetModelInfo_EmptyUrl_ArgumentException() + { + var host = new TunerHostInfo() + { + Url = string.Empty + }; + + await Assert.ThrowsAsync<ArgumentException>(() => _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None)); + } + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json new file mode 100644 index 0000000000..851f17bb26 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json @@ -0,0 +1 @@ +{"FriendlyName":"HDHomeRun PRIME","ModelNumber":"HDHR3-CC","FirmwareName":"hdhomerun3_cablecard","FirmwareVersion":"20160630atest2","DeviceID":"FFFFFFFF","DeviceAuth":"FFFFFFFF","TunerCount":3,"ConditionalAccess":1,"BaseURL":"http://192.168.1.182:80","LineupURL":"http://192.168.1.182:80/lineup.json"} From 514d95e5aa5197808f239ba26266f52b419a0b61 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Wed, 9 Dec 2020 01:08:41 +0100 Subject: [PATCH 0686/1930] Add tests for HdHomerunHost.GetLineup --- .../LiveTv/TunerHosts/HdHomerun/Channels.cs | 21 +++++++ .../TunerHosts/HdHomerun/DiscoverResponse.cs | 4 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 33 +++-------- ...llyfin.Server.Implementations.Tests.csproj | 1 + .../LiveTv/HdHomerunHostTests.cs | 58 +++++++++++++++++-- .../LiveTv/lineup.json | 1 + 6 files changed, 85 insertions(+), 33 deletions(-) create mode 100644 Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs new file mode 100644 index 0000000000..740cbb66ee --- /dev/null +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs @@ -0,0 +1,21 @@ +namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun +{ + internal class Channels + { + public string GuideNumber { get; set; } + + public string GuideName { get; set; } + + public string VideoCodec { get; set; } + + public string AudioCodec { get; set; } + + public string URL { get; set; } + + public bool Favorite { get; set; } + + public bool DRM { get; set; } + + public bool HD { get; set; } + } +} diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs index 3d739f3089..09d77f8382 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs @@ -1,10 +1,8 @@ -#pragma warning disable CS1591 - using System; namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { - public class DiscoverResponse + internal class DiscoverResponse { public string FriendlyName { get; set; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 1329084b68..9500dda749 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Json.Converters; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -39,6 +39,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private readonly INetworkManager _networkManager; private readonly IStreamHelper _streamHelper; + private readonly JsonSerializerOptions _jsonOptions; + private readonly Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>(); public HdHomerunHost( @@ -58,6 +60,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun _socketFactory = socketFactory; _networkManager = networkManager; _streamHelper = streamHelper; + + _jsonOptions = JsonDefaults.GetOptions(); } public string Name => "HD Homerun"; @@ -69,13 +73,13 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private string GetChannelId(TunerHostInfo info, Channels i) => ChannelIdPrefix + i.GuideNumber; - private async Task<List<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken) + internal async Task<List<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken) { var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var lineup = await JsonSerializer.DeserializeAsync<List<Channels>>(stream, cancellationToken: cancellationToken) + var lineup = await JsonSerializer.DeserializeAsync<List<Channels>>(stream, _jsonOptions, cancellationToken) .ConfigureAwait(false) ?? new List<Channels>(); if (info.ImportFavoritesOnly) @@ -102,7 +106,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun Id = GetChannelId(info, i), IsFavorite = i.Favorite, TunerHostId = info.Id, - IsHD = i.HD == 1, + IsHD = i.HD, AudioCodec = i.AudioCodec, VideoCodec = i.VideoCodec, ChannelType = ChannelType.TV, @@ -132,7 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun .GetAsync(GetApiUrl(info) + "/discover.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, cancellationToken: cancellationToken) + var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, _jsonOptions, cancellationToken) .ConfigureAwait(false); if (!string.IsNullOrEmpty(cacheKey)) @@ -330,25 +334,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return new Uri(url).AbsoluteUri.TrimEnd('/'); } - private class Channels - { - public string GuideNumber { get; set; } - - public string GuideName { get; set; } - - public string VideoCodec { get; set; } - - public string AudioCodec { get; set; } - - public string URL { get; set; } - - public bool Favorite { get; set; } - - public bool DRM { get; set; } - - public int HD { get; set; } - } - protected EncodingOptions GetEncodingOptions() { return Config.GetConfiguration<EncodingOptions>("encoding"); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 08392b25ea..310219e742 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -37,6 +37,7 @@ <ItemGroup> <EmbeddedResource Include="LiveTv\discover.json" /> + <EmbeddedResource Include="LiveTv\lineup.json" /> </ItemGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs index c38d9ea4d8..4b1509edd9 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -22,15 +22,26 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv public HdHomerunHostTests() { - const string ResourceName = "Jellyfin.Server.Implementations.Tests.LiveTv.discover.json"; + const string BaseResourcePath = "Jellyfin.Server.Implementations.Tests.LiveTv."; var messageHandler = new Mock<HttpMessageHandler>(); - messageHandler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) - .Returns( - () => Task.FromResult(new HttpResponseMessage() + messageHandler.Protected() + .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) + .Returns<HttpRequestMessage, CancellationToken>( + (m, _) => { - Content = new StreamContent(typeof(HdHomerunHostTests).Assembly.GetManifestResourceStream(ResourceName)!) - })); + var resource = BaseResourcePath + m.RequestUri?.Segments[^1]; + var stream = typeof(HdHomerunHostTests).Assembly.GetManifestResourceStream(resource); + if (stream == null) + { + throw new NullReferenceException("Resource doesn't exist: " + resource); + } + + return Task.FromResult(new HttpResponseMessage() + { + Content = new StreamContent(stream) + }); + }); var http = new Mock<IHttpClientFactory>(); http.Setup(x => x.CreateClient(It.IsAny<string>())) @@ -73,5 +84,40 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv await Assert.ThrowsAsync<ArgumentException>(() => _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None)); } + + [Fact] + public async Task GetLineup_Valid_Success() + { + var host = new TunerHostInfo() + { + Url = TestIp + }; + + var channels = await _hdHomerunHost.GetLineup(host, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(6, channels.Count); + Assert.Equal("4.1", channels[0].GuideNumber); + Assert.Equal("WCMH-DT", channels[0].GuideName); + Assert.True(channels[0].HD); + Assert.True(channels[0].Favorite); + Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL); + } + + [Fact] + public async Task GetLineup_ImportFavoritesOnly_Success() + { + var host = new TunerHostInfo() + { + Url = TestIp, + ImportFavoritesOnly = true + }; + + var channels = await _hdHomerunHost.GetLineup(host, CancellationToken.None).ConfigureAwait(false); + Assert.Single(channels); + Assert.Equal("4.1", channels[0].GuideNumber); + Assert.Equal("WCMH-DT", channels[0].GuideName); + Assert.True(channels[0].HD); + Assert.True(channels[0].Favorite); + Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL); + } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json new file mode 100644 index 0000000000..4cb5ebc8ec --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json @@ -0,0 +1 @@ +[ { "GuideNumber": "4.1", "GuideName": "WCMH-DT", "HD": 1, "Favorite": 1, "URL": "http://192.168.1.111:5004/auto/v4.1" }, { "GuideNumber": "4.2", "GuideName": "MeTV", "URL": "http://192.168.1.111:5004/auto/v4.2" }, { "GuideNumber": "4.3", "GuideName": "ION TV", "URL": "http://192.168.1.111:5004/auto/v4.3" }, { "GuideNumber": "6.1", "GuideName": "WSYX DT", "HD": 1, "URL": "http://192.168.1.111:5004/auto/v6.1" }, { "GuideNumber": "6.2", "GuideName": "MYTV", "URL": "http://192.168.1.111:5004/auto/v6.2" }, { "GuideNumber": "6.3", "GuideName": "ANTENNA", "URL": "http://192.168.1.111:5004/auto/v6.3" } ] From c0fde3496c43b5648c369ca32306148d5aa50b91 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Wed, 9 Dec 2020 01:24:30 +0100 Subject: [PATCH 0687/1930] Add tests for HdHomerunHost.TryGetTunerHostInfo --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 3 ++- .../LiveTv/HdHomerunHostTests.cs | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 9500dda749..4fe6cbf316 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -713,7 +713,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return list; } - private async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken) + internal async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken) { var hostInfo = new TunerHostInfo { @@ -725,6 +725,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun hostInfo.DeviceId = modelInfo.DeviceID; hostInfo.FriendlyName = modelInfo.FriendlyName; + hostInfo.TunerCount = modelInfo.TunerCount; return hostInfo; } diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs index 4b1509edd9..fb7cf6a471 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -119,5 +119,16 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.True(channels[0].Favorite); Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL); } + + [Fact] + public async Task TryGetTunerHostInfo_Valid_Success() + { + var host = await _hdHomerunHost.TryGetTunerHostInfo(TestIp, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(_hdHomerunHost.Type, host.Type); + Assert.Equal(TestIp, host.Url); + Assert.Equal("HDHomeRun PRIME", host.FriendlyName); + Assert.Equal("FFFFFFFF", host.DeviceId); + Assert.Equal(3, host.TunerCount); + } } } From 75aa3718dc38758d6e048d8ba9e2b97b2686d04c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 8 Dec 2020 17:47:13 -0700 Subject: [PATCH 0688/1930] Actually use library options when filtering metadata providers --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 085f769d0c..299c555d0d 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller.BaseItemManager return !baseItem.EnableMediaSourceDisplay; } - var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); + var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name); if (typeOptions != null) { return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); @@ -79,7 +79,7 @@ namespace MediaBrowser.Controller.BaseItemManager return !baseItem.EnableMediaSourceDisplay; } - var typeOptions = libraryOptions.GetTypeOptions(GetType().Name); + var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name); if (typeOptions != null) { return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); From c955f196341b4dbaf993eecdffb3c994e66b53ec Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 8 Dec 2020 19:33:26 -0700 Subject: [PATCH 0689/1930] Serialize GUID without dashes --- .../Json/Converters/JsonGuidConverter.cs | 3 ++- .../Json/JsonGuidConverterTests.cs | 11 ++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs index ccf214e3ca..bd96001105 100644 --- a/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonGuidConverter.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; @@ -19,7 +20,7 @@ namespace MediaBrowser.Common.Json.Converters /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) { - writer.WriteStringValue(value); + writer.WriteStringValue(value.ToString("N", CultureInfo.InvariantCulture)); } } } diff --git a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs index 663cc3c78f..fc17573fb9 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Text.Json; using MediaBrowser.Common.Json.Converters; using Xunit; @@ -46,7 +47,15 @@ namespace Jellyfin.Common.Tests.Json [Fact] public void Serialize_EmptyGuid_EmptyGuid() { - Assert.Equal($"\"{Guid.Empty}\"", JsonSerializer.Serialize(Guid.Empty, _options)); + Assert.Equal($"\"{Guid.Empty:N}\"", JsonSerializer.Serialize(Guid.Empty, _options)); + } + + [Fact] + public void Serialize_Valid_NoDash_Success() + { + var guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA"); + var str = JsonSerializer.Serialize(guid, _options); + Assert.Equal($"\"{guid:N}\"", str); } } } From ebd9ab3ccc2a152b2f950d8948f018fadf5e8916 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Wed, 9 Dec 2020 14:39:11 +0800 Subject: [PATCH 0690/1930] use larger batch size on mpegts to avoid corrupted thumbnails --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index b1da9c712d..4c804371ed 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -603,16 +603,19 @@ namespace MediaBrowser.MediaEncoding.Encoder } // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. + // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will lower the processing speed. var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); + var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase); if (enableThumbnail) { + var batchSize = useLargerBatchSize ? "50" : "24"; if (string.IsNullOrEmpty(vf)) { - vf = "-vf thumbnail=24"; + vf = "-vf thumbnail=" + batchSize; } else { - vf += ",thumbnail=24"; + vf += ",thumbnail=" + batchSize; } } From 060f6c194f186eccd4eede7426a65e3496fdcf45 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Wed, 9 Dec 2020 16:37:15 +0800 Subject: [PATCH 0691/1930] Apply suggestions from code review Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 4c804371ed..fbd08a97c7 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -605,9 +605,9 @@ namespace MediaBrowser.MediaEncoding.Encoder // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. // mpegts need larger batch size otherwise the corrupted thumbnail will be created. Larger batch size will lower the processing speed. var enableThumbnail = useIFrame && !string.Equals("wtv", container, StringComparison.OrdinalIgnoreCase); - var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase); if (enableThumbnail) { + var useLargerBatchSize = string.Equals("mpegts", container, StringComparison.OrdinalIgnoreCase); var batchSize = useLargerBatchSize ? "50" : "24"; if (string.IsNullOrEmpty(vf)) { From aa5fa7cb8fd42200520a9b0d76aa38d23023eecc Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 9 Dec 2020 07:36:31 -0700 Subject: [PATCH 0692/1930] Update to dotnet 5.0.1 --- .../Emby.Server.Implementations.csproj | 2 +- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- Jellyfin.Data/Jellyfin.Data.csproj | 4 ++-- .../Jellyfin.Server.Implementations.csproj | 4 ++-- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++-- deployment/Dockerfile.debian.amd64 | 2 +- deployment/Dockerfile.debian.arm64 | 2 +- deployment/Dockerfile.debian.armhf | 2 +- deployment/Dockerfile.linux.amd64 | 2 +- deployment/Dockerfile.macos | 2 +- deployment/Dockerfile.portable | 2 +- deployment/Dockerfile.ubuntu.amd64 | 2 +- deployment/Dockerfile.ubuntu.arm64 | 2 +- deployment/Dockerfile.ubuntu.armhf | 2 +- deployment/Dockerfile.windows.amd64 | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 16 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 91c4648c62..9e9452f32c 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -31,7 +31,7 @@ <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" /> - <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index da6e5fa2d4..b4f2817f71 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -16,7 +16,7 @@ <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.0" /> + <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 89d6f4d9b7..572038d001 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -41,8 +41,8 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.0" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.1" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.1" /> </ItemGroup> <ItemGroup> diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index e663798da0..5f508ea0a5 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -25,11 +25,11 @@ <ItemGroup> <PackageReference Include="System.Linq.Async" Version="5.0.0" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0"> + <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0"> + <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 03d06fdff3..97fb56ba1e 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -40,8 +40,8 @@ <PackageReference Include="CommandLineParser" Version="2.8.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.0" /> - <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="5.0.0" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.1" /> + <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="5.0.1" /> <PackageReference Include="prometheus-net" Version="4.0.0" /> <PackageReference Include="prometheus-net.AspNetCore" Version="4.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index f0d9188c17..d2f98ca827 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index 8132ee8873..ffc94e0889 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 31f534838b..b25f59329a 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 2bedafcc5a..2e993c25df 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index d470f9b749..f2bbe7f243 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index d2007c0751..603becedf1 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index 084159d459..a6c7cc5d43 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index c2caf4cf8e..3a80058166 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 719b3a85b6..22b9e7ea8b 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index e6905c906d..b1ca610533 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/820db713-c9a5-466e-b72a-16f2f5ed00e2/628aa2a75f6aa270e77f4a83b3742fb8/dotnet-sdk-5.0.100-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 7c552ec060..90222d5c8d 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -16,7 +16,7 @@ <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.0" /> + <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> <PackageReference Include="xunit" Version="2.4.1" /> From 681a0f3e75f3675c449aba426ceb8fe3241d470c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 9 Dec 2020 19:57:25 -0700 Subject: [PATCH 0693/1930] Add nullable guid test --- .../Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs index fc17573fb9..1e1cde9572 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs @@ -57,5 +57,13 @@ namespace Jellyfin.Common.Tests.Json var str = JsonSerializer.Serialize(guid, _options); Assert.Equal($"\"{guid:N}\"", str); } + + [Fact] + public void Serialize_Nullable_Success() + { + Guid? guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA"); + var str = JsonSerializer.Serialize(guid, _options); + Assert.Equal($"\"{guid:N}\"", str); + } } } From 2478c8fa644b7f08100dcd001d08b021bf87b36e Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 9 Dec 2020 23:15:33 -0700 Subject: [PATCH 0694/1930] Fix inverted condition when authenticating with an ApiKey --- .../HttpServer/Security/AuthorizationContext.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index d62e2eefe4..024404ceb0 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -185,11 +185,11 @@ namespace Emby.Server.Implementations.HttpServer.Security updateToken = true; } - authInfo.IsApiKey = true; + authInfo.IsApiKey = false; } else { - authInfo.IsApiKey = false; + authInfo.IsApiKey = true; } if (updateToken) From 3c5bbeb80ccde3a97d766cdd7d99b514b20ac85d Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 10 Dec 2020 13:38:33 +0100 Subject: [PATCH 0695/1930] Remove ImageFetcherPostScanTask --- .../Library/ImageFetcherPostScanTask.cs | 130 ------------------ .../Library/LibraryManager.cs | 10 +- .../Library/ILibraryManager.cs | 2 +- .../Manager/MetadataService.cs | 17 ++- 4 files changed, 14 insertions(+), 145 deletions(-) delete mode 100644 Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs diff --git a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs b/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs deleted file mode 100644 index d4e790c9a6..0000000000 --- a/Emby.Server.Implementations/Library/ImageFetcherPostScanTask.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Jellyfin.Data.Events; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Net; -using Microsoft.Extensions.Logging; - -namespace Emby.Server.Implementations.Library -{ - /// <summary> - /// A library post scan/refresh task for pre-fetching remote images. - /// </summary> - public class ImageFetcherPostScanTask : ILibraryPostScanTask - { - private readonly ILibraryManager _libraryManager; - private readonly IProviderManager _providerManager; - private readonly ILogger<ImageFetcherPostScanTask> _logger; - private readonly SemaphoreSlim _imageFetcherLock; - - private ConcurrentDictionary<Guid, (BaseItem item, ItemUpdateType updateReason)> _queuedItems; - - /// <summary> - /// Initializes a new instance of the <see cref="ImageFetcherPostScanTask"/> class. - /// </summary> - /// <param name="libraryManager">An instance of <see cref="ILibraryManager"/>.</param> - /// <param name="providerManager">An instance of <see cref="IProviderManager"/>.</param> - /// <param name="logger">An instance of <see cref="ILogger{ImageFetcherPostScanTask}"/>.</param> - public ImageFetcherPostScanTask( - ILibraryManager libraryManager, - IProviderManager providerManager, - ILogger<ImageFetcherPostScanTask> logger) - { - _libraryManager = libraryManager; - _providerManager = providerManager; - _logger = logger; - _queuedItems = new ConcurrentDictionary<Guid, (BaseItem item, ItemUpdateType updateReason)>(); - _imageFetcherLock = new SemaphoreSlim(1, 1); - _libraryManager.ItemAdded += OnLibraryManagerItemAddedOrUpdated; - _libraryManager.ItemUpdated += OnLibraryManagerItemAddedOrUpdated; - _providerManager.RefreshCompleted += OnProviderManagerRefreshCompleted; - } - - /// <inheritdoc /> - public async Task Run(IProgress<double> progress, CancellationToken cancellationToken) - { - // Sometimes a library scan will cause this to run twice if there's an item refresh going on. - await _imageFetcherLock.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - var now = DateTime.UtcNow; - var itemGuids = _queuedItems.Keys.ToList(); - - for (var i = 0; i < itemGuids.Count; i++) - { - if (!_queuedItems.TryGetValue(itemGuids[i], out var queuedItem)) - { - continue; - } - - var itemId = queuedItem.item.Id.ToString("N", CultureInfo.InvariantCulture); - var itemType = queuedItem.item.GetType(); - _logger.LogDebug( - "Updating remote images for item {ItemId} with media type {ItemMediaType}", - itemId, - itemType); - try - { - await _libraryManager.UpdateImagesAsync(queuedItem.item, queuedItem.updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to fetch images for {Type} item with id {ItemId}", itemType, itemId); - } - - _queuedItems.TryRemove(queuedItem.item.Id, out _); - } - - if (itemGuids.Count > 0) - { - _logger.LogInformation( - "Finished updating/pre-fetching {NumberOfImages} images. Elapsed time: {TimeElapsed}s.", - itemGuids.Count.ToString(CultureInfo.InvariantCulture), - (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture)); - } - else - { - _logger.LogDebug("No images were updated."); - } - } - finally - { - _imageFetcherLock.Release(); - } - } - - private void OnLibraryManagerItemAddedOrUpdated(object sender, ItemChangeEventArgs itemChangeEventArgs) - { - if (!_queuedItems.ContainsKey(itemChangeEventArgs.Item.Id) && itemChangeEventArgs.Item.ImageInfos.Length > 0) - { - _queuedItems.AddOrUpdate( - itemChangeEventArgs.Item.Id, - (itemChangeEventArgs.Item, itemChangeEventArgs.UpdateReason), - (key, existingValue) => existingValue); - } - } - - private void OnProviderManagerRefreshCompleted(object sender, GenericEventArgs<BaseItem> e) - { - if (!_queuedItems.ContainsKey(e.Argument.Id) && e.Argument.ImageInfos.Length > 0) - { - _queuedItems.AddOrUpdate( - e.Argument.Id, - (e.Argument, ItemUpdateType.None), - (key, existingValue) => existingValue); - } - - // The RefreshCompleted event is a bit awkward in that it seems to _only_ be fired on - // the item that was refreshed regardless of children refreshes. So we take it as a signal - // that the refresh is entirely completed. - Run(null, CancellationToken.None).GetAwaiter().GetResult(); - } - } -} diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 5b926b0f4f..47184b7892 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1955,9 +1955,9 @@ namespace Emby.Server.Implementations.Library } /// <inheritdoc /> - public Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) + public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) { - RunMetadataSavers(items, updateReason); + await RunMetadataSavers(items, updateReason).ConfigureAwait(false); _itemRepository.SaveItems(items, cancellationToken); @@ -1988,15 +1988,13 @@ namespace Emby.Server.Implementations.Library } } } - - return Task.CompletedTask; } /// <inheritdoc /> public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken); - public void RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason) + public async Task RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason) { foreach (var item in items) { @@ -2006,6 +2004,8 @@ namespace Emby.Server.Implementations.Library } item.DateLastSaved = DateTime.UtcNow; + + await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); } } diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 24b101694d..ff80952f76 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -571,7 +571,7 @@ namespace MediaBrowser.Controller.Library string videoPath, string[] files); - void RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason); + Task RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason); BaseItem GetParentItem(string parentId, Guid? userId); diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 6dbce3067e..e78eae4fd1 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -232,6 +232,7 @@ namespace MediaBrowser.Providers.Manager private Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) { var personsToSave = new List<BaseItem>(); + var personsToSaveWithImages = new List<BaseItem>(); foreach (var person in people) { @@ -239,14 +240,13 @@ namespace MediaBrowser.Providers.Manager if (person.ProviderIds.Count > 0 || !string.IsNullOrWhiteSpace(person.ImageUrl)) { - var saveEntity = false; var personEntity = LibraryManager.GetPerson(person.Name); foreach (var id in person.ProviderIds) { if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) { personEntity.SetProviderId(id.Key, id.Value); - saveEntity = true; + personsToSave.Add(personEntity); } } @@ -260,18 +260,17 @@ namespace MediaBrowser.Providers.Manager }, 0); - saveEntity = true; - } - - if (saveEntity) - { - personsToSave.Add(personEntity); + personsToSaveWithImages.Add(personEntity); } } } + // This is a little ugly, but it saves a lot of I/O with the db by doing this in bulk. + // To avoid updating images for no reason, we differentiate between the two item update types. LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload); - LibraryManager.CreateItems(personsToSave, null, CancellationToken.None); + LibraryManager.RunMetadataSavers(personsToSaveWithImages, ItemUpdateType.ImageUpdate); + + LibraryManager.CreateItems(personsToSave.Concat(personsToSaveWithImages).ToList(), null, CancellationToken.None); return Task.CompletedTask; } From dd238937f4739291dd4eab337d8be00194951761 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 10 Dec 2020 13:44:58 +0100 Subject: [PATCH 0696/1930] Remember to await the async task --- MediaBrowser.Providers/Manager/MetadataService.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index e78eae4fd1..a1cd0b2eac 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -229,7 +229,7 @@ namespace MediaBrowser.Providers.Manager await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false); } - private Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) + private async Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) { var personsToSave = new List<BaseItem>(); var personsToSaveWithImages = new List<BaseItem>(); @@ -267,11 +267,10 @@ namespace MediaBrowser.Providers.Manager // This is a little ugly, but it saves a lot of I/O with the db by doing this in bulk. // To avoid updating images for no reason, we differentiate between the two item update types. - LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload); - LibraryManager.RunMetadataSavers(personsToSaveWithImages, ItemUpdateType.ImageUpdate); + await LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload).ConfigureAwait(false); + await LibraryManager.RunMetadataSavers(personsToSaveWithImages, ItemUpdateType.ImageUpdate).ConfigureAwait(false); LibraryManager.CreateItems(personsToSave.Concat(personsToSaveWithImages).ToList(), null, CancellationToken.None); - return Task.CompletedTask; } protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) From 3e062bc0cd369910f66eb6abb35f05991f7c70fb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 10 Dec 2020 12:57:44 +0000 Subject: [PATCH 0697/1930] Bump Microsoft.NET.Test.Sdk from 16.8.0 to 16.8.3 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.8.0 to 16.8.3. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.8.0...v16.8.3) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 90222d5c8d..b5e8e521ca 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index e8eca67600..af4684f562 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index 6e3fac43d4..1ec88dada5 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index f91db6744a..8c9dc48201 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -8,7 +8,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index e88de38112..c934ea1c24 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -19,7 +19,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 567cf34ef3..6118581e12 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index 48b0b4c7d6..90782f6bbc 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <PackageReference Include="coverlet.collector" Version="1.3.0" /> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 310219e742..bcd12deaf7 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -16,7 +16,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.14.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="Moq" Version="4.15.2" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> From 3f6e6c48393f0cabadb10f95cd3b98b8a1cdd7b3 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 10 Dec 2020 14:47:47 +0100 Subject: [PATCH 0698/1930] Simplify --- .../Library/LibraryManager.cs | 23 +++++++++---------- .../Library/ILibraryManager.cs | 2 +- .../Manager/MetadataService.cs | 21 +++++++++-------- 3 files changed, 24 insertions(+), 22 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 47184b7892..db27862ce7 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -42,7 +42,6 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Library; -using MediaBrowser.Model.Net; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Tasks; using MediaBrowser.Providers.MediaInfo; @@ -1957,7 +1956,10 @@ namespace Emby.Server.Implementations.Library /// <inheritdoc /> public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) { - await RunMetadataSavers(items, updateReason).ConfigureAwait(false); + foreach (var item in items) + { + await RunMetadataSavers(item, updateReason).ConfigureAwait(false); + } _itemRepository.SaveItems(items, cancellationToken); @@ -1994,19 +1996,16 @@ namespace Emby.Server.Implementations.Library public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken); - public async Task RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason) + public Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason) { - foreach (var item in items) + if (item.IsFileProtocol) { - if (item.IsFileProtocol) - { - ProviderManager.SaveMetadata(item, updateReason); - } - - item.DateLastSaved = DateTime.UtcNow; - - await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false); + ProviderManager.SaveMetadata(item, updateReason); } + + item.DateLastSaved = DateTime.UtcNow; + + return UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate); } /// <summary> diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index ff80952f76..6700761fcc 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -571,7 +571,7 @@ namespace MediaBrowser.Controller.Library string videoPath, string[] files); - Task RunMetadataSavers(IReadOnlyList<BaseItem> items, ItemUpdateType updateReason); + Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason); BaseItem GetParentItem(string parentId, Guid? userId); diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index a1cd0b2eac..8b3ca17ca1 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -232,7 +232,6 @@ namespace MediaBrowser.Providers.Manager private async Task SavePeopleMetadataAsync(List<PersonInfo> people, LibraryOptions libraryOptions, CancellationToken cancellationToken) { var personsToSave = new List<BaseItem>(); - var personsToSaveWithImages = new List<BaseItem>(); foreach (var person in people) { @@ -240,13 +239,15 @@ namespace MediaBrowser.Providers.Manager if (person.ProviderIds.Count > 0 || !string.IsNullOrWhiteSpace(person.ImageUrl)) { + var itemUpdateType = ItemUpdateType.MetadataDownload; + var saveEntity = false; var personEntity = LibraryManager.GetPerson(person.Name); foreach (var id in person.ProviderIds) { if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) { personEntity.SetProviderId(id.Key, id.Value); - personsToSave.Add(personEntity); + saveEntity = true; } } @@ -260,17 +261,19 @@ namespace MediaBrowser.Providers.Manager }, 0); - personsToSaveWithImages.Add(personEntity); + saveEntity = true; + itemUpdateType = ItemUpdateType.ImageUpdate; + } + + if (saveEntity) + { + personsToSave.Add(personEntity); + await LibraryManager.RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); } } } - // This is a little ugly, but it saves a lot of I/O with the db by doing this in bulk. - // To avoid updating images for no reason, we differentiate between the two item update types. - await LibraryManager.RunMetadataSavers(personsToSave, ItemUpdateType.MetadataDownload).ConfigureAwait(false); - await LibraryManager.RunMetadataSavers(personsToSaveWithImages, ItemUpdateType.ImageUpdate).ConfigureAwait(false); - - LibraryManager.CreateItems(personsToSave.Concat(personsToSaveWithImages).ToList(), null, CancellationToken.None); + LibraryManager.CreateItems(personsToSave, null, CancellationToken.None); } protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) From 0332b7250234370d4f01dc0daad97da862c22997 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 10 Dec 2020 22:41:00 +0800 Subject: [PATCH 0699/1930] fix landing screen options --- .../DisplayPreferencesController.cs | 22 ++-- .../Entities/ItemDisplayPreferences.cs | 1 - Jellyfin.Data/Enums/ViewType.cs | 101 +++++++++++++++--- 3 files changed, 95 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 8b8f63015e..9b5c422206 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -12,6 +12,7 @@ using MediaBrowser.Model.Entities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; namespace Jellyfin.Api.Controllers { @@ -22,14 +23,17 @@ namespace Jellyfin.Api.Controllers public class DisplayPreferencesController : BaseJellyfinApiController { private readonly IDisplayPreferencesManager _displayPreferencesManager; + private readonly ILogger<DisplayPreferencesController> _logger; /// <summary> /// Initializes a new instance of the <see cref="DisplayPreferencesController"/> class. /// </summary> /// <param name="displayPreferencesManager">Instance of <see cref="IDisplayPreferencesManager"/> interface.</param> - public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager) + /// <param name="logger">Instance of <see cref="ILogger{DisplayPreferencesController}"/> interface.</param> + public DisplayPreferencesController(IDisplayPreferencesManager displayPreferencesManager, ILogger<DisplayPreferencesController> logger) { _displayPreferencesManager = displayPreferencesManager; + _logger = logger; } /// <summary> @@ -61,7 +65,6 @@ namespace Jellyfin.Api.Controllers { Client = displayPreferences.Client, Id = displayPreferences.ItemId.ToString(), - ViewType = itemPreferences.ViewType.ToString(), SortBy = itemPreferences.SortBy, SortOrder = itemPreferences.SortOrder, IndexBy = displayPreferences.IndexBy?.ToString(), @@ -77,11 +80,6 @@ namespace Jellyfin.Api.Controllers dto.CustomPrefs["homesection" + homeSection.Order] = homeSection.Type.ToString().ToLowerInvariant(); } - foreach (var itemDisplayPreferences in _displayPreferencesManager.ListItemDisplayPreferences(displayPreferences.UserId, displayPreferences.Client)) - { - dto.CustomPrefs["landing-" + itemDisplayPreferences.ItemId] = itemDisplayPreferences.ViewType.ToString().ToLowerInvariant(); - } - dto.CustomPrefs["chromecastVersion"] = displayPreferences.ChromecastVersion.ToString().ToLowerInvariant(); dto.CustomPrefs["skipForwardLength"] = displayPreferences.SkipForwardLength.ToString(CultureInfo.InvariantCulture); dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture); @@ -189,10 +187,9 @@ namespace Jellyfin.Api.Controllers foreach (var key in displayPreferences.CustomPrefs.Keys.Where(key => key.StartsWith("landing-", StringComparison.OrdinalIgnoreCase))) { - if (Guid.TryParse(key.AsSpan().Slice("landing-".Length), out var preferenceId)) + if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out var type)) { - var itemPreferences = _displayPreferencesManager.GetItemDisplayPreferences(existingDisplayPreferences.UserId, preferenceId, existingDisplayPreferences.Client); - itemPreferences.ViewType = Enum.Parse<ViewType>(displayPreferences.ViewType); + _logger.LogError("Invaild ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]); displayPreferences.CustomPrefs.Remove(key); } } @@ -204,11 +201,6 @@ namespace Jellyfin.Api.Controllers itemPrefs.RememberSorting = displayPreferences.RememberSorting; itemPrefs.ItemId = itemId; - if (Enum.TryParse<ViewType>(displayPreferences.ViewType, true, out var viewType)) - { - itemPrefs.ViewType = viewType; - } - // Set all remaining custom preferences. _displayPreferencesManager.SetCustomItemDisplayPreferences(userId, itemId, existingDisplayPreferences.Client, displayPreferences.CustomPrefs); _displayPreferencesManager.SaveChanges(); diff --git a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs index d81e4a31c4..2b25bb25f2 100644 --- a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs @@ -23,7 +23,6 @@ namespace Jellyfin.Data.Entities Client = client; SortBy = "SortName"; - ViewType = ViewType.Poster; SortOrder = SortOrder.Ascending; RememberSorting = false; RememberIndexing = false; diff --git a/Jellyfin.Data/Enums/ViewType.cs b/Jellyfin.Data/Enums/ViewType.cs index 595429ab1b..c0fd7d448b 100644 --- a/Jellyfin.Data/Enums/ViewType.cs +++ b/Jellyfin.Data/Enums/ViewType.cs @@ -1,4 +1,4 @@ -namespace Jellyfin.Data.Enums +namespace Jellyfin.Data.Enums { /// <summary> /// An enum representing the type of view for a library or collection. @@ -6,33 +6,108 @@ public enum ViewType { /// <summary> - /// Shows banners. + /// Shows albums. /// </summary> - Banner = 0, + Albums = 0, /// <summary> - /// Shows a list of content. + /// Shows album artists. /// </summary> - List = 1, + AlbumArtists = 1, /// <summary> - /// Shows poster artwork. + /// Shows artists. /// </summary> - Poster = 2, + Artists = 2, /// <summary> - /// Shows poster artwork with a card containing the name and year. + /// Shows channels. /// </summary> - PosterCard = 3, + Channels = 3, /// <summary> - /// Shows a thumbnail. + /// Shows collections. /// </summary> - Thumb = 4, + Collections = 4, /// <summary> - /// Shows a thumbnail with a card containing the name and year. + /// Shows episodes. /// </summary> - ThumbCard = 5 + Episodes = 5, + + /// <summary> + /// Shows favorites. + /// </summary> + Favorites = 6, + + /// <summary> + /// Shows genres. + /// </summary> + Genres = 7, + + /// <summary> + /// Shows guide. + /// </summary> + Guide = 8, + + /// <summary> + /// Shows movies. + /// </summary> + Movies = 9, + + /// <summary> + /// Shows networks. + /// </summary> + Networks = 10, + + /// <summary> + /// Shows playlists. + /// </summary> + Playlists = 11, + + /// <summary> + /// Shows programs. + /// </summary> + Programs = 12, + + /// <summary> + /// Shows recordings. + /// </summary> + Recordings = 13, + + /// <summary> + /// Shows schedule. + /// </summary> + Schedule = 14, + + /// <summary> + /// Shows series. + /// </summary> + Series = 15, + + /// <summary> + /// Shows shows. + /// </summary> + Shows = 16, + + /// <summary> + /// Shows songs. + /// </summary> + Songs = 17, + + /// <summary> + /// Shows songs. + /// </summary> + Suggestions = 18, + + /// <summary> + /// Shows trailers. + /// </summary> + Trailers = 19, + + /// <summary> + /// Shows upcoming. + /// </summary> + Upcoming = 20 } } From b66abf0556802f2278acdfed9fb5d4292cd3f122 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 10 Dec 2020 08:17:02 -0700 Subject: [PATCH 0700/1930] Add support back for /emby and /mediabrowser routes --- .../ApiApplicationBuilderExtensions.cs | 13 +++++ .../Middleware/PathTrimMiddleware.cs | 54 +++++++++++++++++++ Jellyfin.Server/Startup.cs | 2 + 3 files changed, 69 insertions(+) create mode 100644 Jellyfin.Server/Middleware/PathTrimMiddleware.cs diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index a56e159590..492adfbffc 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -117,5 +117,18 @@ namespace Jellyfin.Server.Extensions { return appBuilder.UseMiddleware<RobotsRedirectionMiddleware>(); } + + /// <summary> + /// Adds /emby and /mediabrowser route trimming to the application pipeline. + /// </summary> + /// <remarks> + /// This must be injected before any path related middleware. + /// </remarks> + /// <param name="appBuilder">The application builder.</param> + /// <returns>The updated application builder.</returns> + public static IApplicationBuilder UsePathTrim(this IApplicationBuilder appBuilder) + { + return appBuilder.UseMiddleware<PathTrimMiddleware>(); + } } } diff --git a/Jellyfin.Server/Middleware/PathTrimMiddleware.cs b/Jellyfin.Server/Middleware/PathTrimMiddleware.cs new file mode 100644 index 0000000000..6360cba500 --- /dev/null +++ b/Jellyfin.Server/Middleware/PathTrimMiddleware.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Middleware +{ + /// <summary> + /// Removes /emby and /mediabrowser from requested route. + /// </summary> + public class PathTrimMiddleware + { + private const string EmbyPath = "/emby"; + private const string MediabrowserPath = "/mediabrowser"; + + private readonly RequestDelegate _next; + private readonly ILogger<PathTrimMiddleware> _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="PathTrimMiddleware"/> class. + /// </summary> + /// <param name="next">The next delegate in the pipeline.</param> + /// <param name="logger">The logger.</param> + public PathTrimMiddleware( + RequestDelegate next, + ILogger<PathTrimMiddleware> logger) + { + _next = next; + _logger = logger; + } + + /// <summary> + /// Executes the middleware action. + /// </summary> + /// <param name="httpContext">The current HTTP context.</param> + /// <returns>The async task.</returns> + public async Task Invoke(HttpContext httpContext) + { + var localPath = httpContext.Request.Path.ToString(); + if (localPath.StartsWith(EmbyPath, StringComparison.OrdinalIgnoreCase)) + { + httpContext.Request.Path = localPath[EmbyPath.Length..]; + _logger.LogDebug("Removing {EmbyPath} from route.", EmbyPath); + } + else if (localPath.StartsWith(MediabrowserPath, StringComparison.OrdinalIgnoreCase)) + { + httpContext.Request.Path = localPath[MediabrowserPath.Length..]; + _logger.LogDebug("Removing {MediabrowserPath} from route.", MediabrowserPath); + } + + await _next(httpContext).ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 306a52ce8f..3395d2413f 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -128,6 +128,8 @@ namespace Jellyfin.Server mainApp.UseHttpsRedirection(); } + // This must be injected before any path related middleware. + mainApp.UsePathTrim(); mainApp.UseStaticFiles(); if (appConfig.HostWebClient()) { From a9aafbaf5a6c7c90e815a4844c7f71215ee25420 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 10 Dec 2020 08:25:05 -0700 Subject: [PATCH 0701/1930] Don't throw exception unless needed --- .../LiveTv/Listings/SchedulesDirect.cs | 31 ++++++++----------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 2073b9ef1c..90e6cc9668 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -611,30 +611,25 @@ namespace Emby.Server.Implementations.LiveTv.Listings CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) { - HttpResponseMessage response = null; - try + var response = await _httpClientFactory.CreateClient(NamedClient.Default) + .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false); + if (response.IsSuccessStatusCode) { - response = await _httpClientFactory.CreateClient(NamedClient.Default) - .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false); - response.EnsureSuccessStatusCode(); return response; } - catch (HttpRequestException ex) + + // Response is automatically disposed in the calling function, + // so dispose manually if not returning. + response.Dispose(); + if (!enableRetry || (int)response.StatusCode >= 500) { - response?.Dispose(); - _tokens.Clear(); - - if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500) - { - enableRetry = false; - } - - if (!enableRetry) - { - throw; - } + throw new HttpRequestException( + string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase), + null, + response.StatusCode); } + _tokens.Clear(); options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false)); return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false); } From 15a3d8d62680fb7eec911ca65ac1cd1ef12be507 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Thu, 10 Dec 2020 18:02:12 +0100 Subject: [PATCH 0702/1930] Forgot to revert some other changes, dunno if needed --- MediaBrowser.Controller/Entities/BaseItem.cs | 1 + MediaBrowser.Controller/Entities/Folder.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index d8fad3bfbb..1b25fbdbb7 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1385,6 +1385,7 @@ namespace MediaBrowser.Controller.Entities new List<FileSystemMetadata>(); var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false); + await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh if (ownedItemsChanged) { diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 23f4c00c10..57d04ddfac 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -354,6 +354,11 @@ namespace MediaBrowser.Controller.Entities { await currentChild.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false); } + else + { + // metadata is up-to-date; make sure DB has correct images dimensions and hash + await LibraryManager.UpdateImagesAsync(currentChild).ConfigureAwait(false); + } continue; } From 0d2106a2727f572ef556845d6dd49c224d3d4d96 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 10 Dec 2020 11:36:31 -0700 Subject: [PATCH 0703/1930] Allow playlist to be created by query string --- .../Controllers/PlaylistsController.cs | 28 +++++++++++++++---- .../Models/PlaylistDtos/CreatePlaylistDto.cs | 2 +- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index 3e55434c06..fcdad4bc72 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; @@ -17,6 +18,7 @@ using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Jellyfin.Api.Controllers { @@ -53,6 +55,13 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Creates a new playlist. /// </summary> + /// <remarks> + /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence. + /// </remarks> + /// <param name="name">The playlist name.</param> + /// <param name="ids">The item ids.</param> + /// <param name="userId">The user id.</param> + /// <param name="mediaType">The media type.</param> /// <param name="createPlaylistRequest">The create playlist payload.</param> /// <returns> /// A <see cref="Task" /> that represents the asynchronous operation to create a playlist. @@ -61,14 +70,23 @@ namespace Jellyfin.Api.Controllers [HttpPost] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<ActionResult<PlaylistCreationResult>> CreatePlaylist( - [FromBody, Required] CreatePlaylistDto createPlaylistRequest) + [FromQuery] string? name, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] IReadOnlyList<Guid> ids, + [FromQuery] Guid? userId, + [FromQuery] string? mediaType, + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest) { + if (ids.Count == 0) + { + ids = createPlaylistRequest?.Ids ?? Array.Empty<Guid>(); + } + var result = await _playlistManager.CreatePlaylist(new PlaylistCreationRequest { - Name = createPlaylistRequest.Name, - ItemIdList = createPlaylistRequest.Ids, - UserId = createPlaylistRequest.UserId, - MediaType = createPlaylistRequest.MediaType + Name = name ?? createPlaylistRequest?.Name, + ItemIdList = ids, + UserId = userId ?? createPlaylistRequest?.UserId ?? default, + MediaType = mediaType ?? createPlaylistRequest?.MediaType }).ConfigureAwait(false); return result; diff --git a/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs index d0d6889fc8..65d4b644e4 100644 --- a/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs +++ b/Jellyfin.Api/Models/PlaylistDtos/CreatePlaylistDto.cs @@ -24,7 +24,7 @@ namespace Jellyfin.Api.Models.PlaylistDtos /// <summary> /// Gets or sets the user id. /// </summary> - public Guid UserId { get; set; } + public Guid? UserId { get; set; } /// <summary> /// Gets or sets the media type. From 297b7ea6fa81700e3b4cd4d86250495137499878 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 10 Dec 2020 11:36:58 -0700 Subject: [PATCH 0704/1930] Fix empty body for PlaybackInfo --- Jellyfin.Api/Controllers/MediaInfoController.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index a76dc057a0..2a1da31c9e 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -17,6 +17,7 @@ using MediaBrowser.Model.MediaInfo; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; namespace Jellyfin.Api.Controllers @@ -119,7 +120,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableTranscoding, [FromQuery] bool? allowVideoStreamCopy, [FromQuery] bool? allowAudioStreamCopy, - [FromBody] PlaybackInfoDto? playbackInfoDto) + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] PlaybackInfoDto? playbackInfoDto) { var authInfo = _authContext.GetAuthorizationInfo(Request); From abcbb9f1569f88f85071f450ba808cb268ba172a Mon Sep 17 00:00:00 2001 From: kaboom83 <kaboom083@gmail.com> Date: Thu, 10 Dec 2020 21:22:25 +0000 Subject: [PATCH 0705/1930] Translated using Weblate (Slovenian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sl/ --- Emby.Server.Implementations/Localization/Core/sl-SI.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sl-SI.json b/Emby.Server.Implementations/Localization/Core/sl-SI.json index 66681f0251..343e067b79 100644 --- a/Emby.Server.Implementations/Localization/Core/sl-SI.json +++ b/Emby.Server.Implementations/Localization/Core/sl-SI.json @@ -113,5 +113,10 @@ "TasksApplicationCategory": "Aplikacija", "TasksLibraryCategory": "Knjižnica", "TasksMaintenanceCategory": "Vzdrževanje", - "TaskDownloadMissingSubtitlesDescription": "Na podlagi nastavitev metapodatkov poišče manjkajoče podnapise na internetu." + "TaskDownloadMissingSubtitlesDescription": "Na podlagi nastavitev metapodatkov poišče manjkajoče podnapise na internetu.", + "TaskCleanActivityLogDescription": "Počisti zapise v dnevniku aktivnosti starejše od nastavljenega časa.", + "TaskCleanActivityLog": "Počisti dnevnik aktivnosti", + "Undefined": "Nedoločen", + "Forced": "Prisilno", + "Default": "Privzeto" } From 34029f860c1c870e7c50aaa4aaf1188e7e8c72b4 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 10 Dec 2020 19:05:49 -0700 Subject: [PATCH 0706/1930] Fix openapi file schema --- Jellyfin.Server/Filters/FileResponseFilter.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Filters/FileResponseFilter.cs b/Jellyfin.Server/Filters/FileResponseFilter.cs index 7ad9466c17..eae9a80048 100644 --- a/Jellyfin.Server/Filters/FileResponseFilter.cs +++ b/Jellyfin.Server/Filters/FileResponseFilter.cs @@ -14,7 +14,8 @@ namespace Jellyfin.Server.Filters { Schema = new OpenApiSchema { - Type = "file" + Type = "string", + Format = "binary" } }; From a79c210c7669dca482a7655ed6118cf7713c2e77 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Fri, 11 Dec 2020 11:35:00 +0800 Subject: [PATCH 0707/1930] fix typo Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Jellyfin.Api/Controllers/DisplayPreferencesController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index 9b5c422206..f7bb968f0b 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -189,7 +189,7 @@ namespace Jellyfin.Api.Controllers { if (!Enum.TryParse<ViewType>(displayPreferences.CustomPrefs[key], true, out var type)) { - _logger.LogError("Invaild ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]); + _logger.LogError("Invalid ViewType: {LandingScreenOption}", displayPreferences.CustomPrefs[key]); displayPreferences.CustomPrefs.Remove(key); } } From 69d581033b227c38cf810d4943aebe9aa421e33a Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 11 Dec 2020 07:17:06 -0700 Subject: [PATCH 0708/1930] Use a more descriptive middleware name --- .../Extensions/ApiApplicationBuilderExtensions.cs | 2 +- ...ddleware.cs => LegacyEmbyRouteRewriteMiddleware.cs} | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) rename Jellyfin.Server/Middleware/{PathTrimMiddleware.cs => LegacyEmbyRouteRewriteMiddleware.cs} (83%) diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 492adfbffc..88e2b4152b 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -128,7 +128,7 @@ namespace Jellyfin.Server.Extensions /// <returns>The updated application builder.</returns> public static IApplicationBuilder UsePathTrim(this IApplicationBuilder appBuilder) { - return appBuilder.UseMiddleware<PathTrimMiddleware>(); + return appBuilder.UseMiddleware<LegacyEmbyRouteRewriteMiddleware>(); } } } diff --git a/Jellyfin.Server/Middleware/PathTrimMiddleware.cs b/Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs similarity index 83% rename from Jellyfin.Server/Middleware/PathTrimMiddleware.cs rename to Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs index 6360cba500..fdd8974d2b 100644 --- a/Jellyfin.Server/Middleware/PathTrimMiddleware.cs +++ b/Jellyfin.Server/Middleware/LegacyEmbyRouteRewriteMiddleware.cs @@ -8,22 +8,22 @@ namespace Jellyfin.Server.Middleware /// <summary> /// Removes /emby and /mediabrowser from requested route. /// </summary> - public class PathTrimMiddleware + public class LegacyEmbyRouteRewriteMiddleware { private const string EmbyPath = "/emby"; private const string MediabrowserPath = "/mediabrowser"; private readonly RequestDelegate _next; - private readonly ILogger<PathTrimMiddleware> _logger; + private readonly ILogger<LegacyEmbyRouteRewriteMiddleware> _logger; /// <summary> - /// Initializes a new instance of the <see cref="PathTrimMiddleware"/> class. + /// Initializes a new instance of the <see cref="LegacyEmbyRouteRewriteMiddleware"/> class. /// </summary> /// <param name="next">The next delegate in the pipeline.</param> /// <param name="logger">The logger.</param> - public PathTrimMiddleware( + public LegacyEmbyRouteRewriteMiddleware( RequestDelegate next, - ILogger<PathTrimMiddleware> logger) + ILogger<LegacyEmbyRouteRewriteMiddleware> logger) { _next = next; _logger = logger; From ac2593e3703adba38c27675fdc46c83b235ec659 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 11 Dec 2020 08:06:04 -0700 Subject: [PATCH 0709/1930] Set convolveAlpha to true --- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index ee60748c71..eab5777d5d 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -435,7 +435,7 @@ namespace Jellyfin.Drawing.Skia 0f, kernelOffset, SKShaderTileMode.Clamp, - false); + true); canvas.DrawBitmap( source, From 76f61eb0d6941782c3d3187e16a22333c8b13b4c Mon Sep 17 00:00:00 2001 From: Patrick Barron <barronpm@gmail.com> Date: Fri, 11 Dec 2020 10:15:43 -0500 Subject: [PATCH 0710/1930] Convert DeleteUser to async --- Jellyfin.Api/Controllers/UserController.cs | 4 ++-- Jellyfin.Server.Implementations/Users/UserManager.cs | 8 ++++---- MediaBrowser.Controller/Library/IUserManager.cs | 3 ++- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 0f7c25d0e4..d614174804 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -133,11 +133,11 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult DeleteUser([FromRoute, Required] Guid userId) + public async Task<ActionResult> DeleteUser([FromRoute, Required] Guid userId) { var user = _userManager.GetUserById(userId); _sessionManager.RevokeUserTokens(user.Id, null); - _userManager.DeleteUser(userId); + await _userManager.DeleteUserAsync(userId).ConfigureAwait(false); return NoContent(); } diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index f684d151d6..e37fcc908b 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -220,7 +220,7 @@ namespace Jellyfin.Server.Implementations.Users } /// <inheritdoc/> - public void DeleteUser(Guid userId) + public async Task DeleteUserAsync(Guid userId) { if (!_users.TryGetValue(userId, out var user)) { @@ -246,7 +246,7 @@ namespace Jellyfin.Server.Implementations.Users nameof(userId)); } - using var dbContext = _dbProvider.CreateContext(); + await using var dbContext = _dbProvider.CreateContext(); // Clear all entities related to the user from the database. if (user.ProfileImage != null) @@ -258,10 +258,10 @@ namespace Jellyfin.Server.Implementations.Users dbContext.RemoveRange(user.Preferences); dbContext.RemoveRange(user.AccessSchedules); dbContext.Users.Remove(user); - dbContext.SaveChanges(); + await dbContext.SaveChangesAsync().ConfigureAwait(false); _users.Remove(userId); - _eventManager.Publish(new UserDeletedEventArgs(user)); + await _eventManager.PublishAsync(new UserDeletedEventArgs(user)).ConfigureAwait(false); } /// <inheritdoc/> diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs index 8fd3b8c347..6e267834b0 100644 --- a/MediaBrowser.Controller/Library/IUserManager.cs +++ b/MediaBrowser.Controller/Library/IUserManager.cs @@ -93,7 +93,8 @@ namespace MediaBrowser.Controller.Library /// Deletes the specified user. /// </summary> /// <param name="userId">The id of the user to be deleted.</param> - void DeleteUser(Guid userId); + /// <returns>A task representing the deletion of the user.</returns> + Task DeleteUserAsync(Guid userId); /// <summary> /// Resets the password. From 41218c5613ea7a83804f7b8ee0b61d315db45c0c Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Fri, 11 Dec 2020 23:49:35 +0800 Subject: [PATCH 0711/1930] fix ssl certificate cannot be saved --- .../ApplicationHost.cs | 52 ++++++++++++++----- .../ServerConfigurationManager.cs | 26 ---------- .../Configuration/NetworkConfiguration.cs | 12 ++++- 3 files changed, 51 insertions(+), 39 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d74ea03520..d2f340cd3f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -284,13 +285,6 @@ namespace Emby.Server.Implementations fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); - CertificateInfo = new CertificateInfo - { - Path = ServerConfigurationManager.Configuration.CertificatePath, - Password = ServerConfigurationManager.Configuration.CertificatePassword - }; - Certificate = GetCertificate(CertificateInfo); - ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; ApplicationVersionString = ApplicationVersion.ToString(3); ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; @@ -456,6 +450,7 @@ namespace Emby.Server.Implementations Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false)); ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated; + ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated; _mediaEncoder.SetFFmpegPath(); @@ -505,6 +500,13 @@ namespace Emby.Server.Implementations HttpsPort = NetworkConfiguration.DefaultHttpsPort; } + CertificateInfo = new CertificateInfo + { + Path = networkConfiguration.CertificatePath, + Password = networkConfiguration.CertificatePassword + }; + Certificate = GetCertificate(CertificateInfo); + DiscoverTypes(); RegisterServices(); @@ -912,11 +914,11 @@ namespace Emby.Server.Implementations protected void OnConfigurationUpdated(object sender, EventArgs e) { var requiresRestart = false; + var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); // Don't do anything if these haven't been set yet if (HttpPort != 0 && HttpsPort != 0) { - var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); // Need to restart if ports have changed if (networkConfiguration.HttpServerPortNumber != HttpPort || networkConfiguration.HttpsPortNumber != HttpsPort) @@ -936,10 +938,7 @@ namespace Emby.Server.Implementations requiresRestart = true; } - var currentCertPath = CertificateInfo?.Path; - var newCertPath = ServerConfigurationManager.Configuration.CertificatePath; - - if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase)) + if (ValidateSslCertificate(networkConfiguration)) { requiresRestart = true; } @@ -952,6 +951,35 @@ namespace Emby.Server.Implementations } } + /// <summary> + /// Validates the SSL certificate. + /// </summary> + /// <param name="networkConfig">The new configuration.</param> + /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception> + private bool ValidateSslCertificate(NetworkConfiguration networkConfig) + { + var newPath = networkConfig.CertificatePath; + + if (!string.IsNullOrWhiteSpace(newPath) + && !string.Equals(CertificateInfo?.Path, newPath, StringComparison.Ordinal)) + { + if (File.Exists(newPath)) + { + return true; + } + else + { + throw new FileNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + "Certificate file '{0}' does not exist.", + newPath)); + } + } + + return false; + } + /// <summary> /// Notifies that the kernel that a change has been made that requires a restart. /// </summary> diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index f05a30a897..7a8ed8c29f 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -88,38 +88,12 @@ namespace Emby.Server.Implementations.Configuration var newConfig = (ServerConfiguration)newConfiguration; ValidateMetadataPath(newConfig); - ValidateSslCertificate(newConfig); ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration>(newConfig)); base.ReplaceConfiguration(newConfiguration); } - /// <summary> - /// Validates the SSL certificate. - /// </summary> - /// <param name="newConfig">The new configuration.</param> - /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception> - private void ValidateSslCertificate(BaseApplicationConfiguration newConfig) - { - var serverConfig = (ServerConfiguration)newConfig; - - var newPath = serverConfig.CertificatePath; - - if (!string.IsNullOrWhiteSpace(newPath) - && !string.Equals(Configuration.CertificatePath, newPath, StringComparison.Ordinal)) - { - if (!File.Exists(newPath)) - { - throw new FileNotFoundException( - string.Format( - CultureInfo.InvariantCulture, - "Certificate file '{0}' does not exist.", - newPath)); - } - } - } - /// <summary> /// Validates the metadata path. /// </summary> diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index df420f48a2..792e57f6ab 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -27,6 +27,16 @@ namespace Jellyfin.Networking.Configuration /// </summary> public bool RequireHttps { get; set; } + /// <summary> + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// </summary> + public string CertificatePath { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. + /// </summary> + public string CertificatePassword { get; set; } = string.Empty; + /// <summary> /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. /// </summary> @@ -83,7 +93,7 @@ namespace Jellyfin.Networking.Configuration /// </summary> /// <remarks> /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be - /// provided for <see cref="ServerConfiguration.CertificatePath"/> and <see cref="ServerConfiguration.CertificatePassword"/>. + /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>. /// </remarks> public bool EnableHttps { get; set; } From d701b67de11f8bfcadddcb4b02e9cd28d113f5d6 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 12 Dec 2020 02:36:31 +0800 Subject: [PATCH 0712/1930] Apply suggestions from code review Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/ApplicationHost.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d2f340cd3f..1a47335ad7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -967,14 +967,12 @@ namespace Emby.Server.Implementations { return true; } - else - { - throw new FileNotFoundException( - string.Format( - CultureInfo.InvariantCulture, - "Certificate file '{0}' does not exist.", - newPath)); - } + + throw new FileNotFoundException( + string.Format( + CultureInfo.InvariantCulture, + "Certificate file '{0}' does not exist.", + newPath)); } return false; From 7d24460faca89a171616f268a4e0bfbeb25f6b98 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 11 Dec 2020 13:57:03 -0700 Subject: [PATCH 0713/1930] Fix copy-paste error --- MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 299c555d0d..31dd954028 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -51,7 +51,7 @@ namespace MediaBrowser.Controller.BaseItemManager var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name); if (typeOptions != null) { - return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); } if (!libraryOptions.EnableInternetProviders) @@ -61,7 +61,7 @@ namespace MediaBrowser.Controller.BaseItemManager var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); - return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); } /// <inheritdoc /> From b670937c3d373173159a40f803e6e907ec0cd060 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 11 Dec 2020 15:00:43 -0700 Subject: [PATCH 0714/1930] Use typed UserManager GetPreference --- .../Library/UserViewManager.cs | 12 +++---- .../TV/TVSeriesManager.cs | 3 +- Jellyfin.Api/Controllers/ItemsController.cs | 16 ++++----- Jellyfin.Data/Entities/User.cs | 36 +++++++++++++++++-- .../Users/UserManager.cs | 18 +++++----- .../Migrations/Routines/MigrateUserDb.cs | 4 +-- MediaBrowser.Controller/Channels/Channel.cs | 8 ++--- .../Entities/Audio/MusicAlbum.cs | 2 +- .../Entities/Audio/MusicArtist.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 8 ++--- .../Entities/Movies/BoxSet.cs | 2 +- MediaBrowser.Controller/Entities/TV/Series.cs | 2 +- 12 files changed, 71 insertions(+), 42 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index e4221dd508..6c74e6bd48 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -129,23 +129,23 @@ namespace Emby.Server.Implementations.Library if (!query.IncludeHidden) { - list = list.Where(i => !user.GetPreference(PreferenceKind.MyMediaExcludes).Contains(i.Id.ToString("N", CultureInfo.InvariantCulture))).ToList(); + list = list.Where(i => !user.GetPreference<Guid>(PreferenceKind.MyMediaExcludes).Contains(i.Id)).ToList(); } var sorted = _libraryManager.Sort(list, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).ToList(); - var orders = user.GetPreference(PreferenceKind.OrderedViews).ToList(); + var orders = user.GetPreference<Guid>(PreferenceKind.OrderedViews); return list .OrderBy(i => { - var index = orders.IndexOf(i.Id.ToString("D", CultureInfo.InvariantCulture)); + var index = Array.IndexOf(orders, i.Id); if (index == -1 && i is UserView view && view.DisplayParentId != Guid.Empty) { - index = orders.IndexOf(view.DisplayParentId.ToString("D", CultureInfo.InvariantCulture)); + index = Array.IndexOf(orders, view.DisplayParentId); } return index == -1 ? int.MaxValue : index; @@ -280,8 +280,8 @@ namespace Emby.Server.Implementations.Library { parents = _libraryManager.GetUserRootFolder().GetChildren(user, true) .Where(i => i is Folder) - .Where(i => !user.GetPreference(PreferenceKind.LatestItemExcludes) - .Contains(i.Id.ToString("N", CultureInfo.InvariantCulture))) + .Where(i => !user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes) + .Contains(i.Id)) .ToList(); } diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 447c587f99..a2a9b37a75 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -75,8 +75,7 @@ namespace Emby.Server.Implementations.TV { parents = _libraryManager.GetUserRootFolder().GetChildren(user, true) .Where(i => i is Folder) - .Where(i => !user.GetPreference(PreferenceKind.LatestItemExcludes) - .Contains(i.Id.ToString("N", CultureInfo.InvariantCulture))) + .Where(i => !user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes).Contains(i.Id)) .ToArray(); } diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 7e9035f80f..0816efb38b 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -254,18 +254,18 @@ namespace Jellyfin.Api.Controllers includeItemTypes = new[] { "Playlist" }; } - bool isInEnabledFolder = user!.GetPreference(PreferenceKind.EnabledFolders).Any(i => new Guid(i) == item.Id) + var enabledChannels = user!.GetPreference<Guid>(PreferenceKind.EnabledChannels); + + bool isInEnabledFolder = Array.IndexOf(user.GetPreference<Guid>(PreferenceKind.EnabledFolders), item.Id) != -1 // Assume all folders inside an EnabledChannel are enabled - || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.Id) + || Array.IndexOf(enabledChannels, item.Id) != -1 // Assume all items inside an EnabledChannel are enabled - || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.ChannelId); + || Array.IndexOf(enabledChannels, item.ChannelId) != -1; var collectionFolders = _libraryManager.GetCollectionFolders(item); foreach (var collectionFolder in collectionFolders) { - if (user.GetPreference(PreferenceKind.EnabledFolders).Contains( - collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture), - StringComparer.OrdinalIgnoreCase)) + if (user.GetPreference<Guid>(PreferenceKind.EnabledFolders).Contains(collectionFolder.Id)) { isInEnabledFolder = true; } @@ -786,12 +786,12 @@ namespace Jellyfin.Api.Controllers var ancestorIds = Array.Empty<Guid>(); - var excludeFolderIds = user.GetPreference(PreferenceKind.LatestItemExcludes); + var excludeFolderIds = user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes); if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0) { ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true) .Where(i => i is Folder) - .Where(i => !excludeFolderIds.Contains(i.Id.ToString("N", CultureInfo.InvariantCulture))) + .Where(i => !excludeFolderIds.Contains(i.Id)) .Select(i => i.Id) .ToArray(); } diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 6d46819143..0733cc6705 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; @@ -413,6 +414,25 @@ namespace Jellyfin.Data.Entities return Equals(val, string.Empty) ? Array.Empty<string>() : val.Split(Delimiter); } + /// <summary> + /// Gets the user's preferences for the given preference kind. + /// </summary> + /// <param name="preference">The preference kind.</param> + /// <typeparam name="T">Type of preference.</typeparam> + /// <returns>A {T} array containing the user's preference.</returns> + public T[] GetPreference<T>(PreferenceKind preference) + { + var val = Preferences.First(p => p.Kind == preference).Value; + if (string.IsNullOrEmpty(val)) + { + return Array.Empty<T>(); + } + + var converter = TypeDescriptor.GetConverter(typeof(T)); + var stringValues = val.Split(Delimiter); + return Array.ConvertAll(stringValues, value => (T)converter.ConvertFromString(value)); + } + /// <summary> /// Sets the specified preference to the given value. /// </summary> @@ -421,7 +441,19 @@ namespace Jellyfin.Data.Entities public void SetPreference(PreferenceKind preference, string[] values) { Preferences.First(p => p.Kind == preference).Value - = string.Join(Delimiter.ToString(CultureInfo.InvariantCulture), values); + = string.Join(Delimiter, values); + } + + /// <summary> + /// Sets the specified preference to the given value. + /// </summary> + /// <param name="preference">The preference kind.</param> + /// <param name="values">The values.</param> + /// <typeparam name="T">The type of value.</typeparam> + public void SetPreference<T>(PreferenceKind preference, T[] values) + { + Preferences.First(p => p.Kind == preference).Value + = string.Join(Delimiter, values); } /// <summary> @@ -441,7 +473,7 @@ namespace Jellyfin.Data.Entities /// <returns><c>True</c> if the folder is in the user's grouped folders.</returns> public bool IsFolderGrouped(Guid id) { - return GetPreference(PreferenceKind.GroupedFolders).Any(i => new Guid(i) == id); + return Array.IndexOf(GetPreference<Guid>(PreferenceKind.GroupedFolders), id) != -1; } private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index e37fcc908b..f576e662aa 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -376,14 +376,14 @@ namespace Jellyfin.Server.Implementations.Users EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing), AccessSchedules = user.AccessSchedules.ToArray(), BlockedTags = user.GetPreference(PreferenceKind.BlockedTags), - EnabledChannels = user.GetPreference(PreferenceKind.EnabledChannels)?.Select(Guid.Parse).ToArray(), + EnabledChannels = user.GetPreference<Guid>(PreferenceKind.EnabledChannels), EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices), - EnabledFolders = user.GetPreference(PreferenceKind.EnabledFolders)?.Select(Guid.Parse).ToArray(), + EnabledFolders = user.GetPreference<Guid>(PreferenceKind.EnabledFolders), EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders), SyncPlayAccess = user.SyncPlayAccess, - BlockedChannels = user.GetPreference(PreferenceKind.BlockedChannels)?.Select(Guid.Parse).ToArray(), - BlockedMediaFolders = user.GetPreference(PreferenceKind.BlockedMediaFolders)?.Select(Guid.Parse).ToArray(), - BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems).Select(Enum.Parse<UnratedItem>).ToArray() + BlockedChannels = user.GetPreference<Guid>(PreferenceKind.BlockedChannels), + BlockedMediaFolders = user.GetPreference<Guid>(PreferenceKind.BlockedMediaFolders), + BlockUnratedItems = user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems) } }; } @@ -704,13 +704,11 @@ namespace Jellyfin.Server.Implementations.Users } // TODO: fix this at some point - user.SetPreference( - PreferenceKind.BlockUnratedItems, - policy.BlockUnratedItems?.Select(i => i.ToString()).ToArray() ?? Array.Empty<string>()); + user.SetPreference(PreferenceKind.BlockUnratedItems, policy.BlockUnratedItems ?? Array.Empty<UnratedItem>()); user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags); - user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray()); + user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels); user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices); - user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray()); + user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders); user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders); dbContext.Update(user); diff --git a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs index 74c5503314..33f039c394 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs @@ -168,9 +168,9 @@ namespace Jellyfin.Server.Migrations.Routines } user.SetPreference(PreferenceKind.BlockedTags, policy.BlockedTags); - user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray()); + user.SetPreference(PreferenceKind.EnabledChannels, policy.EnabledChannels); user.SetPreference(PreferenceKind.EnabledDevices, policy.EnabledDevices); - user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders?.Select(i => i.ToString("N", CultureInfo.InvariantCulture)).ToArray()); + user.SetPreference(PreferenceKind.EnabledFolders, policy.EnabledFolders); user.SetPreference(PreferenceKind.EnableContentDeletionFromFolders, policy.EnableContentDeletionFromFolders); user.SetPreference(PreferenceKind.OrderedViews, config.OrderedViews); user.SetPreference(PreferenceKind.GroupedFolders, config.GroupedFolders); diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs index 129cdb519f..c8a8db528e 100644 --- a/MediaBrowser.Controller/Channels/Channel.cs +++ b/MediaBrowser.Controller/Channels/Channel.cs @@ -17,9 +17,10 @@ namespace MediaBrowser.Controller.Channels { public override bool IsVisible(User user) { - if (user.GetPreference(PreferenceKind.BlockedChannels) != null) + var blockedChannelsPreference = user.GetPreference<Guid>(PreferenceKind.BlockedChannels); + if (blockedChannelsPreference.Length != 0) { - if (user.GetPreference(PreferenceKind.BlockedChannels).Contains(Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase)) + if (blockedChannelsPreference.Contains(Id)) { return false; } @@ -27,8 +28,7 @@ namespace MediaBrowser.Controller.Channels else { if (!user.HasPermission(PermissionKind.EnableAllChannels) - && !user.GetPreference(PreferenceKind.EnabledChannels) - .Contains(Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase)) + && !user.GetPreference<Guid>(PreferenceKind.EnabledChannels).Contains(Id)) { return false; } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index 48cd9371a0..260daa1c2e 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -120,7 +120,7 @@ namespace MediaBrowser.Controller.Entities.Audio protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music.ToString()); + return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); } public override UnratedItem GetBlockUnratedType() diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index c5e50cf45d..5d586bfb58 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -145,7 +145,7 @@ namespace MediaBrowser.Controller.Entities.Audio protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music.ToString()); + return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); } public override UnratedItem GetBlockUnratedType() diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 1b25fbdbb7..3aa93565bd 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -480,11 +480,11 @@ namespace MediaBrowser.Controller.Entities return true; } - var allowed = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders); + var allowed = user.GetPreference<Guid>(PreferenceKind.EnableContentDeletionFromFolders); if (SourceType == SourceType.Channel) { - return allowed.Contains(ChannelId.ToString(""), StringComparer.OrdinalIgnoreCase); + return allowed.Contains(ChannelId); } else { @@ -492,7 +492,7 @@ namespace MediaBrowser.Controller.Entities foreach (var folder in collectionFolders) { - if (allowed.Contains(folder.Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase)) + if (allowed.Contains(folder.Id)) { return true; } @@ -1909,7 +1909,7 @@ namespace MediaBrowser.Controller.Entities return false; } - return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType().ToString()); + return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType()); } /// <summary> diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 8de88cc1b1..343da38256 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -49,7 +49,7 @@ namespace MediaBrowser.Controller.Entities.Movies protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Movie.ToString()); + return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Movie); } public override double GetDefaultPrimaryImageAspectRatio() diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index e8afa9a490..aaed879c3a 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -452,7 +452,7 @@ namespace MediaBrowser.Controller.Entities.TV protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series.ToString()); + return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series); } public override UnratedItem GetBlockUnratedType() From f5cce9e630135eec076a6cb9e7ea08d81bcd45c5 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 11 Dec 2020 15:04:14 -0700 Subject: [PATCH 0715/1930] Use typed UserManager GetPreference --- MediaBrowser.Controller/Entities/Folder.cs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 57d04ddfac..0f936538b3 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -186,13 +186,10 @@ namespace MediaBrowser.Controller.Entities { if (this is ICollectionFolder && !(this is BasePluginFolder)) { - var blockedMediaFolders = user.GetPreference(PreferenceKind.BlockedMediaFolders); + var blockedMediaFolders = user.GetPreference<Guid>(PreferenceKind.BlockedMediaFolders); if (blockedMediaFolders.Length > 0) { - if (blockedMediaFolders.Contains(Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase) || - - // Backwards compatibility - blockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase)) + if (blockedMediaFolders.Contains(Id)) { return false; } @@ -200,8 +197,7 @@ namespace MediaBrowser.Controller.Entities else { if (!user.HasPermission(PermissionKind.EnableAllFolders) - && !user.GetPreference(PreferenceKind.EnabledFolders) - .Contains(Id.ToString("N", CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase)) + && !user.GetPreference<Guid>(PreferenceKind.EnabledFolders).Contains(Id)) { return false; } From 297cb27ab6d725e7bd9dee74d956dcb8a0dc6354 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Fri, 11 Dec 2020 21:13:28 -0500 Subject: [PATCH 0716/1930] remove opf extension for book types --- .../Library/Resolvers/Books/BookResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs index 59af7ce8ac..86242d1379 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs @@ -11,7 +11,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books { public class BookResolver : MediaBrowser.Controller.Resolvers.ItemResolver<Book> { - private readonly string[] _validExtensions = { ".azw", ".azw3", ".cb7", ".cbr", ".cbt", ".cbz", ".epub", ".mobi", ".opf", ".pdf" }; + private readonly string[] _validExtensions = { ".azw", ".azw3", ".cb7", ".cbr", ".cbt", ".cbz", ".epub", ".mobi", ".pdf" }; protected override Book Resolve(ItemResolveArgs args) { From 7be3276dff834d1a3aa4199815f7e14864b06b5b Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 12 Dec 2020 18:24:25 +0800 Subject: [PATCH 0717/1930] Fine tune some tone mapping params *Set recommand algorithm to Hable *Set recommand tone mapping peak to 100 --- MediaBrowser.Model/Configuration/EncodingOptions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index 100756c24f..38b3335107 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -88,11 +88,11 @@ namespace MediaBrowser.Model.Configuration // The left side of the dot is the platform number, and the right side is the device number on the platform. OpenclDevice = "0.0"; EnableTonemapping = false; - TonemappingAlgorithm = "reinhard"; + TonemappingAlgorithm = "hable"; TonemappingRange = "auto"; TonemappingDesat = 0; TonemappingThreshold = 0.8; - TonemappingPeak = 0; + TonemappingPeak = 100; TonemappingParam = 0; H264Crf = 23; H265Crf = 28; From d9263dacd5d2e3594e08a5c75bedb31cfc4c5c97 Mon Sep 17 00:00:00 2001 From: Patrick Barron <barronpm@gmail.com> Date: Sat, 12 Dec 2020 11:20:48 -0500 Subject: [PATCH 0718/1930] Enable nullable for Jellyfin.Server.Implementations --- Jellyfin.Server.Implementations/Activity/ActivityManager.cs | 2 +- .../Events/Consumers/Session/PlaybackStartLogger.cs | 2 +- .../Events/Consumers/Session/PlaybackStopLogger.cs | 2 +- .../Jellyfin.Server.Implementations.csproj | 1 + Jellyfin.Server.Implementations/JellyfinDb.cs | 1 + .../Users/DefaultAuthenticationProvider.cs | 2 -- .../Users/DefaultPasswordResetProvider.cs | 2 -- .../Users/DeviceAccessEntryPoint.cs | 3 +-- Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs | 2 -- Jellyfin.Server.Implementations/Users/UserManager.cs | 3 +-- .../ValueConverters/DateTimeKindValueConverter.cs | 4 ++-- 11 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs index 7bde4f35be..27360afb0a 100644 --- a/Jellyfin.Server.Implementations/Activity/ActivityManager.cs +++ b/Jellyfin.Server.Implementations/Activity/ActivityManager.cs @@ -27,7 +27,7 @@ namespace Jellyfin.Server.Implementations.Activity } /// <inheritdoc/> - public event EventHandler<GenericEventArgs<ActivityLogEntry>> EntryCreated; + public event EventHandler<GenericEventArgs<ActivityLogEntry>>? EntryCreated; /// <inheritdoc/> public async Task CreateAsync(ActivityLog entry) diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs index ec4a76e7ff..0340248bbd 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs @@ -86,7 +86,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session return name; } - private static string GetPlaybackNotificationType(string mediaType) + private static string? GetPlaybackNotificationType(string mediaType) { if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)) { diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs index a0bad29e9b..1648b1b475 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStopLogger.cs @@ -94,7 +94,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session return name; } - private static string GetPlaybackStoppedNotificationType(string mediaType) + private static string? GetPlaybackStoppedNotificationType(string mediaType) { if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)) { diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 5f508ea0a5..9e4a2065fe 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -5,6 +5,7 @@ <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <Nullable>enable</Nullable> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 7f3f837494..39f842354f 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs index 662b4bf651..6a78e7ee6f 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultAuthenticationProvider.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Linq; using System.Text; diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index 334f27f859..9cc1c3e5e5 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; using System.IO; diff --git a/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs b/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs index 1fb89c4a63..dbba80c210 100644 --- a/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs +++ b/Jellyfin.Server.Implementations/Users/DeviceAccessEntryPoint.cs @@ -1,5 +1,4 @@ -#nullable enable -#pragma warning disable CS1591 +#pragma warning disable CS1591 using System.Threading.Tasks; using Jellyfin.Data.Entities; diff --git a/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs index 5f32479e1d..c4e4c460a6 100644 --- a/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs +++ b/Jellyfin.Server.Implementations/Users/InvalidAuthProvider.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Threading.Tasks; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Authentication; diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index e37fcc908b..b76b272cfc 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -1,5 +1,4 @@ -#nullable enable -#pragma warning disable CA1307 +#pragma warning disable CA1307 using System; using System.Collections.Concurrent; diff --git a/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs index 8a510898bf..a9a18c823a 100644 --- a/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs +++ b/Jellyfin.Server.Implementations/ValueConverters/DateTimeKindValueConverter.cs @@ -13,9 +13,9 @@ namespace Jellyfin.Server.Implementations.ValueConverters /// </summary> /// <param name="kind">The kind to specify.</param> /// <param name="mappingHints">The mapping hints.</param> - public DateTimeKindValueConverter(DateTimeKind kind, ConverterMappingHints mappingHints = null) + public DateTimeKindValueConverter(DateTimeKind kind, ConverterMappingHints? mappingHints = null) : base(v => v.ToUniversalTime(), v => DateTime.SpecifyKind(v, kind), mappingHints) { } } -} \ No newline at end of file +} From 8f4a4a3cc56e9a5c0582c2bda3c0608daa781f64 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 12 Dec 2020 10:36:17 -0700 Subject: [PATCH 0719/1930] Convert values without throwing exception --- Jellyfin.Data/Entities/User.cs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 0733cc6705..d19cbac7fb 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using System.Globalization; using System.Linq; using System.Text.Json.Serialization; using Jellyfin.Data.Enums; @@ -428,9 +427,36 @@ namespace Jellyfin.Data.Entities return Array.Empty<T>(); } + // Convert array of {string} to array of {T} var converter = TypeDescriptor.GetConverter(typeof(T)); var stringValues = val.Split(Delimiter); - return Array.ConvertAll(stringValues, value => (T)converter.ConvertFromString(value)); + var parsedValues = new object[stringValues.Length]; + var convertedCount = 0; + for (var i = 0; i < stringValues.Length; i++) + { + try + { + parsedValues[i] = converter.ConvertFromString(stringValues[i].Trim()); + convertedCount++; + } + catch (FormatException) + { + // Unable to convert value + } + } + + var typedValues = new T[convertedCount]; + var typedValueIndex = 0; + for (var i = 0; i < parsedValues.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; } /// <summary> From ee23d06154133ffc506dda3a8ef0e09d20c03c6c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 13 Dec 2020 08:15:26 -0700 Subject: [PATCH 0720/1930] Use a more descriptive function name --- Emby.Server.Implementations/Library/UserViewManager.cs | 6 +++--- Emby.Server.Implementations/TV/TVSeriesManager.cs | 2 +- Jellyfin.Api/Controllers/ItemsController.cs | 8 ++++---- Jellyfin.Data/Entities/User.cs | 4 ++-- Jellyfin.Server.Implementations/Users/UserManager.cs | 10 +++++----- MediaBrowser.Controller/Channels/Channel.cs | 4 ++-- MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs | 2 +- MediaBrowser.Controller/Entities/Audio/MusicArtist.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 4 ++-- MediaBrowser.Controller/Entities/Folder.cs | 4 ++-- MediaBrowser.Controller/Entities/Movies/BoxSet.cs | 2 +- MediaBrowser.Controller/Entities/TV/Series.cs | 2 +- 12 files changed, 25 insertions(+), 25 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index 6c74e6bd48..b6b7ea9495 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -129,12 +129,12 @@ namespace Emby.Server.Implementations.Library if (!query.IncludeHidden) { - list = list.Where(i => !user.GetPreference<Guid>(PreferenceKind.MyMediaExcludes).Contains(i.Id)).ToList(); + list = list.Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.MyMediaExcludes).Contains(i.Id)).ToList(); } var sorted = _libraryManager.Sort(list, user, new[] { ItemSortBy.SortName }, SortOrder.Ascending).ToList(); - var orders = user.GetPreference<Guid>(PreferenceKind.OrderedViews); + var orders = user.GetPreferenceValues<Guid>(PreferenceKind.OrderedViews); return list .OrderBy(i => @@ -280,7 +280,7 @@ namespace Emby.Server.Implementations.Library { parents = _libraryManager.GetUserRootFolder().GetChildren(user, true) .Where(i => i is Folder) - .Where(i => !user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes) + .Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes) .Contains(i.Id)) .ToList(); } diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a2a9b37a75..f0734340be 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.TV { parents = _libraryManager.GetUserRootFolder().GetChildren(user, true) .Where(i => i is Folder) - .Where(i => !user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes).Contains(i.Id)) + .Where(i => !user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes).Contains(i.Id)) .ToArray(); } diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 0816efb38b..b84136ac6f 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -254,9 +254,9 @@ namespace Jellyfin.Api.Controllers includeItemTypes = new[] { "Playlist" }; } - var enabledChannels = user!.GetPreference<Guid>(PreferenceKind.EnabledChannels); + var enabledChannels = user!.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels); - bool isInEnabledFolder = Array.IndexOf(user.GetPreference<Guid>(PreferenceKind.EnabledFolders), item.Id) != -1 + bool isInEnabledFolder = Array.IndexOf(user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders), item.Id) != -1 // Assume all folders inside an EnabledChannel are enabled || Array.IndexOf(enabledChannels, item.Id) != -1 // Assume all items inside an EnabledChannel are enabled @@ -265,7 +265,7 @@ namespace Jellyfin.Api.Controllers var collectionFolders = _libraryManager.GetCollectionFolders(item); foreach (var collectionFolder in collectionFolders) { - if (user.GetPreference<Guid>(PreferenceKind.EnabledFolders).Contains(collectionFolder.Id)) + if (user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(collectionFolder.Id)) { isInEnabledFolder = true; } @@ -786,7 +786,7 @@ namespace Jellyfin.Api.Controllers var ancestorIds = Array.Empty<Guid>(); - var excludeFolderIds = user.GetPreference<Guid>(PreferenceKind.LatestItemExcludes); + var excludeFolderIds = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes); if (parentIdGuid.Equals(Guid.Empty) && excludeFolderIds.Length > 0) { ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true) diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index d19cbac7fb..cc85a0b85d 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -419,7 +419,7 @@ namespace Jellyfin.Data.Entities /// <param name="preference">The preference kind.</param> /// <typeparam name="T">Type of preference.</typeparam> /// <returns>A {T} array containing the user's preference.</returns> - public T[] GetPreference<T>(PreferenceKind preference) + public T[] GetPreferenceValues<T>(PreferenceKind preference) { var val = Preferences.First(p => p.Kind == preference).Value; if (string.IsNullOrEmpty(val)) @@ -499,7 +499,7 @@ namespace Jellyfin.Data.Entities /// <returns><c>True</c> if the folder is in the user's grouped folders.</returns> public bool IsFolderGrouped(Guid id) { - return Array.IndexOf(GetPreference<Guid>(PreferenceKind.GroupedFolders), id) != -1; + return Array.IndexOf(GetPreferenceValues<Guid>(PreferenceKind.GroupedFolders), id) != -1; } private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index f576e662aa..400f02ef21 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -376,14 +376,14 @@ namespace Jellyfin.Server.Implementations.Users EnablePublicSharing = user.HasPermission(PermissionKind.EnablePublicSharing), AccessSchedules = user.AccessSchedules.ToArray(), BlockedTags = user.GetPreference(PreferenceKind.BlockedTags), - EnabledChannels = user.GetPreference<Guid>(PreferenceKind.EnabledChannels), + EnabledChannels = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels), EnabledDevices = user.GetPreference(PreferenceKind.EnabledDevices), - EnabledFolders = user.GetPreference<Guid>(PreferenceKind.EnabledFolders), + EnabledFolders = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders), EnableContentDeletionFromFolders = user.GetPreference(PreferenceKind.EnableContentDeletionFromFolders), SyncPlayAccess = user.SyncPlayAccess, - BlockedChannels = user.GetPreference<Guid>(PreferenceKind.BlockedChannels), - BlockedMediaFolders = user.GetPreference<Guid>(PreferenceKind.BlockedMediaFolders), - BlockUnratedItems = user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems) + BlockedChannels = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels), + BlockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders), + BlockUnratedItems = user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems) } }; } diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs index c8a8db528e..b2315bda47 100644 --- a/MediaBrowser.Controller/Channels/Channel.cs +++ b/MediaBrowser.Controller/Channels/Channel.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Controller.Channels { public override bool IsVisible(User user) { - var blockedChannelsPreference = user.GetPreference<Guid>(PreferenceKind.BlockedChannels); + var blockedChannelsPreference = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedChannels); if (blockedChannelsPreference.Length != 0) { if (blockedChannelsPreference.Contains(Id)) @@ -28,7 +28,7 @@ namespace MediaBrowser.Controller.Channels else { if (!user.HasPermission(PermissionKind.EnableAllChannels) - && !user.GetPreference<Guid>(PreferenceKind.EnabledChannels).Contains(Id)) + && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels).Contains(Id)) { return false; } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index 260daa1c2e..9a33ad9d74 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -120,7 +120,7 @@ namespace MediaBrowser.Controller.Entities.Audio protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); + return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); } public override UnratedItem GetBlockUnratedType() diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 5d586bfb58..8a9bb12c7b 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -145,7 +145,7 @@ namespace MediaBrowser.Controller.Entities.Audio protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); + return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Music); } public override UnratedItem GetBlockUnratedType() diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 3aa93565bd..cbb02aabd7 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -480,7 +480,7 @@ namespace MediaBrowser.Controller.Entities return true; } - var allowed = user.GetPreference<Guid>(PreferenceKind.EnableContentDeletionFromFolders); + var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders); if (SourceType == SourceType.Channel) { @@ -1909,7 +1909,7 @@ namespace MediaBrowser.Controller.Entities return false; } - return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType()); + return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType()); } /// <summary> diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 0f936538b3..cac5026f70 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -186,7 +186,7 @@ namespace MediaBrowser.Controller.Entities { if (this is ICollectionFolder && !(this is BasePluginFolder)) { - var blockedMediaFolders = user.GetPreference<Guid>(PreferenceKind.BlockedMediaFolders); + var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders); if (blockedMediaFolders.Length > 0) { if (blockedMediaFolders.Contains(Id)) @@ -197,7 +197,7 @@ namespace MediaBrowser.Controller.Entities else { if (!user.HasPermission(PermissionKind.EnableAllFolders) - && !user.GetPreference<Guid>(PreferenceKind.EnabledFolders).Contains(Id)) + && !user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(Id)) { return false; } diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 343da38256..05e4229cad 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -49,7 +49,7 @@ namespace MediaBrowser.Controller.Entities.Movies protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Movie); + return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Movie); } public override double GetDefaultPrimaryImageAspectRatio() diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index aaed879c3a..1a379074dc 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -452,7 +452,7 @@ namespace MediaBrowser.Controller.Entities.TV protected override bool GetBlockUnratedValue(User user) { - return user.GetPreference<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series); + return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(UnratedItem.Series); } public override UnratedItem GetBlockUnratedType() From c6b381db1098041fe975f9830728bf1f000ce71f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 13 Dec 2020 08:32:33 -0700 Subject: [PATCH 0721/1930] Use request body for mapping xml channels --- Jellyfin.Api/Controllers/LiveTvController.cs | 11 ++------ .../Models/LiveTvDtos/SetChannelMappingDto.cs | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) create mode 100644 Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 56d4b3933e..6f2d432277 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -1119,20 +1119,15 @@ namespace Jellyfin.Api.Controllers /// <summary> /// Set channel mappings. /// </summary> - /// <param name="providerId">Provider id.</param> - /// <param name="tunerChannelId">Tuner channel id.</param> - /// <param name="providerChannelId">Provider channel id.</param> + /// <param name="setChannelMappingDto">The set channel mapping dto.</param> /// <response code="200">Created channel mapping returned.</response> /// <returns>An <see cref="OkResult"/> containing the created channel mapping.</returns> [HttpPost("ChannelMappings")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task<ActionResult<TunerChannelMapping>> SetChannelMapping( - [FromQuery] string? providerId, - [FromQuery] string? tunerChannelId, - [FromQuery] string? providerChannelId) + public async Task<ActionResult<TunerChannelMapping>> SetChannelMapping([FromBody, Required] SetChannelMappingDto setChannelMappingDto) { - return await _liveTvManager.SetChannelMapping(providerId, tunerChannelId, providerChannelId).ConfigureAwait(false); + return await _liveTvManager.SetChannelMapping(setChannelMappingDto.ProviderId, setChannelMappingDto.TunerChannelId, setChannelMappingDto.ProviderChannelId).ConfigureAwait(false); } /// <summary> diff --git a/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs b/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs new file mode 100644 index 0000000000..2ddaa89e8b --- /dev/null +++ b/Jellyfin.Api/Models/LiveTvDtos/SetChannelMappingDto.cs @@ -0,0 +1,28 @@ +using System.ComponentModel.DataAnnotations; + +namespace Jellyfin.Api.Models.LiveTvDtos +{ + /// <summary> + /// Set channel mapping dto. + /// </summary> + public class SetChannelMappingDto + { + /// <summary> + /// Gets or sets the provider id. + /// </summary> + [Required] + public string ProviderId { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the tuner channel id. + /// </summary> + [Required] + public string TunerChannelId { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the provider channel id. + /// </summary> + [Required] + public string ProviderChannelId { get; set; } = string.Empty; + } +} \ No newline at end of file From a83a4f55d97485088e4e7d82318f17d2117f6934 Mon Sep 17 00:00:00 2001 From: A Foley <beartotem@live.com> Date: Sun, 13 Dec 2020 14:50:10 +0000 Subject: [PATCH 0722/1930] Translated using Weblate (French (Canada)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr_CA/ --- .../Localization/Core/fr-CA.json | 66 ++++++++++--------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr-CA.json b/Emby.Server.Implementations/Localization/Core/fr-CA.json index 0c19a01524..3c51d64e04 100644 --- a/Emby.Server.Implementations/Localization/Core/fr-CA.json +++ b/Emby.Server.Implementations/Localization/Core/fr-CA.json @@ -1,9 +1,9 @@ { "Albums": "Albums", - "AppDeviceValues": "Application : {0}, Appareil : {1}", + "AppDeviceValues": "App : {0}, Appareil : {1}", "Application": "Application", "Artists": "Artistes", - "AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès", + "AuthenticationSucceededWithUserName": "{0} authentifié avec succès", "Books": "Livres", "CameraImageUploadedFrom": "Une nouvelle image de caméra a été téléchargée depuis {0}", "Channels": "Chaînes", @@ -11,11 +11,11 @@ "Collections": "Collections", "DeviceOfflineWithName": "{0} s'est déconnecté", "DeviceOnlineWithName": "{0} est connecté", - "FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}", + "FailedLoginAttemptWithUserName": "Tentative de connexion échoué par {0}", "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes", + "HeaderAlbumArtists": "Artistes de l'album", "HeaderContinueWatching": "Reprendre le visionnement", "HeaderFavoriteAlbums": "Albums favoris", "HeaderFavoriteArtists": "Artistes favoris", @@ -26,12 +26,12 @@ "HeaderNextUp": "À Suivre", "HeaderRecordingGroups": "Groupes d'enregistrements", "HomeVideos": "Vidéos personnelles", - "Inherit": "Hériter", + "Inherit": "Hérite", "ItemAddedWithName": "{0} a été ajouté à la médiathèque", "ItemRemovedWithName": "{0} a été supprimé de la médiathèque", "LabelIpAddressValue": "Adresse IP : {0}", "LabelRunningTimeValue": "Durée : {0}", - "Latest": "Derniers", + "Latest": "Plus récent", "MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour", "MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers la version {0}", "MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour", @@ -40,15 +40,15 @@ "Movies": "Films", "Music": "Musique", "MusicVideos": "Vidéos musicales", - "NameInstallFailed": "{0} échec d'installation", + "NameInstallFailed": "échec d'installation de {0}", "NameSeasonNumber": "Saison {0}", "NameSeasonUnknown": "Saison Inconnue", - "NewVersionIsAvailable": "Une nouvelle version du serveur Jellyfin est disponible au téléchargement.", + "NewVersionIsAvailable": "Une nouvelle version du serveur Jellyfin est disponible.", "NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible", "NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée", "NotificationOptionAudioPlayback": "Lecture audio démarrée", "NotificationOptionAudioPlaybackStopped": "Lecture audio arrêtée", - "NotificationOptionCameraImageUploaded": "L'image de l'appareil photo a été transférée", + "NotificationOptionCameraImageUploaded": "Image d'appareil photo transférée", "NotificationOptionInstallationFailed": "Échec d'installation", "NotificationOptionNewLibraryContent": "Nouveau contenu ajouté", "NotificationOptionPluginError": "Erreur d'extension", @@ -70,9 +70,9 @@ "ScheduledTaskFailedWithName": "{0} a échoué", "ScheduledTaskStartedWithName": "{0} a commencé", "ServerNameNeedsToBeRestarted": "{0} doit être redémarré", - "Shows": "Émissions", + "Shows": "Séries", "Songs": "Chansons", - "StartupEmbyServerIsLoading": "Le serveur Jellyfin est en cours de chargement. Veuillez réessayer dans quelques instants.", + "StartupEmbyServerIsLoading": "Serveur Jellyfin en cours de chargement. Réessayez dans quelques instants.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Échec du téléchargement des sous-titres depuis {0} pour {1}", "Sync": "Synchroniser", @@ -80,39 +80,43 @@ "TvShows": "Séries Télé", "User": "Utilisateur", "UserCreatedWithName": "L'utilisateur {0} a été créé", - "UserDeletedWithName": "L'utilisateur {0} a été supprimé", - "UserDownloadingItemWithValues": "{0} est en train de télécharger {1}", + "UserDeletedWithName": "L'utilisateur {0} supprimé", + "UserDownloadingItemWithValues": "{0} télécharge {1}", "UserLockedOutWithName": "L'utilisateur {0} a été verrouillé", - "UserOfflineFromDevice": "{0} s'est déconnecté depuis {1}", - "UserOnlineFromDevice": "{0} s'est connecté depuis {1}", - "UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié", + "UserOfflineFromDevice": "{0} s'est déconnecté de {1}", + "UserOnlineFromDevice": "{0} s'est connecté de {1}", + "UserPasswordChangedWithName": "Le mot de passe de utilisateur {0} a été modifié", "UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}", - "UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}", - "UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}", + "UserStartedPlayingItemWithValues": "{0} joue {1} sur {2}", + "UserStoppedPlayingItemWithValues": "{0} a terminé la lecture de {1} sur {2}", "ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque", "ValueSpecialEpisodeName": "Spécial - {0}", "VersionNumber": "Version {0}", - "TasksLibraryCategory": "Bibliothèque", + "TasksLibraryCategory": "Médiathèque", "TasksMaintenanceCategory": "Entretien", - "TaskDownloadMissingSubtitlesDescription": "Recherche l'internet pour des sous-titres manquants à base de métadonnées configurées.", + "TaskDownloadMissingSubtitlesDescription": "Recherche les sous-titres manquant sur l'internet selon la configuration des métadonnées.", "TaskDownloadMissingSubtitles": "Télécharger les sous-titres manquants", - "TaskRefreshChannelsDescription": "Rafraîchit des informations des chaines internet.", - "TaskRefreshChannels": "Rafraîchir des chaines", - "TaskCleanTranscodeDescription": "Supprime les fichiers de transcodage de plus d'un jour.", + "TaskRefreshChannelsDescription": "Rafraîchit les informations des chaines internet.", + "TaskRefreshChannels": "Rafraîchir les chaines", + "TaskCleanTranscodeDescription": "Supprime les fichiers de transcodage datant de plus d'un jour.", "TaskCleanTranscode": "Nettoyer le répertoire de transcodage", - "TaskUpdatePluginsDescription": "Télécharger et installer les mises à jours des extensions qui sont configurés pour les m.à.j. automisés.", + "TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurés pour les m.à.j. automatiques.", "TaskUpdatePlugins": "Mise à jour des extensions", - "TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre bibliothèque de médias.", - "TaskRefreshPeople": "Rafraîchir les acteurs", - "TaskCleanLogsDescription": "Supprime les journaux qui ont plus que {0} jours.", + "TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre médiathèque.", + "TaskRefreshPeople": "Rafraîchir les personnes", + "TaskCleanLogsDescription": "Supprime les journaux plus vieux que {0} jours.", "TaskCleanLogs": "Nettoyer le répertoire des journaux", - "TaskRefreshLibraryDescription": "Analyse votre bibliothèque média pour trouver de nouveaux fichiers et rafraîchit les métadonnées.", + "TaskRefreshLibraryDescription": "Analyse votre médiathèque pour trouver de nouveaux fichiers et rafraîchit les métadonnées.", "TaskRefreshChapterImages": "Extraire les images de chapitre", "TaskRefreshChapterImagesDescription": "Créer des vignettes pour les vidéos qui ont des chapitres.", - "TaskRefreshLibrary": "Analyser la bibliothèque de médias", + "TaskRefreshLibrary": "Analyser la médiathèque", "TaskCleanCache": "Nettoyer le répertoire des fichiers temporaires", "TasksApplicationCategory": "Application", "TaskCleanCacheDescription": "Supprime les fichiers temporaires qui ne sont plus nécessaire pour le système.", - "TasksChannelsCategory": "Canaux Internet", - "Default": "Par défaut" + "TasksChannelsCategory": "Chaines Internet", + "Default": "Par défaut", + "TaskCleanActivityLogDescription": "Éfface les entrées du journal plus anciennes que l'âge configuré.", + "TaskCleanActivityLog": "Nettoyer le journal d'activité", + "Undefined": "Indéfini", + "Forced": "Forcé" } From ca5f87c7ebd2a1dca0def67759b6cf991a0407bb Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 14 Dec 2020 07:20:16 -0700 Subject: [PATCH 0723/1930] Fix get provider id extension --- MediaBrowser.Model/Entities/ProviderIdsExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 1782b42e21..98097477c6 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -49,7 +49,7 @@ namespace MediaBrowser.Model.Entities } instance.ProviderIds.TryGetValue(name, out string? id); - return id; + return string.IsNullOrEmpty(id) ? null : id; } /// <summary> From a515ecbada489bb79e8bcce6fd1aabe6d81ce235 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 14 Dec 2020 07:53:56 -0700 Subject: [PATCH 0724/1930] Use range operator to get subarray --- Jellyfin.Data/Entities/User.cs | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index cc85a0b85d..725531a7d8 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -430,14 +430,17 @@ namespace Jellyfin.Data.Entities // Convert array of {string} to array of {T} var converter = TypeDescriptor.GetConverter(typeof(T)); var stringValues = val.Split(Delimiter); - var parsedValues = new object[stringValues.Length]; var convertedCount = 0; + var parsedValues = new T[stringValues.Length]; for (var i = 0; i < stringValues.Length; i++) { try { - parsedValues[i] = converter.ConvertFromString(stringValues[i].Trim()); - convertedCount++; + var parsedValue = converter.ConvertFromString(stringValues[i].Trim()); + if (parsedValue != null) + { + parsedValues.SetValue(parsedValue, convertedCount++); + } } catch (FormatException) { @@ -445,18 +448,7 @@ namespace Jellyfin.Data.Entities } } - var typedValues = new T[convertedCount]; - var typedValueIndex = 0; - for (var i = 0; i < parsedValues.Length; i++) - { - if (parsedValues[i] != null) - { - typedValues.SetValue(parsedValues[i], typedValueIndex); - typedValueIndex++; - } - } - - return typedValues; + return parsedValues[..convertedCount]; } /// <summary> From e0510909040a05d2b3170634ac2ef85a52ae184d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 14 Dec 2020 09:03:36 -0700 Subject: [PATCH 0725/1930] Use proper array setter --- Jellyfin.Data/Entities/User.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 725531a7d8..a0232e156d 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -439,7 +439,7 @@ namespace Jellyfin.Data.Entities var parsedValue = converter.ConvertFromString(stringValues[i].Trim()); if (parsedValue != null) { - parsedValues.SetValue(parsedValue, convertedCount++); + parsedValues[convertedCount++] = (T)parsedValue; } } catch (FormatException) From 7986465cf785ca385fd1765326887e550bced033 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Sun, 6 Dec 2020 23:48:54 +0000 Subject: [PATCH 0726/1930] Initial upload --- .../ApplicationHost.cs | 250 ++----- .../Emby.Server.Implementations.csproj | 8 +- .../Plugins/Active.png | Bin 0 -> 1422 bytes .../Plugins/Malfunction.png | Bin 0 -> 2091 bytes .../Plugins/NotSupported.png | Bin 0 -> 2046 bytes .../Plugins/PluginManager.cs | 674 ++++++++++++++++++ .../Plugins/PluginManifest.cs | 60 -- .../Plugins/RestartRequired.png | Bin 0 -> 1996 bytes .../Plugins/Superceded.png | Bin 0 -> 2136 bytes Emby.Server.Implementations/Plugins/blank.png | Bin 0 -> 120 bytes .../Plugins/disabled.png | Bin 0 -> 1790 bytes .../ScheduledTasks/Tasks/PluginUpdateTask.cs | 2 +- .../Updates/InstallationManager.cs | 456 ++++++------ .../Controllers/DashboardController.cs | 20 +- Jellyfin.Api/Controllers/PackageController.cs | 8 +- Jellyfin.Api/Controllers/PluginsController.cs | 384 +++++++--- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 8 +- MediaBrowser.Common/IApplicationHost.cs | 42 +- MediaBrowser.Common/Plugins/BasePlugin.cs | 15 +- .../Plugins/IHasPluginConfiguration.cs | 33 + MediaBrowser.Common/Plugins/IPlugin.cs | 40 +- MediaBrowser.Common/Plugins/IPluginManager.cs | 86 +++ MediaBrowser.Common/Plugins/LocalPlugin.cs | 94 ++- MediaBrowser.Common/Plugins/PluginManifest.cs | 85 +++ .../Updates/IInstallationManager.cs | 32 +- .../Updates/InstallationEventArgs.cs | 11 +- .../Updates/PluginUninstalledEventArgs.cs | 7 +- .../IServerApplicationHost.cs | 10 - .../Configuration/ServerConfiguration.cs | 10 + MediaBrowser.Model/Plugins/PluginInfo.cs | 39 +- MediaBrowser.Model/Plugins/PluginStatus.cs | 17 + MediaBrowser.Model/Updates/PackageInfo.cs | 43 +- MediaBrowser.Model/Updates/VersionInfo.cs | 42 +- MediaBrowser.sln | 5 +- 34 files changed, 1726 insertions(+), 755 deletions(-) create mode 100644 Emby.Server.Implementations/Plugins/Active.png create mode 100644 Emby.Server.Implementations/Plugins/Malfunction.png create mode 100644 Emby.Server.Implementations/Plugins/NotSupported.png create mode 100644 Emby.Server.Implementations/Plugins/PluginManager.cs delete mode 100644 Emby.Server.Implementations/Plugins/PluginManifest.cs create mode 100644 Emby.Server.Implementations/Plugins/RestartRequired.png create mode 100644 Emby.Server.Implementations/Plugins/Superceded.png create mode 100644 Emby.Server.Implementations/Plugins/blank.png create mode 100644 Emby.Server.Implementations/Plugins/disabled.png create mode 100644 MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs create mode 100644 MediaBrowser.Common/Plugins/IPluginManager.cs create mode 100644 MediaBrowser.Common/Plugins/PluginManifest.cs create mode 100644 MediaBrowser.Model/Plugins/PluginStatus.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d74ea03520..f88c6c6208 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -34,7 +34,6 @@ using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Playlists; -using Emby.Server.Implementations.Plugins; using Emby.Server.Implementations.QuickConnect; using Emby.Server.Implementations.ScheduledTasks; using Emby.Server.Implementations.Security; @@ -119,7 +118,9 @@ namespace Emby.Server.Implementations private readonly IXmlSerializer _xmlSerializer; private readonly IJsonSerializer _jsonSerializer; private readonly IStartupOptions _startupOptions; + private readonly IPluginManager _pluginManager; + private List<Type> _creatingInstances; private IMediaEncoder _mediaEncoder; private ISessionManager _sessionManager; private string[] _urlPrefixes; @@ -181,16 +182,6 @@ namespace Emby.Server.Implementations protected IServiceCollection ServiceCollection { get; } - private IPlugin[] _plugins; - - private IReadOnlyList<LocalPlugin> _pluginsManifests; - - /// <summary> - /// Gets the plugins. - /// </summary> - /// <value>The plugins.</value> - public IReadOnlyList<IPlugin> Plugins => _plugins; - /// <summary> /// Gets the logger factory. /// </summary> @@ -294,6 +285,14 @@ namespace Emby.Server.Implementations ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; ApplicationVersionString = ApplicationVersion.ToString(3); ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; + + _pluginManager = new PluginManager( + LoggerFactory, + this, + ServerConfigurationManager.Configuration, + ApplicationPaths.PluginsPath, + ApplicationPaths.CachePath, + ApplicationVersion); } /// <summary> @@ -393,8 +392,26 @@ namespace Emby.Server.Implementations /// <returns>System.Object.</returns> protected object CreateInstanceSafe(Type type) { + if (_creatingInstances == null) + { + _creatingInstances = new List<Type>(); + } + + if (_creatingInstances.IndexOf(type) != -1) + { + Logger.LogError("DI Loop detected."); + Logger.LogError("Attempted creation of {Type}", type.FullName); + foreach (var entry in _creatingInstances) + { + Logger.LogError("Called from: {stack}", entry.FullName); + } + + throw new ExternalException("DI Loop detected."); + } + try { + _creatingInstances.Add(type); Logger.LogDebug("Creating instance of {Type}", type); return ActivatorUtilities.CreateInstance(ServiceProvider, type); } @@ -403,6 +420,10 @@ namespace Emby.Server.Implementations Logger.LogError(ex, "Error creating {Type}", type); return null; } + finally + { + _creatingInstances.Remove(type); + } } /// <summary> @@ -412,11 +433,7 @@ namespace Emby.Server.Implementations /// <returns>``0.</returns> public T Resolve<T>() => ServiceProvider.GetService<T>(); - /// <summary> - /// Gets the export types. - /// </summary> - /// <typeparam name="T">The type.</typeparam> - /// <returns>IEnumerable{Type}.</returns> + /// <inheritdoc/> public IEnumerable<Type> GetExportTypes<T>() { var currentType = typeof(T); @@ -445,6 +462,27 @@ namespace Emby.Server.Implementations return parts; } + /// <inheritdoc /> + public IReadOnlyCollection<T> GetExports<T>(CreationDelegate defaultFunc, bool manageLifetime = true) + { + // Convert to list so this isn't executed for each iteration + var parts = GetExportTypes<T>() + .Select(i => defaultFunc(i)) + .Where(i => i != null) + .Cast<T>() + .ToList(); + + if (manageLifetime) + { + lock (_disposableParts) + { + _disposableParts.AddRange(parts.OfType<IDisposable>()); + } + } + + return parts; + } + /// <summary> /// Runs the startup tasks. /// </summary> @@ -509,7 +547,7 @@ namespace Emby.Server.Implementations RegisterServices(); - RegisterPluginServices(); + _pluginManager.RegisterServices(ServiceCollection); } /// <summary> @@ -523,7 +561,7 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(ConfigurationManager); ServiceCollection.AddSingleton<IApplicationHost>(this); - + ServiceCollection.AddSingleton<IPluginManager>(_pluginManager); ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths); ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>(); @@ -768,34 +806,7 @@ namespace Emby.Server.Implementations } ConfigurationManager.AddParts(GetExports<IConfigurationFactory>()); - _plugins = GetExports<IPlugin>() - .Where(i => i != null) - .ToArray(); - - if (Plugins != null) - { - foreach (var plugin in Plugins) - { - if (_pluginsManifests != null && plugin is IPluginAssembly assemblyPlugin) - { - // Ensure the version number matches the Plugin Manifest information. - foreach (var item in _pluginsManifests) - { - if (Path.GetDirectoryName(plugin.AssemblyFilePath).Equals(item.Path, StringComparison.OrdinalIgnoreCase)) - { - // Update version number to that of the manifest. - assemblyPlugin.SetAttributes( - plugin.AssemblyFilePath, - Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(plugin.AssemblyFilePath)), - item.Version); - break; - } - } - } - - Logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version); - } - } + _pluginManager.CreatePlugins(); _urlPrefixes = GetUrlPrefixes().ToArray(); @@ -834,22 +845,6 @@ namespace Emby.Server.Implementations _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray(); } - private void RegisterPluginServices() - { - foreach (var pluginServiceRegistrator in GetExportTypes<IPluginServiceRegistrator>()) - { - try - { - var instance = (IPluginServiceRegistrator)Activator.CreateInstance(pluginServiceRegistrator); - instance.RegisterServices(ServiceCollection); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly); - } - } - } - private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies) { foreach (var ass in assemblies) @@ -862,11 +857,13 @@ namespace Emby.Server.Implementations catch (FileNotFoundException ex) { Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName); + _pluginManager.FailPlugin(ass); continue; } catch (TypeLoadException ex) { Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName); + _pluginManager.FailPlugin(ass); continue; } @@ -1005,129 +1002,15 @@ namespace Emby.Server.Implementations protected abstract void RestartInternal(); - /// <inheritdoc/> - public IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true) - { - var minimumVersion = new Version(0, 0, 0, 1); - var versions = new List<LocalPlugin>(); - if (!Directory.Exists(path)) - { - // Plugin path doesn't exist, don't try to enumerate subfolders. - return Enumerable.Empty<LocalPlugin>(); - } - - var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); - - foreach (var dir in directories) - { - try - { - var metafile = Path.Combine(dir, "meta.json"); - if (File.Exists(metafile)) - { - var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile); - - if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) - { - targetAbi = minimumVersion; - } - - if (!Version.TryParse(manifest.Version, out var version)) - { - version = minimumVersion; - } - - if (ApplicationVersion >= targetAbi) - { - // Only load Plugins if the plugin is built for this version or below. - versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir)); - } - } - else - { - // No metafile, so lets see if the folder is versioned. - metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; - - int versionIndex = dir.LastIndexOf('_'); - if (versionIndex != -1 && Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version parsedVersion)) - { - // Versioned folder. - versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir)); - } - else - { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. - versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir)); - } - } - } - catch - { - continue; - } - } - - string lastName = string.Empty; - versions.Sort(LocalPlugin.Compare); - // Traverse backwards through the list. - // The first item will be the latest version. - for (int x = versions.Count - 1; x >= 0; x--) - { - if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase)) - { - versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories)); - lastName = versions[x].Name; - continue; - } - - if (!string.IsNullOrEmpty(lastName) && cleanup) - { - // Attempt a cleanup of old folders. - try - { - Logger.LogDebug("Deleting {Path}", versions[x].Path); - Directory.Delete(versions[x].Path, true); - } - catch (Exception e) - { - Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path); - } - - versions.RemoveAt(x); - } - } - - return versions; - } - /// <summary> /// Gets the composable part assemblies. /// </summary> /// <returns>IEnumerable{Assembly}.</returns> protected IEnumerable<Assembly> GetComposablePartAssemblies() { - if (Directory.Exists(ApplicationPaths.PluginsPath)) + foreach (var p in _pluginManager.LoadAssemblies()) { - _pluginsManifests = GetLocalPlugins(ApplicationPaths.PluginsPath).ToList(); - foreach (var plugin in _pluginsManifests) - { - foreach (var file in plugin.DllFiles) - { - Assembly plugAss; - try - { - plugAss = Assembly.LoadFrom(file); - } - catch (FileLoadException ex) - { - Logger.LogError(ex, "Failed to load assembly {Path}", file); - continue; - } - - Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file); - yield return plugAss; - } - } + yield return p; } // Include composable parts in the Model assembly @@ -1369,17 +1252,6 @@ namespace Emby.Server.Implementations } } - /// <summary> - /// Removes the plugin. - /// </summary> - /// <param name="plugin">The plugin.</param> - public void RemovePlugin(IPlugin plugin) - { - var list = _plugins.ToList(); - list.Remove(plugin); - _plugins = list.ToArray(); - } - public IEnumerable<Assembly> GetApiPluginAssemblies() { var assemblies = _allConcreteTypes diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 91c4648c62..dd60229825 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -73,6 +73,12 @@ <EmbeddedResource Include="Localization\countries.json" /> <EmbeddedResource Include="Localization\Core\*.json" /> <EmbeddedResource Include="Localization\Ratings\*.csv" /> + <EmbeddedResource Include="Plugins\blank.png" /> + <EmbeddedResource Include="Plugins\Superceded.png" /> + <EmbeddedResource Include="Plugins\Disabled.png" /> + <EmbeddedResource Include="Plugins\NotSupported.png" /> + <EmbeddedResource Include="Plugins\Malfunction.png" /> + <EmbeddedResource Include="Plugins\RestartRequired.png" /> + <EmbeddedResource Include="Plugins\Active.png" /> </ItemGroup> - </Project> diff --git a/Emby.Server.Implementations/Plugins/Active.png b/Emby.Server.Implementations/Plugins/Active.png new file mode 100644 index 0000000000000000000000000000000000000000..3722ee5200f60eb51419a182b8e094c42c6291ec GIT binary patch literal 1422 zcmV;91#$X`P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D1tUpBK~z{ry_bD# z6jczwXWrYr-Mzc^+Hy3sRX(I7El3YRB@F=!NDwJSK?5z3hy<eujR_=11^KANs0kk$ z{}iMcJ{r@Kq6Q=(A`*}iLm^oFph)GTE#)XJy}RD-zUSM!J)rao{es_Ra+lfJH}hs^ z=ItRoLef{{LslMnPW(*coS!mGR{O{Tcy`YWDJ@xBo2<(3|J~S1C_~^Be|;nYjM+0i zC3AqgR3>ERUk$Awn+W1lWvaa3p$FjG^TLRcsR?^q0{Y0h8v#%l0Yb<xLCR*IDcs-u z&;ls<x&RuIjETZ|d7VGt^#{UY=L9Ih!vUG)SHHUdmSsmG*8NP@_AF=}$mjV6c@ETG zYxA~*3{ZiBgOU@vgBQe{Tl9Mda(7R~WKY7f$35D{n)+5rHyIF)Ksnav63aU__s2%t zG(x{-Aa7e93>uKMX0XS(<y=Fn#DRk-Ja7QH%2k+oY)(h#7X6liX?qJuibwfOwAl)) z(qo_jZCt_0hh|k)*{TloO9p1_n@v-b)y*lwd2Q1zkO)RZ^g5#|S#<rMi*cP>^f?3h z`>dU7o81n&{NL+swibZtVsQySzLIfab@fx#wze~U%0PZ)J`7BDe(F)B<(F;*#jZ(2 z&?-6!e?Zw>cR%MAkqnGGISzDLhts~(5oLFnb?`;>Iuk!iQlzyP{Q(g57J-Rx)8w_1 zg5xWmFK>!!yM|0SHvvYskC;2UIjf}b&?}0qzb`qZIgsk~EcI%RHJ6)1(PvJh!Wa)} z8ePyG=N2UU#^CvBZe=GjzDkV9gA0$&d(6HTm-O}N@bnWS=cKwEo37jpVzl6*sW(gx zno3u>Cnp}a%^!%k4VGNJ8FCP-Y7r))2~~@Z&Yv>vz%<*WBh#l&dL}JV-Co}klEqlP zvvbZtlE{9dvrSuZt8M*Yh{5<9VxeoXT~Ne9gu{WM3EmHu94Vx>U4%D}6=tL-s1^RU zup9Bt&c!{V1hCPqNsD()FK4!Sw;-mo=Awvvu}smt-M=U@%V7hRv0~|oq5+oS(%*_y zuS+QlhK&qUR9ei|65Rxrph<84nfu?B$f`Xc(gpAQ@iM?I=jS4iD<j&wK|C*7s?aIX zg%ogEb1-aQh|+F|vPUds?d<ifQ+C_E(0y(XqT;Frig-yl44jX*Rd+yacgj=_gvEIp z>o<Ybav>cqIW_cc8TYN<R`-YwlW^s!g~PeYe-}OyZPk4d$>6GrFKrxKT4}3#OovJ6 z@(nvLOQcv-HIG$ySHd{~#X)xY2l{*M+@jN2u=><%$SK{$8J}mXI>E)LZ8u1hs<P1= zp8TfXR`-fdXF<uB9l}2@7fpUS)@Jt#V-#E}zSj~y-zVo5aSx+)+1sv()_hB}Cc8KF zqDeuP=+DUX?O%>PV&Bnw;s#(nm_%>zdlAHrdv^~YwYxP|ye_BIj2ici_yGuty*q_N zTp>$X9~(HpB+wN2s`;vU#y0CST?Sy$Iz0Wl=!%t*^o!k7BGo%2zW$R*+iZ)z(_z-% zO>S;3xKFxK)1<S`447ydj$w*}zkA^e<+#u1LtWRQp`pRH?mck>C@Cqy%*@PWm&-Mj zHM+*I7D-i7%q;(RDL<)-<`&4=+1cSyqeg|Rs=9pL>lSezK`<CZ@$Z!gk%VBVRz2&l zO!^Q^3|o3}5>oN*fFh7ibEKzqxj<1-5eykJ1WnUKkqI;m11O~s4u`oVb#-;TtgOto c?kxcS0~w3NKFYLwmjD0&07*qoM6N<$g7!P0tN;K2 literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/Malfunction.png b/Emby.Server.Implementations/Plugins/Malfunction.png new file mode 100644 index 0000000000000000000000000000000000000000..d4726150eb52857ff3ad25462517be0de9187b47 GIT binary patch literal 2091 zcmV+`2-Nq9P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D2f#^0K~z{rwO46u zRM!>$=FPmB@opS@yx|6?nP3~-;DUh~3sV%OB83v9CO_JwL83qCB30@FiNQ75N!q5$ zB9(+BRcX`~l|m4f6E(qLOaLb~v0~!}jPY(}jF+)J#<RbE=goMLV;E#9M>=}<oqOKB zXZg;#_ZbkKlv8`ZvpLCXIHIT))ntu>cWlT%=EV=c``q~|&WFNkUk@oCKDlOF(@PsQ z&*cv_ZS)ekh2syjrk6KrhkjO+Pn|n);+CXDp0^_NU9rl6yoYze;y(k_t=HLNyo%h7 zPr#mTeTO<~Sao3(&43sMn$40^0Cc`d?Kt`y3plD^j!#D@7)qgzHLSWYie>=4V}w07 zxlJ}-IW~|@3HpP{H&STQH5W+H3<wRl12xXZ6Tp(4fEEbz;>X}@sexlu^78e9Fd;ck zUHSQo8#K+`qiI#PFuS|8&nk;G&MzY~Ckv-&5twvM_;2_<6QRIpAJdRYk?iZ!CrP7Z zZ+JLEXZMvZiVUNYl#qJyg|Yzz{mG%wSEH#>7IRlNmOZ`)IR67m_(}0UaQWz481HX` zL7DA?7)Ru$*x(y?p{Tsh!q;hQ=OZy7`Qo!BBSpXa3lNY6WI+)}NJJXn+g<?%Yx%-) z!hOK<mpSC*ELB}uqZ5Q>>)RE0{djZkfsZ>oBa`!zd~R!adaZNiZ{A?+HdA6IPkA-9 zI^PXkRaj&?82ud2iI{AzF(ai_X#CSJu&T0Na^{p7eSRLAiJvTJWW<atYhw(V*fPe` zn?$|rV3K#4r-3HU>$0SIm~t)11$E=~_{rc_6fuCx2BvDsV?e=Efc=+1#slnwVhra@ z^xP=Sve%ho6I;YwRwGX^LNf;3mUIIYBOk#@I6E}7RsR?5XD-4uzJ$h<6H$z!bRC5o zE8I9LPZ@A$q#IzMN6iQSh?@7SPgJ~J`}6mX)$MPtI_&JK`3U&t4tmAV3odjcqA`tt z;N#9nv;)T*ojZ@z_xH8*jP>%}O;+~-)gM0@dM7C-$DW+B3K;%0Y{WD$=OdY;5d^6g znvTBl!oJeyObUKtfR+{13}>8f|4+C4q5dl8q`vgSgy_+~X4BUji|mwAzSX{M`<9~D z?VHPhu76QO!h1UdxM_%3%G-_0hyTVt(aY=^khZ)KnJbH-CMILF{R+BHokaie&C*RT zT{tHj$%cdE0rFVneUdz+7z|v2BLh)A4ZtXDVwLp$6H6c2j8(gLW96=0_(oYFRPR}! z=UpUag|Kw%R@mZAr@69443Jn!-OO!+L91$*4A(ZN1zcYN++3!PlxkoI!7GPw{+T`G zy$H4+qg&Ux1Hm~^1IywJXqv_k<hZ{zDJAzV+L^F8i<n}7^bP2tv|gQMJP%9Bn$2ka z#Etye@1r2JNgqR%{y~-!4oRkUQpEss)BX)w<MU<Cn!P2P_^!PAL}Bcy^0gHiS*Z_a z6fI|B+9;I>Ol>aA+~`j+EW(lg;Og}u=u1KJ(O4wC=7-vuiP1i0R<=tkhPU5AY$$rI zQi3?%Y;fPEb+*jRl<LnaOM>h3QYUg(*!Sc=`Ve8+#1wdFCc9r^E|6MGUQO68<${#S z3R4jg3@~G@CmmScQo?$o=cO^QH!MTz=^-|^hcIzN#h1rFLiHCncJs@CK+M+oOsVtR zzy2|AKE$B3QpuHX7?|j0_(zy2-iEAp47Ogw#NaRj9v_l&GLV{o50_wW$5~NQqO7%! zPaH@)a6jU^E%?#8Nq8BQ|C}&kU`GfYv1j2|ERMg{^;W)ny89&e?&mZe)M3c-8E)V} zhkb-e)(rUk>A3XXQFJ)nr<?oS^)geK9ltg=qp7Um(Fb5oVAu5Y!{hS6c}+oXQaZ5y z3-}DF;Z+JoU^~AAJzE#y@mJ4nZ*$zdOz91>*f&Ljbb@5|=29T>S?D^}fVwY--uTtu zTMkh;9-hOIN7iJmsIaI93wL~vs!p`kUdOjawgI0ratT&=i=?<naRgn*APO80;?3=Y zuWa1kw1!eaq9z%P5F=m|pwS2&a8gpVkLVri9RxQ&NTqA!t_WZKcYXiav5}kC11=Yw z%^nyN@)6t1OVU~g;Id$B%&#-dTxW$7F`XmG%3odZ!EcLr+J(KGF+k3Ey_6z=k|&Q{ zuah+$ZqGy!2nfAN3CneCC<w!dk6`Qk)QP+v0<)Lhyq%5JqoDSZ5w+6X@1YUhJlY!v zv9u~1DT#?MQmS9)BL>hI0}YT`l_OOZ&m{tERp~LX#HjpQKVfD!D?v^uF;*?;zHkM3 zUByriGeGnlZLE&F1E{<|8_(wCaAO+OMVSPAqz88I8k~Bnn7v(KOH!n!&Ga*lcgeYI z3L-Tx9kmtf{!CSxG)=~uigo)^^V8wJ?n2W42#vdGUk>dOWL>r5=|B%E+`P;V(3yNX zC}qmRTU0%Y#02veYQ;z%Yz@zswJRYlJ~VTJO_LlZ3hm_i)?Zv+%NXnF5Q=MfVMCj0 zR5HEZN&Y3#LHS-k-$=YKMn*7Bm=Lstpcy$YayqQ=qO<z<=h8$cnamCYx;y>NT#~LO z2NvNyT?K3yV0@8Ao>fhEOoFEl*^u!8fBGObcsr6)Qc7p)wjtliPYIL0AmTch_&>mp Vv#07tKs^8e002ovPDHLkV1ly-^R)l~ literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/NotSupported.png b/Emby.Server.Implementations/Plugins/NotSupported.png new file mode 100644 index 0000000000000000000000000000000000000000..a13c1f7c1c03605a5d7e0afdc6f4a81621330ab2 GIT binary patch literal 2046 zcmV<a2LbqrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000NYNkl<Zc-pmB zdr(x@8UNj77Zz8_`)y(<@=^#dd4+`qnoP))M3RWM(~;U4r~RWE+Qc|&ND)C}<0R2& zgH6(O8cjwsj;WT0#GnBJEU#VV5d@KkAjsmnBF|m+ar@o9H?kJO`VVL3gL}Vo?stCY z_dU+H4D1ilcZDfAu2SZ#Na7?BOJy)j+%--Zurae#Sx)noN3ijegR!^y*SnK8__@o@ zh3D>qliy>cVqq8^Lf84jXzRbXHoxpjmsPn;0Hn?PQ*K6WF7k0Q)&K*4=l2RP#>Du~ z&{=*$nX*rrLCU%10^qLNpR9}9`2}z}miUm-{=~TJI_SOr4E1M4-KiywiL`EFxd8a6 z_NQp#w*M1QZ=!SFht=gCNieu?L-VPk8)+qtNu<;*7XYt{T?uDmpV^e<8$_q?KEMNr zF2i7BJ({X3KgoMv{TeC9mkWT4n@ke=U14fV%#M>lRXnfFXhF;2myuB197%8eBs0qe zKui+QRFu#k`}<=e@wGny`Vj)4BmlqW0B~t>o5XDUQSCmtyL?~my+;KgQ6E%{!EAK1 zSQe%<OFC!IK&;#H2B3U_|0Lmabf5bWlOsJ~L?YYO*1ygkKA4*vN9^A3onR+JH~?<y zlBe#)zFr2HI0K@GiQ!Z%z4yEeXsh`-mrx+`ZF*$?k3*Kv65_4%<2P~ae0$J|%7FoU z0DM}ClQr?L9VhN`NaIK%vY7@CiV^d|=~xqq5eteSw>fJ7<mFJk^GB>NYV;?q21^vG zc>u4z2Q>VOG{hR?AWS(3VCb1)Yyfd5UBsppz$}n-3aWPt2tb3M0KgstDa61b3a5*J zYz?`Bf_k!>vRg@qG|r#g?jQgb0ucWZ0oX|Zl)j`KvkO37nyQK2@g_8lHJBLehe)~t zo@>^@EhGr&{SYu{ZCJ4fKo7*ePXKm5I)E#0DKrie2|D_;|2eN7tB43(`FK`@`|lo) zj`v-il?7ZsLWV6iv9SaIE(W6i3iXk{Ail8vkpOt?+ZdjAwsB;*V`$<Qy-$%yNW3a{ zC;THm_oWawcXFey$-XN@6c-}Ox|kANd9N68uh((_?lv9HD3yTChnWp9nb;c5#N4)= zw;OMO&o4+xTm{QqMKgfUMUTB3LSEeZeC)B190hRmG_8;<4uBE9pah!innr(>AMRAQ zK_qeD<DZCeiS$Oqj$C@MpzoV+F>+^Go_(mHp0W8{So&Z{3v)xW^Pi9TG9*V144qpX zfRHSZGU)kOi`(Bbc;dOI;TatTu}o&QYMPmWuB{CN6%|<ZLNr!yNkZ$%Gp4vbH7-j< zm83K;ENj!VQD2ATqyi&fE$#vlzj^1;QH)=gA?B6sF!r>;&{PA{o!izWVsC#)6VoAH z6N%PiM-lLB7{-}?#O$p0SPFpC<vq!#BNU0be(PMwlWHLoY>sX%<P0WzW^m=L3B>Oz zfT8>}Ov3}j3W5ExOmhKjHbETt1f)5eDL#(ES?-AVgLS@~3CF94G7M%jJ9dB8xHYS^ z{+pw}jgmeYDBJ7n@AXE+CaVA1N;05d=zcCMoJD9Y9e`(8E?h>tVC<z1&B0;u!eur? z5*&`{RS~#x>5FMaMf=aW74GT->AH~T<hZ45!_=4#VyP3{gI8g-B89@T1DK}d5IfUm zRM;H7c*90&PV_@WzX=zgxeEENSD^p*zrfN-S+f}nt1m+YI*=E|Sn={!G?aaS%!X@L z2B_<iYvNx04H=})N=$THsMgO>lQTU?8_})m97r35K-<}eX{`<>{Ty5$^MhApFzLr| zG4V7Mn|}$tsur&2Tb4?D+~2UC;vo&nuP!39zSCDI#d1yjpYo_`*9x@R(C6rmIa2_B zI8%v!%~VzU@Khr=6BW2JIViwI5xp%Nmoh&=+SAFH8|;P4+1e!mOm39JF=!2xN)<Be zI&1;F1l&<Qyg5gsTNrx2Y(Yg$@9~0@9iMVGgvph8$pJC@x5a!ke7p}&#f6faO;m|z z>9RB}ysRiDIQm6WXL5xEja_}ntZlaiKv%Jj0*JLKw+z>SMo?Y9fc3?7(WDv1eEY>U z8-B`z>6aa@nfwE1W$^ZKgN6LhT7zyu2oMGaBFYZ!_<c0@4yiXZbY{;3D99!U^$W$3 z;ZILU4YMw2{j6>(skkm2eEVgYHwmwrB6(G4T=3eS5;c;Os6`Zu=<t@s2!KeqOPbrS z;ncur{@?mWE(ie9h=E^F&}kk<&dthv&{|fFnB7&2T`Zoel5}m{_B8Z<pu$-BD3TJR zsbF#-SgY`xGgg6xMN7vI=+;eK*wWHnKvN_9bzG9JiQP%{e$KoQ0G(*~+aC0)ZhfvO zsmsTF1L|<8F!f0Alm6RRzqppxG3bBiDn`!TL}+LbynQKMC1QRh#e`O?#f^bM+I;fA zTh-V1koG1QPdoz$6ulw~yV7D=*yULLMj$A=M-ui{hk?H>xgl#gn9)Ne$DcJ@IDV;_ zVqm^!hW`2t=5Fa9#54EruF2eX;kNF?r-Ng)LM(B=a?IAIlq85NNcicymckm;m0-{& z3#ed#Ys<aCx9>|0vjCj4!TpMw{*g&*HRnzP>t(v+FbEl76yCY-RtVW(Z*bId?fI<m c{R6812UxKZ7X$tn8UO$Q07*qoM6N<$f>PAuAOHXW literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs new file mode 100644 index 0000000000..8596dfcf8a --- /dev/null +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -0,0 +1,674 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Json; +using MediaBrowser.Common; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Plugins; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Emby.Server.Implementations +{ + /// <summary> + /// Defines the <see cref="PluginManager" />. + /// </summary> + public class PluginManager : IPluginManager + { + private const int OffsetFromTopRightCorner = 38; + + private readonly string _pluginsPath; + private readonly Version _appVersion; + private readonly JsonSerializerOptions _jsonOptions; + private readonly ILogger<PluginManager> _logger; + private readonly IApplicationHost _appHost; + private readonly string _imagesPath; + private readonly ServerConfiguration _config; + private readonly IList<LocalPlugin> _plugins; + private readonly Version _nextVersion; + private readonly Version _minimumVersion; + + /// <summary> + /// Initializes a new instance of the <see cref="PluginManager"/> class. + /// </summary> + /// <param name="loggerfactory">The <see cref="ILoggerFactory"/>.</param> + /// <param name="appHost">The <see cref="IApplicationHost"/>.</param> + /// <param name="config">The <see cref="ServerConfiguration"/>.</param> + /// <param name="pluginsPath">The plugin path.</param> + /// <param name="imagesPath">The image cache path.</param> + /// <param name="appVersion">The application version.</param> + public PluginManager( + ILoggerFactory loggerfactory, + IApplicationHost appHost, + ServerConfiguration config, + string pluginsPath, + string imagesPath, + Version appVersion) + { + _logger = loggerfactory.CreateLogger<PluginManager>(); + _pluginsPath = pluginsPath; + _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); + _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions.PropertyNameCaseInsensitive = true; + _jsonOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + _config = config; + _appHost = appHost; + _imagesPath = imagesPath; + _nextVersion = new Version(_appVersion.Major, _appVersion.Minor + 2, _appVersion.Build, _appVersion.Revision); + _minimumVersion = new Version(0, 0, 0, 1); + _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>(); + } + + /// <summary> + /// Gets the Plugins. + /// </summary> + public IList<LocalPlugin> Plugins => _plugins; + + /// <summary> + /// Returns all the assemblies. + /// </summary> + /// <returns>An IEnumerable{Assembly}.</returns> + public IEnumerable<Assembly> LoadAssemblies() + { + foreach (var plugin in _plugins) + { + foreach (var file in plugin.DllFiles) + { + try + { + plugin.Assembly = Assembly.LoadFrom(file); + } + catch (FileLoadException ex) + { + _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin.", file); + ChangePluginState(plugin, PluginStatus.Malfunction); + continue; + } + + _logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugin.Assembly.FullName, file); + yield return plugin.Assembly; + } + } + } + + /// <summary> + /// Creates all the plugin instances. + /// </summary> + public void CreatePlugins() + { + var createdPlugins = _appHost.GetExports<IPlugin>(CreatePluginInstance) + .Where(i => i != null) + .ToArray(); + } + + /// <summary> + /// Registers the plugin's services with the DI. + /// Note: DI is not yet instantiated yet. + /// </summary> + /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param> + public void RegisterServices(IServiceCollection serviceCollection) + { + foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>()) + { + var plugin = GetPluginByType(pluginServiceRegistrator.Assembly.GetType()); + if (plugin == null) + { + throw new NullReferenceException(); + } + + CheckIfStillSuperceded(plugin); + if (!plugin.IsEnabledAndSupported) + { + continue; + } + + try + { + var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator); + instance?.RegisterServices(serviceCollection); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName); + if (ChangePluginState(plugin, PluginStatus.Malfunction)) + { + _logger.LogInformation("Disabling plugin {Path}", plugin.Path); + } + } + } + } + + /// <summary> + /// Imports a plugin manifest from <paramref name="folder"/>. + /// </summary> + /// <param name="folder">Folder of the plugin.</param> + public void ImportPluginFrom(string folder) + { + if (string.IsNullOrEmpty(folder)) + { + throw new ArgumentNullException(nameof(folder)); + } + + // Load the plugin. + var plugin = LoadManifest(folder); + // Make sure we haven't already loaded this. + if (plugin == null || _plugins.Any(p => p.Manifest.Equals(plugin.Manifest))) + { + return; + } + + _plugins.Add(plugin); + EnablePlugin(plugin); + } + + /// <summary> + /// Removes the plugin reference '<paramref name="plugin"/>. + /// </summary> + /// <param name="plugin">The plugin.</param> + /// <returns>Outcome of the operation.</returns> + public bool RemovePlugin(LocalPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException(nameof(plugin)); + } + + plugin.Instance?.OnUninstalling(); + + if (DeletePlugin(plugin)) + { + return true; + } + + // Unable to delete, so disable. + return ChangePluginState(plugin, PluginStatus.Disabled); + } + + /// <summary> + /// Attempts to find the plugin with and id of <paramref name="id"/>. + /// </summary> + /// <param name="id">Id of plugin.</param> + /// <param name="version">The version of the plugin to locate.</param> + /// <param name="plugin">A <see cref="LocalPlugin"/> if found, otherwise null.</param> + /// <returns>Boolean value signifying the success of the search.</returns> + public bool TryGetPlugin(Guid id, Version? version, out LocalPlugin? plugin) + { + if (version == null) + { + // If no version is given, return the largest version number. (This is for backwards compatibility). + plugin = _plugins.Where(p => p.Id.Equals(id)).OrderByDescending(p => p.Version).FirstOrDefault(); + } + else + { + plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version)); + } + + return plugin != null; + } + + /// <summary> + /// Enables the plugin, disabling all other versions. + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param> + public void EnablePlugin(LocalPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException(nameof(plugin)); + } + + if (ChangePluginState(plugin, PluginStatus.Active)) + { + UpdateSuccessors(plugin); + } + } + + /// <summary> + /// Disable the plugin. + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param> + public void DisablePlugin(LocalPlugin plugin) + { + if (plugin == null) + { + throw new ArgumentNullException(nameof(plugin)); + } + + // Update the manifest on disk + if (ChangePluginState(plugin, PluginStatus.Disabled)) + { + UpdateSuccessors(plugin); + } + } + + /// <summary> + /// Changes the status of the other versions of the plugin to "Superceded". + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param> + private void UpdateSuccessors(LocalPlugin plugin) + { + // This value is memory only - so that the web will show restart required. + plugin.Manifest.Status = PluginStatus.RestartRequired; + + // Detect whether there is another version of this plugin that needs disabling. + var predecessor = _plugins.OrderByDescending(p => p.Version) + .FirstOrDefault( + p => p.Id.Equals(plugin.Id) + && p.Name.Equals(plugin.Name, StringComparison.OrdinalIgnoreCase) + && p.IsEnabledAndSupported + && p.Version != plugin.Version); + + if (predecessor == null) + { + return; + } + + if (!ChangePluginState(predecessor, PluginStatus.Superceded)) + { + _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); + } + } + + /// <summary> + /// Disable the plugin. + /// </summary> + /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param> + public void FailPlugin(Assembly assembly) + { + // Only save if disabled. + if (assembly == null) + { + throw new ArgumentNullException(nameof(assembly)); + } + + var plugin = _plugins.Where(p => assembly.Equals(p.Assembly)).FirstOrDefault(); + if (plugin == null) + { + // A plugin's assembly didn't cause this issue, so ignore it. + return; + } + + ChangePluginState(plugin, PluginStatus.Malfunction); + } + + /// <summary> + /// Saves the manifest back to disk. + /// </summary> + /// <param name="manifest">The <see cref="PluginManifest"/> to save.</param> + /// <param name="path">The path where to save the manifest.</param> + /// <returns>True if successful.</returns> + public bool SaveManifest(PluginManifest manifest, string path) + { + if (manifest == null) + { + return false; + } + + try + { + var data = JsonSerializer.Serialize(manifest, _jsonOptions); + File.WriteAllText(Path.Combine(path, "meta.json"), data, Encoding.UTF8); + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogWarning(e, "Unable to save plugin manifest. {Path}", path); + return false; + } + } + + /// <summary> + /// Changes a plugin's load status. + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param> + /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param> + /// <returns>Success of the task.</returns> + private bool ChangePluginState(LocalPlugin plugin, PluginStatus state) + { + if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path)) + { + // No need to save as the state hasn't changed. + return true; + } + + plugin.Manifest.Status = state; + SaveManifest(plugin.Manifest, plugin.Path); + try + { + var data = JsonSerializer.Serialize(plugin.Manifest, _jsonOptions); + File.WriteAllText(Path.Combine(plugin.Path, "meta.json"), data, Encoding.UTF8); + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogWarning(e, "Unable to disable plugin {Path}", plugin.Path); + return false; + } + } + + /// <summary> + /// Finds the plugin record using the type. + /// </summary> + /// <param name="type">The <see cref="Type"/> being sought.</param> + /// <returns>The matching record, or null if not found.</returns> + private LocalPlugin? GetPluginByType(Type type) + { + // Find which plugin it is by the path. + return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(type.Assembly.Location), StringComparison.Ordinal)); + } + + /// <summary> + /// Creates the instance safe. + /// </summary> + /// <param name="type">The type.</param> + /// <returns>System.Object.</returns> + private object? CreatePluginInstance(Type type) + { + // Find the record for this plugin. + var plugin = GetPluginByType(type); + + if (plugin != null) + { + CheckIfStillSuperceded(plugin); + + if (plugin.IsEnabledAndSupported == true) + { + _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name); + return null; + } + } + + try + { + _logger.LogDebug("Creating instance of {Type}", type); + var instance = ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type); + if (plugin == null) + { + // Create a dummy record for the providers. + var pInstance = (IPlugin)instance; + plugin = new LocalPlugin( + pInstance.AssemblyFilePath, + true, + new PluginManifest + { + Guid = pInstance.Id, + Status = PluginStatus.Active, + Name = pInstance.Name, + Version = pInstance.Version.ToString(), + MaxAbi = _nextVersion.ToString() + }) + { + Instance = pInstance + }; + + _plugins.Add(plugin); + + plugin.Manifest.Status = PluginStatus.Active; + } + else + { + plugin.Instance = (IPlugin)instance; + var manifest = plugin.Manifest; + var pluginStr = plugin.Instance.Version.ToString(); + if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)) + { + // If a plugin without a manifest failed to load due to an external issue (eg config), + // this updates the manifest to the actual plugin values. + manifest.Version = pluginStr; + manifest.Name = plugin.Instance.Name; + manifest.Description = plugin.Instance.Description; + } + + manifest.Status = PluginStatus.Active; + SaveManifest(manifest, plugin.Path); + } + + _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version); + + return instance; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogError(ex, "Error creating {Type}", type.FullName); + if (plugin != null) + { + if (ChangePluginState(plugin, PluginStatus.Malfunction)) + { + _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path); + return null; + } + } + + _logger.LogDebug("Unable to auto-disable."); + return null; + } + } + + private void CheckIfStillSuperceded(LocalPlugin plugin) + { + if (plugin.Manifest.Status != PluginStatus.Superceded) + { + return; + } + + var predecessor = _plugins.OrderByDescending(p => p.Version) + .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version); + if (predecessor != null) + { + return; + } + + plugin.Manifest.Status = PluginStatus.Active; + } + + /// <summary> + /// Attempts to delete a plugin. + /// </summary> + /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param> + /// <returns>True if successful.</returns> + private bool DeletePlugin(LocalPlugin plugin) + { + // Attempt a cleanup of old folders. + try + { + _logger.LogDebug("Deleting {Path}", plugin.Path); + Directory.Delete(plugin.Path, true); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogWarning(e, "Unable to delete {Path}", plugin.Path); + return false; + } + + return _plugins.Remove(plugin); + } + + private LocalPlugin? LoadManifest(string dir) + { + try + { + Version? version; + PluginManifest? manifest = null; + var metafile = Path.Combine(dir, "meta.json"); + if (File.Exists(metafile)) + { + try + { + var data = File.ReadAllText(metafile, Encoding.UTF8); + manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogError(ex, "Error deserializing {Path}.", dir); + } + } + + if (manifest != null) + { + if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) + { + targetAbi = _minimumVersion; + } + + if (!Version.TryParse(manifest.MaxAbi, out var maxAbi)) + { + maxAbi = _appVersion; + } + + if (!Version.TryParse(manifest.Version, out version)) + { + manifest.Version = _minimumVersion.ToString(); + } + + return new LocalPlugin(dir, _appVersion >= targetAbi && _appVersion <= maxAbi, manifest); + } + + // No metafile, so lets see if the folder is versioned. + // TODO: Phase this support out in future versions. + metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; + int versionIndex = dir.LastIndexOf('_'); + if (versionIndex != -1) + { + // Get the version number from the filename if possible. + metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex]; + version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion; + } + else + { + // Un-versioned folder - Add it under the path name and version it suitable for this instance. + version = _appVersion; + } + + // Auto-create a plugin manifest, so we can disable it, if it fails to load. + // NOTE: This Plugin is marked as valid for two upgrades, at which point, it can be assumed the + // code base will have changed sufficiently to make it invalid. + manifest = new PluginManifest + { + Status = PluginStatus.RestartRequired, + Name = metafile, + AutoUpdate = false, + Guid = metafile.GetMD5(), + TargetAbi = _appVersion.ToString(), + MaxAbi = _nextVersion.ToString(), + Version = version.ToString() + }; + + return new LocalPlugin(dir, true, manifest); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogError(ex, "Something went wrong!"); + return null; + } + } + + /// <summary> + /// Gets the list of local plugins. + /// </summary> + /// <returns>Enumerable of local plugins.</returns> + private IEnumerable<LocalPlugin> DiscoverPlugins() + { + var versions = new List<LocalPlugin>(); + + if (!Directory.Exists(_pluginsPath)) + { + // Plugin path doesn't exist, don't try to enumerate sub-folders. + return Enumerable.Empty<LocalPlugin>(); + } + + var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly); + LocalPlugin? entry; + foreach (var dir in directories) + { + entry = LoadManifest(dir); + if (entry != null) + { + versions.Add(entry); + } + } + + string lastName = string.Empty; + versions.Sort(LocalPlugin.Compare); + // Traverse backwards through the list. + // The first item will be the latest version. + for (int x = versions.Count - 1; x >= 0; x--) + { + entry = versions[x]; + if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase)) + { + entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories)); + if (entry.IsEnabledAndSupported) + { + lastName = entry.Name; + continue; + } + } + + if (string.IsNullOrEmpty(lastName)) + { + continue; + } + + var manifest = entry.Manifest; + var cleaned = false; + var path = entry.Path; + if (_config.RemoveOldPlugins) + { + // Attempt a cleanup of old folders. + try + { + _logger.LogDebug("Deleting {Path}", path); + Directory.Delete(path, true); + cleaned = true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogWarning(e, "Unable to delete {Path}", path); + } + + versions.RemoveAt(x); + } + + if (!cleaned) + { + if (manifest == null) + { + _logger.LogWarning("Unable to disable plugin {Path}", entry.Path); + continue; + } + + // Update the manifest so its not loaded next time. + manifest.Status = PluginStatus.Disabled; + SaveManifest(manifest, entry.Path); + } + } + + // Only want plugin folders which have files. + return versions.Where(p => p.DllFiles.Count != 0); + } + } +} diff --git a/Emby.Server.Implementations/Plugins/PluginManifest.cs b/Emby.Server.Implementations/Plugins/PluginManifest.cs deleted file mode 100644 index 33762791bc..0000000000 --- a/Emby.Server.Implementations/Plugins/PluginManifest.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; - -namespace Emby.Server.Implementations.Plugins -{ - /// <summary> - /// Defines a Plugin manifest file. - /// </summary> - public class PluginManifest - { - /// <summary> - /// Gets or sets the category of the plugin. - /// </summary> - public string Category { get; set; } - - /// <summary> - /// Gets or sets the changelog information. - /// </summary> - public string Changelog { get; set; } - - /// <summary> - /// Gets or sets the description of the plugin. - /// </summary> - public string Description { get; set; } - - /// <summary> - /// Gets or sets the Global Unique Identifier for the plugin. - /// </summary> - public Guid Guid { get; set; } - - /// <summary> - /// Gets or sets the Name of the plugin. - /// </summary> - public string Name { get; set; } - - /// <summary> - /// Gets or sets an overview of the plugin. - /// </summary> - public string Overview { get; set; } - - /// <summary> - /// Gets or sets the owner of the plugin. - /// </summary> - public string Owner { get; set; } - - /// <summary> - /// Gets or sets the compatibility version for the plugin. - /// </summary> - public string TargetAbi { get; set; } - - /// <summary> - /// Gets or sets the timestamp of the plugin. - /// </summary> - public DateTime Timestamp { get; set; } - - /// <summary> - /// Gets or sets the Version number of the plugin. - /// </summary> - public string Version { get; set; } - } -} diff --git a/Emby.Server.Implementations/Plugins/RestartRequired.png b/Emby.Server.Implementations/Plugins/RestartRequired.png new file mode 100644 index 0000000000000000000000000000000000000000..65fd102a2ca7ffb99c7843fa46b1c5274ec0e76b GIT binary patch literal 1996 zcmV;-2Q&DIP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000M*Nkl<Zc-pmB zeN>cX7XQr`GXw;Kd?{+jT}C0~W0?5L5s0=A&*Dm@R@;$vPaQpbjN?|W8G<l?rc$hC zyOz~frX8$SqAbk-fdyf3X58=-5&2TqK|~lp83yLv`_B6k!-ow2@SJlw^W5is?)^RY zx%c;61aLfrr_y7S++~7qgc7MlEOUX`blYMwW94JH)yHVvIt?559Rf$rPi%=^;U{-F z8koEpQonhmVqm`6hRa2HsB60OaLWF(mu<=!0w6n+9orJ}e5Q}oQUNr7$oUG?z|{R9 zE*|@!IyS31fs}(Y1wgLPj_Hcn^c7I5q<FZHe~P$!Fb2F{gW+&y{gNDQ6n$r!DF8nD z>{w&OtDgdf)pX7t*sk0&8fN(`ICCiT>e3u-G%34g3V_$~&5=ixPpnS#T|lR=-_8LD z+mBZ5Y1Eb%|7+EIhBrvrJyQVOJX|CTPo*!>g{OW2l&Lsvf)2X8=MbqmvzTU0BzI>D zfS6=XZDwSXa@{_m_|ke{pq&6z6Mz?40Bl+Ok7U?>Q)QM~uFk5wGhF}@!;bh43|l;` z)`=y}kj{CQKZ4h61*-qRZHfF6^+yk&x4i)Zq0s(o+h1o-9}M<(Lz(s;DI8P?3&6vW z^XMJr-}VDTtO4QJz_2QY<_-BkXF0d#wh&mnn|?CmV#sh+LUFtJaR&Akom=ohadWdH z06scRj8XN*`xLt*(m0U_?UuoT5{Nlrb<7Zn1rtb+b<UUp^)cw*-GE0jwX;cU#1up| z3gGp>12r#@hN31A@k=5e4E+`e>;SPRoy4XMz&#-P5cK&Q2|$e>55Q3bVkrVUDV<IN zE&+5El+?ZTRNd8dNXzKS9S#CuB><|A2*4%+Q0+^~4u=2?xl4@7)C?H46)?3nK`46w zvjT$Qp;!Pk9stapc2RKzU;t3QM*y}=AHdnS<BcMT1m~}HeqUthI3DEhIzKT;{^$8& zD&L0^6M-vx$gtHeH>LtWIS{ss0Ax%XfM?dqz*XO9+i#q2GhL^7ABlv-t9VP~C#vLU z6&`ZB#;)3FTm=tcaW-`CW)V-+umEmrHA{0vLMBDPFmr|(L4~o;^2+i&?NxB~1sRDu zZ<%E@vS6!4&$JbaXVxxP?o%Yi11$ygg~R~>N=z%2ec+q8a^!Q|yLl5*krTW_LNF^l z9B_4msj(i-r%KS?byvM?SIy~>)E08P$JCW9J$d2NDa*qP6-jEK?dbFXFhq(nN`Akm zD4~52zGoRiy}WTSZUs@&O*&Q#%)M^7@b%Y2s*FmvsjNwIS1n3h{Zz;aMbZ+W{m03# zKrk{F@Mqx3h$ShB6QT;g#}mJyR^pZrhadkvS78C`VaVSL)wU|nsQ^ez--;;+ijPY6 z3wEQMH1L&Rmp&{Fv%)5)U=mYeF`^3!@JY&B_^j$}cnta=Jt_v6zY=Hj4<KS&r7ye7 z>AyP@%)`S>N6$UW+Qi(`KkfZfh%D6KCCzuX*Vdrb#Q&Ye^xO=LJ3LLq66DmD<KIoU zFup!mJhsB6Kz#bL2A%zv@U5W$vjhrkRc%1skwQyYM)_RUq};GQu1m2@jqBBQ=<Dc$ zSSE%1w{!7Od@QBqd7z()L+nhi4Bf4h7w3G4njni2;Rip*x2XqUvV2F{iC4rBZ96ef zqO3j@!Tu>Isyhf=@`S6_?=PBT7r(OcfIeGojClPedTPn2n8Ix(t{<c(r@xh)(5vd~ zPl=^K=f!L2@9e_Rz#u&5&w)HF2&%p7aA^GwlsBY7fQc!}@WC3np<w^D__6LYl<M(A zjRr69RIE0t{<?}-yOK9yXUa*A!J#?0aHJSb#=f$1H~O^fO6c4NW5WEs;-9x1$3NF@ zfUfNylL8n~jHIYkEQODI0QMfefS)$Q-44LBz%Bh)=j;}bMQAA0;dn*k`y0PFPw_)9 zzv%kM=y_p{$!#C+PI(6P9fkKTP{ul%7nGN1rJkmu3S}iZc+L(0J;hzr;xl&XBw!oR zAfnap@Q9`=j5Iee+J3RkhTo&RaVc|66xw@gC#_EQ(Hyq$ML}8FOzBiwf{Kb=NF`O% zD1ePm13gVVIr0G$NnpO`hF=a>^+ju{0>QOkBV=XU`_gu){t9FEXIljD{RvyGB08yv ztyI##{2~XWr3EPY+2;H;`iv3`-8_J$6oJPn>5OAr2X>X%?3exJ2;WjR*~8*}Is11V zi`EfSO78LmL|SKWG`>@UfNdvN#O*}Ux;4Pn20Hl<<UH?J=WNe7%st0BaYp4P;`_nj zi2%ex-1xZxjr!|f#^+R}V6*`hm8Prr1cds%I&b;IRF+mQHa2Dv;apxhLNm%@;@&~c zlSHHyCAfVu9mLOQ8FBt=7<Jp@8--TJ)oPvC<p}69g#=;<OnYQn`66(yB|BVnI}#cw z+Ow_XoU!YWghICNL_HDdr_>4gI485fbmC3W9pf5Fr`;jArj%p>OGvo?OEbi8Y_+Qb zA`Gx?xi`4>eN5tm`){e6w=3oo_!fy}e3i0KoC_N`Og+qe1&kPA_dUQ@!(?NS|5n1! e`^P(H$NvG|Dd5z6`yu`S0000<MNUMnLSTZEn#wZ( literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/Superceded.png b/Emby.Server.Implementations/Plugins/Superceded.png new file mode 100644 index 0000000000000000000000000000000000000000..251e70535b861efd0401761c5eaa0c8d546748e5 GIT binary patch literal 2136 zcmV-e2&eanP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000OdNkl<Zc-pmB zc~p~E7XKwA5DJt8si4$_Vicq<At0bAlsP@(9Bk==w$*9XnbA&Npe`MYS`geu(LwYS zEmUo*9<2_YDq7p&2q=m{5;tT~0a-+YEJ6qn0?FK$e3mE*_7A>uUe5R3_wKvDci;W} z-U|=?Km4q<f#HrK-f_OrMko;3LD$ltZ_(lXH#X#DP`}{?=6LSI>o543)&6h0O6<}- zBffx*>o77Ip?gq`lApKXdPURNk5jIcn2ZAiKy*1iuyWk&*uggXbHLrb=2)KV(emhJ z6lLtm3yjMPA!Fx20gx!;0~&o+{s^3vQ9kS_K4sj|8y(J{Lv<*&bV`C^5{+vaC;)?% z@quceCHn!@ELvwXOk3{c51r(1xO_17&eQ~jKN%Yb3V`!3U-%uBy*Vq?#hq4Py3q_^ zLJF!B7m=Tnxi2zVwStU~1`2?K*iJY)YweVRiA#R~vgKxLNC67Ay$8SbmtUu^3TkZw z1wcS;Xnw3;g>2z2zMyy!&{0bO@(93(3;?6WeQMp7PPuVGlAyTUrWXYuRBZ~bL$_XR zF!ZLhk!-eu+~EC}H9+25W*5K1C{6zcn%djo@%fgcO~1BIgVCvZ1X;{^8}!2v20*Mz znA{{=l>&6J3HVPYhMA1?eR~H`pJVQG7!AC>m0pcc<<Mwm3FWOQZ7q`0uZ>L2s;=ZZ zt*>p((iyuuG4adkzXN0LgA3LNsO2kmQ|`jaVoi;2fe&U-Jb}3}o3V?U9=$}61vlz| zpbV(Ce+GGM{t&XNS(b}8<>>6arO>psqOI^6d^bj#K=c4u{%_#Y2Q)v~c~)F-D-I03 z^LQ43*h-%vekK6zK)^u)u#5mGT*=yW;Ls6WOM5eBScgK>u0?BG2Sk;{n3Oc%h64~t z8Q4PQ^c!F|infA^T2o5w&Z9-@dsg1>LjVi}z&DiuEN1|Qr5!#|9VqjJSmJ=R@Ao5& z|0bH-+u(4&1c6^Kaxwu>ZJ45#EnNq-;v8D4D!>=Lgh8XcA(pxWW#0h0dW)>|2cQFx zB}2Jw71ebM?)dG-RR3`(FS~`3(o&SxRAJ5o5BTo=B!C=lnE+hb9IUny3Q<^IfAVKl z-7j8l_QONHB=d()kh_cs4W(g8G_k>=Hu?a-YHR#foQqwIX^Y<j+~#8Up&Q`qwJ0jO zi7ufn_9n(pgIPc77yzfZ_dO$zD{Ai*R=3p9cPlFzYR;Lf{l1k)yekz;sE!)*``-#a z)rD0TvVUks$dY$SK^6dtIAYK-EWNuP9a;@OviWb$fr||*zt6pQ{c#bBs5x>oGey&J zTy%<gTl&ttnX+Bd@L-_w2#pXv9{}?Z7?Ay4BSIEOQ1E%A8wr%X6XasRp8VnXG${t! z(pxCYI*WS^+9`kjmm=?RY4bV8Tk=Y@Hez(x$1^AXBn=M&s?(nh;IX$A1>g6O3qGHM z$5Zf=rU6O$qYxc8j?PR<uu}kZnwN3&*s(78x?G38s!F&aa!lx~>Eq5w!>0hXr+aU~ z@4=18PQ6EIf9Dy&rHEcFp}dk>cXylhWAvv`?ns93R~MZ60$_9Y%YY+Z!IL6fy&ZrC z6~_dN=vG|ty;V;IKVj<MneTz9m_ZbrlH1KQYX^@2xPJs?QW^u`!T?xb-4def?l#sn zx9jJHZn*gC&QHdP#=F_YxD0V#<28%)zdn;D=y)>weEJaZkeyP_1-IC9>Px=tfn|H5 z01_T(DD{tS(i~J`PUE>PI89q{-i=KuQEi;oD4h|6n!M|1t!sopWCMxEs~8a+NM%_F zXlVk0EuAtXY}T)s({9ipd&?;b&ZuS)oKPk!J@DadIn8&C%0_@8KHhMV)5$HehW1V+ z?);jIlLfUa)*UN3VA26)e305_`5ZcG>1HLMbQ?(PJL!_6tpfCPs@l4dvlR8k<<LHC zL{~>AYE*>?W;{2gJ%QVEV5j0WM5Qgnl}-EM^HuH)k&w^(ahW{E&Cw=^^>=m~8~2^B zS(AFU@_+PM%SmyNS{@xq$3`w!Sr)o)EkS43P!t`_MA?JZ%$$;joDY2L6DBXDv=3Qe z5u6H6;eqH)B;}5ipiDdp-`HGF>S$+_=BUo9M#}_<YwZ>QNH`uUpA62JDISB{KNa9~ zPT9`rgN26|O?M4i_0NB7_n5YXZb+Y#$ec1!AxS}0+cK64j$}maLq(R(0Jy+>U$kXK z&2dK0=?y!MjTQjtC~l-HzR^N%dF%q}MU*)S-}SlU*<@$GU3~kE1>0=9D(F8+@o@;M zGAZp+L~Wl;YojeR5Y;4}1R&!vfVw`Ih8_S>VL)>Qhlyuiy_FEUb_ZNLctPVIe_`yd z&%DCs%neVKjPOO*gA!cN%g3dw5ApYv!4QgxCAxOApQAgJJJ0+P08=Rgf1(wrpZt%* zdhG_|MoJFGug)G3y<kR>qw`R^WnuP6|IcsQBU#m(6KBiTP5A3%8=jTcyn2(*E0lpO z0&xDt0H_kCsb#bZD$(8mgnXzoZ{gDArn_I?a2xrWb-A9`a(hS0nfs@XF7=%oICbR0 zVKcpYd`-$?g)50U@L6~61v9WQxQuTw+8YeLZ#hhFh`u;pKL)o-u5Lb<Q9zoEdRD>8 zO(7Slf2cukAd&0w<&)9C=V@jpD#qMz>bTz@05LUpCP;YxS<7bc;3}Fm4a`UOtJIvi z_ov6RYdJgf`~1_w<DBhS;?Vcg1v97Fac$uIUV@ok&w3cm80YnUP5OVqj#1y3_noHz O0000<MNUMnLSTZte-C;9 literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/blank.png b/Emby.Server.Implementations/Plugins/blank.png new file mode 100644 index 0000000000000000000000000000000000000000..f81ae32438880c574cd298bff484e6b2d72e3ca7 GIT binary patch literal 120 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1|;Q0k92}K#X;^)4C~IxyaaMs(j9#r85lP9 zbN@+X1@buyJR*x382Ao>Fr%o3R|8Ox*VDx@L?S#n0SJIxRtCl{<HtY-1B0ilpUXO@ GgeCwzs~B_u literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/Plugins/disabled.png b/Emby.Server.Implementations/Plugins/disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..eeb8ffefc2d008695cb1f8fbcce47ee84ae5c277 GIT binary patch literal 1790 zcmV<a1_AkrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000KXNkl<Zc-pmB zSxl2z6h2)k1*I)eq=;A}vb%tSOBoneozYPzGjE27D5wxMF(yV66O-{tBa5RE5HgvE z$xNJa2_stp83m0ZBJK(lL0MX)Wog;E&AGQUlto$}ILUdq=l=KJ@1Etm=VyR@Vdm!M zZg+9v|IK7_P*^ZFHl`mL8Tskx(WC$3yvcz*z9<ZPhhMmGVW+#h$Bnh?)`6?*B5KrX zhv8XM6STIr1fM&1?k$?k3k85zP*BjZAu>wb+pB^%Z{LF1Y=(%4aNu&-2;%9(!-o&Y z;&&4Z1wdF>SfEZ!+6MpJxCI<MlmHM41rQb*0uSo%zst<bip1}R77Bp4u&_}1ZCnCW zRo{h)iE)e3(-Q&${Gq<?err}%Rur1l3kAUA{Q2{LMTAGhvA9mq)YJ?l+%nk~P<D4g z<I~3CGiS~mN8`Xk0a)bf>bfc~H}6S&ViMfAd5ao<+`S7b%I`pWdPXP?+fhdr3IH2b zl7IDTdvr`3^L|}D=yX~Npt8Ia(lauAalQxDXuIh0<;%j%%uJ1=065pKT~lFl2}pv? z612Hs`9(%;ggd2W)RdHz2rphdg8{V$7>wC>;Pd$~K0Xd<X=zSir$WeT0VbLzA#p3s z@HzIQhcq`ohpz5!Iu;1sVDrXJFc)CU9t=#-dvN{wb?NQfw?EheAjVo(5&(BfOM%5= zO^c2d5R=KIO2lL`qY?r%QwCz#9Bwq4;QQ~kL6y85b0pmx%}SVusB8cvgS@JW9zt$l zt5z?}yy;xGHyVwQ5FZcnN(x}fBmny!h)+s}kDVW3@#4i`z)c1R2B5dMm)_KRb9-V1 z5E~l<@(K#T3(YFK04UkSC%}hx1*p|(q**R_ip3yucZXN6-@w?&s6!yE0A%0Dpz3P? z6crUISu8fRwY8Si*VmQ#`7K`-9v+^$Tq^Zi=^p^i&!1!9&2wh_Yyc+Mv^ff@Dk~fY zAWBV5{rSJz+Ac+V`zIW0Q8}m{7cX8c!t(Ri<EDK|m0d3o03>AVBO}lQ6_AmUK>+k$ zxpL(fHk+M-_$8RY_cR*K{*xz9wvr_T01wq|5)5H9Lipq)(VjhfcK@(*=cRz4AZUHx z=1>?&2-bzKg@(tEXdV%f`1rswzvbZU><lWU65hXi2mSq@WhYLYc)*xEnCwi_+P1mi zrKF^6-M(YT&49pQXjim51b}#e@4^RP-=)Cia;Z(H(?OrA4@Sqvz{|@En0VsT#s<TI z1L=$A3o2*-{<OHn<mB?;piubG(cy445D=CswUnxD?vOBrhJ;#qLNp%$r|j(PKSRS- z?-GdI@doyD!1j=tJYfYv?5q6!p{80+layGw#l^+rh+3u9YWE&HcC6yaks~~*RC-D* z_By?O!v^@&)lFkNQ|77)asZdZ0e386KHmksVFaC42kHS0==FN=@bCZze$)8mvEe{^ zx)0ewh>wvvBqR*utbk$dAks160S^ca3<8a20JQi5ve_K^$nbbPde8(uHd>6W(P)_E zVjqbQDB4<~v$F#@xXw>11wX%Kbl<){CA@n160qElWBLC!jf%%6#(>M_(oL}QMKHtk zRdaE10Rb{3d5ngKhrpmWfKVg?i9`Y;NK%7CgVS8>yVRFb@xg-!w_zeO&YnGc3Oynt z^9F-KT~=0hx}>B;j>B#Xfc$)ATtYH*_jJv2Esx6s4wns28XBOdr@L06P&^{`6)RS3 z^!Ap-kPsn7(LTWnK;kWdYIz0e7Xr~ViYfw2sgsvZ2NrT7IywaaJ)lx4XT?<@5W<V* zCa9~c`!z2w?{_o}PfoeU#>TEqP2F3#X-hQLbw611UW_zeQ%M03A|m~wGf8T&l)D}* zd_(#KN<`v(1VCCY@(#=t5xTlsUP)MO4Gz0ts{JAxF1eJKS0js!@irM5m=F4yYaDwE z@~H=sU}$h~+9Z?7LYErh(Zh$@Lx&C#carwYWV6;ICnu+Ni!3^r>*Pe@OD7h)xk1g> z04SIQKp1PL@G$}J)!v1)ef#Fx%pJjh-Ykoz151+vG-(NdbVmW;&xbMre?CY_O(PJ@ z2Nsggo7b<PwWZ|`{1;4tsRopllbxL-UAZzVZ1oy2Ax~J_G4irjRh9u#t;7958%ZiN zq0kwVRuD#$sT-Lq04%R1y=Y-UK?{?`@}?wZo@&n+7RDUL7cT&lv&S9)0jd;L2w!f~ zNpL@-cEVH@kUv$@mV1JweYX{Yg|y}5pJCpg7TT7R+n{n`ej(2^sQ~@tn5^T2r5ffE gQf4}v@8^{N0fxpCu>c)zWdHyG07*qoM6N<$f?{PtRsaA1 literal 0 HcmV?d00001 diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs index 161fa05809..a69380cbb7 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs @@ -8,10 +8,10 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Updates; +using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Net; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; -using MediaBrowser.Model.Globalization; namespace Emby.Server.Implementations.ScheduledTasks { diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index ef346dd5d6..b0a1750bdd 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#nullable enable using System; using System.Collections.Concurrent; @@ -12,7 +12,6 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; -using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; @@ -41,17 +40,15 @@ namespace Emby.Server.Implementations.Updates private readonly IEventManager _eventManager; private readonly IHttpClientFactory _httpClientFactory; private readonly IServerConfigurationManager _config; - private readonly IFileSystem _fileSystem; private readonly JsonSerializerOptions _jsonSerializerOptions; + private readonly IPluginManager _pluginManager; /// <summary> /// Gets the application host. /// </summary> /// <value>The application host.</value> private readonly IServerApplicationHost _applicationHost; - private readonly IZipClient _zipClient; - private readonly object _currentInstallationsLock = new object(); /// <summary> @@ -64,6 +61,17 @@ namespace Emby.Server.Implementations.Updates /// </summary> private readonly ConcurrentBag<InstallationInfo> _completedInstallationsInternal; + /// <summary> + /// Initializes a new instance of the <see cref="InstallationManager"/> class. + /// </summary> + /// <param name="logger">The <see cref="ILogger{InstallationManager}"/>.</param> + /// <param name="appHost">The <see cref="IServerApplicationHost"/>.</param> + /// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param> + /// <param name="eventManager">The <see cref="IEventManager"/>.</param> + /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param> + /// <param name="config">The <see cref="IServerConfigurationManager"/>.</param> + /// <param name="zipClient">The <see cref="IZipClient"/>.</param> + /// <param name="pluginManager">The <see cref="IPluginManager"/>.</param> public InstallationManager( ILogger<InstallationManager> logger, IServerApplicationHost appHost, @@ -71,8 +79,8 @@ namespace Emby.Server.Implementations.Updates IEventManager eventManager, IHttpClientFactory httpClientFactory, IServerConfigurationManager config, - IFileSystem fileSystem, - IZipClient zipClient) + IZipClient zipClient, + IPluginManager pluginManager) { _currentInstallations = new List<(InstallationInfo, CancellationTokenSource)>(); _completedInstallationsInternal = new ConcurrentBag<InstallationInfo>(); @@ -83,16 +91,17 @@ namespace Emby.Server.Implementations.Updates _eventManager = eventManager; _httpClientFactory = httpClientFactory; _config = config; - _fileSystem = fileSystem; _zipClient = zipClient; _jsonSerializerOptions = JsonDefaults.GetOptions(); + _jsonSerializerOptions.PropertyNameCaseInsensitive = true; + _pluginManager = pluginManager; } /// <inheritdoc /> public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal; /// <inheritdoc /> - public async Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, CancellationToken cancellationToken = default) + public async Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default) { try { @@ -103,13 +112,39 @@ namespace Emby.Server.Implementations.Updates return Array.Empty<PackageInfo>(); } + var minimumVersion = new Version(0, 0, 0, 1); // Store the repository and repository url with each version, as they may be spread apart. foreach (var entry in packages) { - foreach (var ver in entry.versions) + for (int a = entry.Versions.Count - 1; a >= 0; a--) { - ver.repositoryName = manifestName; - ver.repositoryUrl = manifest; + var ver = entry.Versions[a]; + ver.RepositoryName = manifestName; + ver.RepositoryUrl = manifest; + + if (!filterIncompatible) + { + continue; + } + + if (!Version.TryParse(ver.TargetAbi, out var targetAbi)) + { + targetAbi = minimumVersion; + } + + if (!Version.TryParse(ver.MaxAbi, out var maxAbi)) + { + maxAbi = _applicationHost.ApplicationVersion; + } + + // Only show plugins that fall between targetAbi and maxAbi + if (_applicationHost.ApplicationVersion >= targetAbi && _applicationHost.ApplicationVersion <= maxAbi) + { + continue; + } + + // Not compatible with this version so remove it. + entry.Versions.Remove(ver); } } @@ -132,69 +167,61 @@ namespace Emby.Server.Implementations.Updates } } - private static void MergeSort(IList<VersionInfo> source, IList<VersionInfo> dest) - { - int sLength = source.Count - 1; - int dLength = dest.Count; - int s = 0, d = 0; - var sourceVersion = source[0].VersionNumber; - var destVersion = dest[0].VersionNumber; - - while (d < dLength) - { - if (sourceVersion.CompareTo(destVersion) >= 0) - { - if (s < sLength) - { - sourceVersion = source[++s].VersionNumber; - } - else - { - // Append all of destination to the end of source. - while (d < dLength) - { - source.Add(dest[d++]); - } - - break; - } - } - else - { - source.Insert(s++, dest[d++]); - if (d >= dLength) - { - break; - } - - sLength++; - destVersion = dest[d].VersionNumber; - } - } - } - /// <inheritdoc /> public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default) { var result = new List<PackageInfo>(); foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories) { - if (repository.Enabled) + if (repository.Enabled && repository.Url != null) { - // Where repositories have the same content, the details of the first is taken. - foreach (var package in await GetPackages(repository.Name, repository.Url, cancellationToken).ConfigureAwait(true)) + // Where repositories have the same content, the details from the first is taken. + foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true)) { - if (!Guid.TryParse(package.guid, out var packageGuid)) + if (!Guid.TryParse(package.Guid, out var packageGuid)) { // Package doesn't have a valid GUID, skip. continue; } - var existing = FilterPackages(result, package.name, packageGuid).FirstOrDefault(); + var existing = FilterPackages(result, package.Name, packageGuid).FirstOrDefault(); + + // Remove invalid versions from the valid package. + for (var i = package.Versions.Count - 1; i >= 0; i--) + { + var version = package.Versions[i]; + + // Update the manifests, if anything changes. + if (_pluginManager.TryGetPlugin(packageGuid, version.VersionNumber, out LocalPlugin? plugin)) + { + bool noChange = string.Equals(plugin!.Manifest.MaxAbi, version.MaxAbi, StringComparison.Ordinal) + || string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal); + if (!noChange) + { + plugin.Manifest.MaxAbi = version.MaxAbi ?? string.Empty; + plugin.Manifest.TargetAbi = version.TargetAbi ?? string.Empty; + _pluginManager.SaveManifest(plugin.Manifest, plugin.Path); + } + } + + // Remove versions with a target abi that is greater then the current application version. + if ((Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi) + || (Version.TryParse(version.MaxAbi, out var maxAbi) && _applicationHost.ApplicationVersion > maxAbi)) + { + package.Versions.RemoveAt(i); + } + } + + // Don't add a package that doesn't have any compatible versions. + if (package.Versions.Count == 0) + { + continue; + } + if (existing != null) { // Assumption is both lists are ordered, so slot these into the correct place. - MergeSort(existing.versions, package.versions); + MergeSortedList(existing.Versions, package.Versions); } else { @@ -210,23 +237,23 @@ namespace Emby.Server.Implementations.Updates /// <inheritdoc /> public IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, - string name = null, - Guid guid = default, - Version specificVersion = null) + string? name = null, + Guid? guid = default, + Version? specificVersion = null) { if (name != null) { - availablePackages = availablePackages.Where(x => x.name.Equals(name, StringComparison.OrdinalIgnoreCase)); + availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } if (guid != Guid.Empty) { - availablePackages = availablePackages.Where(x => Guid.Parse(x.guid) == guid); + availablePackages = availablePackages.Where(x => Guid.Parse(x.Guid) == guid); } if (specificVersion != null) { - availablePackages = availablePackages.Where(x => x.versions.Where(y => y.VersionNumber.Equals(specificVersion)).Any()); + availablePackages = availablePackages.Where(x => x.Versions.Any(y => y.VersionNumber.Equals(specificVersion))); } return availablePackages; @@ -235,10 +262,10 @@ namespace Emby.Server.Implementations.Updates /// <inheritdoc /> public IEnumerable<InstallationInfo> GetCompatibleVersions( IEnumerable<PackageInfo> availablePackages, - string name = null, - Guid guid = default, - Version minVersion = null, - Version specificVersion = null) + string? name = null, + Guid? guid = default, + Version? minVersion = null, + Version? specificVersion = null) { var package = FilterPackages(availablePackages, name, guid, specificVersion).FirstOrDefault(); @@ -249,8 +276,9 @@ namespace Emby.Server.Implementations.Updates } var appVer = _applicationHost.ApplicationVersion; - var availableVersions = package.versions - .Where(x => Version.Parse(x.targetAbi) <= appVer); + var availableVersions = package.Versions + .Where(x => (string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer) + && (string.IsNullOrEmpty(x.MaxAbi) || Version.Parse(x.MaxAbi) >= appVer)); if (specificVersion != null) { @@ -265,12 +293,12 @@ namespace Emby.Server.Implementations.Updates { yield return new InstallationInfo { - Changelog = v.changelog, - Guid = new Guid(package.guid), - Name = package.name, + Changelog = v.Changelog, + Guid = new Guid(package.Guid), + Name = package.Name, Version = v.VersionNumber, - SourceUrl = v.sourceUrl, - Checksum = v.checksum + SourceUrl = v.SourceUrl, + Checksum = v.Checksum }; } } @@ -282,20 +310,6 @@ namespace Emby.Server.Implementations.Updates return GetAvailablePluginUpdates(catalog); } - private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog) - { - var plugins = _applicationHost.GetLocalPlugins(_appPaths.PluginsPath); - foreach (var plugin in plugins) - { - var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version); - var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version); - if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid)) - { - yield return version; - } - } - } - /// <inheritdoc /> public async Task InstallPackage(InstallationInfo package, CancellationToken cancellationToken) { @@ -373,24 +387,140 @@ namespace Emby.Server.Implementations.Updates } /// <summary> - /// Installs the package internal. + /// Uninstalls a plugin. /// </summary> - /// <param name="package">The package.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns><see cref="Task" />.</returns> - private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) + /// <param name="plugin">The <see cref="LocalPlugin"/> to uninstall.</param> + public void UninstallPlugin(LocalPlugin plugin) { - // Set last update time if we were installed before - IPlugin plugin = _applicationHost.Plugins.FirstOrDefault(p => p.Id == package.Guid) - ?? _applicationHost.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase)); + if (plugin == null) + { + return; + } - // Do the install - await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); + if (plugin.Instance?.CanUninstall == false) + { + _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name); + return; + } - // Do plugin-specific processing - _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version); + plugin.Instance?.OnUninstalling(); - return plugin != null; + // Remove it the quick way for now + _pluginManager.RemovePlugin(plugin); + + _eventManager.Publish(new PluginUninstalledEventArgs(plugin.GetPluginInfo())); + + _applicationHost.NotifyPendingRestart(); + } + + /// <inheritdoc/> + public bool CancelInstallation(Guid id) + { + lock (_currentInstallationsLock) + { + var install = _currentInstallations.Find(x => x.info.Guid == id); + if (install == default((InstallationInfo, CancellationTokenSource))) + { + return false; + } + + install.token.Cancel(); + _currentInstallations.Remove(install); + return true; + } + } + + /// <inheritdoc /> + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// <summary> + /// Releases unmanaged and optionally managed resources. + /// </summary> + /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param> + protected virtual void Dispose(bool dispose) + { + if (dispose) + { + lock (_currentInstallationsLock) + { + foreach (var (info, token) in _currentInstallations) + { + token.Dispose(); + } + + _currentInstallations.Clear(); + } + } + } + + /// <summary> + /// Merges two sorted lists. + /// </summary> + /// <param name="source">The source <see cref="IList{VersionInfo}"/> instance to merge.</param> + /// <param name="dest">The destination <see cref="IList{VersionInfo}"/> instance to merge with.</param> + private static void MergeSortedList(IList<VersionInfo> source, IList<VersionInfo> dest) + { + int sLength = source.Count - 1; + int dLength = dest.Count; + int s = 0, d = 0; + var sourceVersion = source[0].VersionNumber; + var destVersion = dest[0].VersionNumber; + + while (d < dLength) + { + if (sourceVersion.CompareTo(destVersion) >= 0) + { + if (s < sLength) + { + sourceVersion = source[++s].VersionNumber; + } + else + { + // Append all of destination to the end of source. + while (d < dLength) + { + source.Add(dest[d++]); + } + + break; + } + } + else + { + source.Insert(s++, dest[d++]); + if (d >= dLength) + { + break; + } + + sLength++; + destVersion = dest[d].VersionNumber; + } + } + } + + private IEnumerable<InstallationInfo> GetAvailablePluginUpdates(IReadOnlyList<PackageInfo> pluginCatalog) + { + var plugins = _pluginManager.Plugins; + foreach (var plugin in plugins) + { + if (plugin.Manifest?.AutoUpdate == false) + { + continue; + } + + var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version); + var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version); + + if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid)) + { + yield return version; + } + } } private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken) @@ -434,7 +564,9 @@ namespace Emby.Server.Implementations.Updates { Directory.Delete(targetDir, true); } +#pragma warning disable CA1031 // Do not catch general exception types catch +#pragma warning restore CA1031 // Do not catch general exception types { // Ignore any exceptions. } @@ -442,119 +574,27 @@ namespace Emby.Server.Implementations.Updates stream.Position = 0; _zipClient.ExtractAllFromZip(stream, targetDir, true); - -#pragma warning restore CA5351 + _pluginManager.ImportPluginFrom(targetDir); } - /// <summary> - /// Uninstalls a plugin. - /// </summary> - /// <param name="plugin">The plugin.</param> - public void UninstallPlugin(IPlugin plugin) + private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) { - if (!plugin.CanUninstall) + // Set last update time if we were installed before + LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Guid) && p.Version.Equals(package.Version)) + ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version)); + if (plugin != null) { - _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name); - return; + plugin.Manifest.Timestamp = DateTime.UtcNow; + _pluginManager.SaveManifest(plugin.Manifest, plugin.Path); } - plugin.OnUninstalling(); + // Do the install + await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); - // Remove it the quick way for now - _applicationHost.RemovePlugin(plugin); + // Do plugin-specific processing + _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version); - var path = plugin.AssemblyFilePath; - bool isDirectory = false; - // Check if we have a plugin directory we should remove too - if (Path.GetDirectoryName(plugin.AssemblyFilePath) != _appPaths.PluginsPath) - { - path = Path.GetDirectoryName(plugin.AssemblyFilePath); - isDirectory = true; - } - - // Make this case-insensitive to account for possible incorrect assembly naming - var file = _fileSystem.GetFilePaths(Path.GetDirectoryName(path)) - .FirstOrDefault(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase)); - - if (!string.IsNullOrWhiteSpace(file)) - { - path = file; - } - - try - { - if (isDirectory) - { - _logger.LogInformation("Deleting plugin directory {0}", path); - Directory.Delete(path, true); - } - else - { - _logger.LogInformation("Deleting plugin file {0}", path); - _fileSystem.DeleteFile(path); - } - } - catch - { - // Ignore file errors. - } - - var list = _config.Configuration.UninstalledPlugins.ToList(); - var filename = Path.GetFileName(path); - if (!list.Contains(filename, StringComparer.OrdinalIgnoreCase)) - { - list.Add(filename); - _config.Configuration.UninstalledPlugins = list.ToArray(); - _config.SaveConfiguration(); - } - - _eventManager.Publish(new PluginUninstalledEventArgs(plugin)); - - _applicationHost.NotifyPendingRestart(); - } - - /// <inheritdoc/> - public bool CancelInstallation(Guid id) - { - lock (_currentInstallationsLock) - { - var install = _currentInstallations.Find(x => x.info.Guid == id); - if (install == default((InstallationInfo, CancellationTokenSource))) - { - return false; - } - - install.token.Cancel(); - _currentInstallations.Remove(install); - return true; - } - } - - /// <inheritdoc /> - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// <summary> - /// Releases unmanaged and optionally managed resources. - /// </summary> - /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources or <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - lock (_currentInstallationsLock) - { - foreach (var tuple in _currentInstallations) - { - tuple.token.Dispose(); - } - - _currentInstallations.Clear(); - } - } + return plugin != null; } } } diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index ccc81dfc55..b77d79209a 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -29,18 +29,22 @@ namespace Jellyfin.Api.Controllers { private readonly ILogger<DashboardController> _logger; private readonly IServerApplicationHost _appHost; + private readonly IPluginManager _pluginManager; /// <summary> /// Initializes a new instance of the <see cref="DashboardController"/> class. /// </summary> /// <param name="logger">Instance of <see cref="ILogger{DashboardController}"/> interface.</param> /// <param name="appHost">Instance of <see cref="IServerApplicationHost"/> interface.</param> + /// <param name="pluginManager">Instance of <see cref="IPluginManager"/> interface.</param> public DashboardController( ILogger<DashboardController> logger, - IServerApplicationHost appHost) + IServerApplicationHost appHost, + IPluginManager pluginManager) { _logger = logger; _appHost = appHost; + _pluginManager = pluginManager; } /// <summary> @@ -83,7 +87,7 @@ namespace Jellyfin.Api.Controllers .Where(i => i != null) .ToList(); - configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages)); + configPages.AddRange(_pluginManager.Plugins.SelectMany(GetConfigPages)); if (pageType.HasValue) { @@ -155,24 +159,24 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin) + private IEnumerable<ConfigurationPageInfo> GetConfigPages(LocalPlugin plugin) { - return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1)); + return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin.Instance, i.Item1)); } - private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin) + private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(LocalPlugin? plugin) { - if (!(plugin is IHasWebPages hasWebPages)) + if (plugin?.Instance is not IHasWebPages hasWebPages) { return new List<Tuple<PluginPageInfo, IPlugin>>(); } - return hasWebPages.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin)); + return hasWebPages.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin.Instance)); } private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages() { - return _appHost.Plugins.SelectMany(GetPluginPages); + return _pluginManager.Plugins.SelectMany(GetPluginPages); } } } diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 6295dfc05d..622a0fe00d 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -2,8 +2,11 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Net.Mime; using System.Threading.Tasks; +using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Updates; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Updates; @@ -43,6 +46,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="PackageInfo"/> containing package information.</returns> [HttpGet("Packages/{name}")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<ActionResult<PackageInfo>> GetPackageInfo( [FromRoute, Required] string name, [FromQuery] Guid? assemblyGuid) @@ -69,6 +73,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="PackageInfo"/> containing available packages information.</returns> [HttpGet("Packages")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<IEnumerable<PackageInfo>> GetPackages() { IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); @@ -99,7 +104,7 @@ namespace Jellyfin.Api.Controllers var packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); if (!string.IsNullOrEmpty(repositoryUrl)) { - packages = packages.Where(p => p.versions.Where(q => q.repositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase)).Any()) + packages = packages.Where(p => p.Versions.Any(q => q.RepositoryUrl.Equals(repositoryUrl, StringComparison.OrdinalIgnoreCase))) .ToList(); } @@ -143,6 +148,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="OkResult"/> containing the list of package repositories.</returns> [HttpGet("Repositories")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public ActionResult<IEnumerable<RepositoryInfo>> GetRepositories() { return _serverConfigurationManager.Configuration.PluginRepositories; diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 98f1bc2d23..3f366dd79f 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -1,15 +1,22 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Globalization; +using System.IO; using System.Linq; +using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; +using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Models.PluginDtos; -using MediaBrowser.Common; +using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Net; using MediaBrowser.Model.Plugins; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -23,112 +30,26 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] public class PluginsController : BaseJellyfinApiController { - private readonly IApplicationHost _appHost; private readonly IInstallationManager _installationManager; - - private readonly JsonSerializerOptions _serializerOptions = JsonDefaults.GetOptions(); + private readonly IPluginManager _pluginManager; + private readonly IConfigurationManager _config; + private readonly JsonSerializerOptions _serializerOptions; /// <summary> /// Initializes a new instance of the <see cref="PluginsController"/> class. /// </summary> - /// <param name="appHost">Instance of the <see cref="IApplicationHost"/> interface.</param> /// <param name="installationManager">Instance of the <see cref="IInstallationManager"/> interface.</param> + /// <param name="pluginManager">Instance of the <see cref="IPluginManager"/> interface.</param> + /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param> public PluginsController( - IApplicationHost appHost, - IInstallationManager installationManager) + IInstallationManager installationManager, + IPluginManager pluginManager, + IConfigurationManager config) { - _appHost = appHost; _installationManager = installationManager; - } - - /// <summary> - /// Gets a list of currently installed plugins. - /// </summary> - /// <response code="200">Installed plugins returned.</response> - /// <returns>List of currently installed plugins.</returns> - [HttpGet] - [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<IEnumerable<PluginInfo>> GetPlugins() - { - return Ok(_appHost.Plugins.OrderBy(p => p.Name).Select(p => p.GetPluginInfo())); - } - - /// <summary> - /// Uninstalls a plugin. - /// </summary> - /// <param name="pluginId">Plugin id.</param> - /// <response code="204">Plugin uninstalled.</response> - /// <response code="404">Plugin not found.</response> - /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> - [HttpDelete("{pluginId}")] - [Authorize(Policy = Policies.RequiresElevation)] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId) - { - var plugin = _appHost.Plugins.FirstOrDefault(p => p.Id == pluginId); - if (plugin == null) - { - return NotFound(); - } - - _installationManager.UninstallPlugin(plugin); - return NoContent(); - } - - /// <summary> - /// Gets plugin configuration. - /// </summary> - /// <param name="pluginId">Plugin id.</param> - /// <response code="200">Plugin configuration returned.</response> - /// <response code="404">Plugin not found or plugin configuration not found.</response> - /// <returns>Plugin configuration.</returns> - [HttpGet("{pluginId}/Configuration")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId) - { - if (!(_appHost.Plugins.FirstOrDefault(p => p.Id == pluginId) is IHasPluginConfiguration plugin)) - { - return NotFound(); - } - - return plugin.Configuration; - } - - /// <summary> - /// Updates plugin configuration. - /// </summary> - /// <remarks> - /// Accepts plugin configuration as JSON body. - /// </remarks> - /// <param name="pluginId">Plugin id.</param> - /// <response code="204">Plugin configuration updated.</response> - /// <response code="404">Plugin not found or plugin does not have configuration.</response> - /// <returns> - /// A <see cref="Task" /> that represents the asynchronous operation to update plugin configuration. - /// The task result contains an <see cref="NoContentResult"/> indicating success, or <see cref="NotFoundResult"/> - /// when plugin not found or plugin doesn't have configuration. - /// </returns> - [HttpPost("{pluginId}/Configuration")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId) - { - if (!(_appHost.Plugins.FirstOrDefault(p => p.Id == pluginId) is IHasPluginConfiguration plugin)) - { - return NotFound(); - } - - var configuration = (BasePluginConfiguration?)await JsonSerializer.DeserializeAsync(Request.Body, plugin.ConfigurationType, _serializerOptions) - .ConfigureAwait(false); - - if (configuration != null) - { - plugin.UpdateConfiguration(configuration); - } - - return NoContent(); + _pluginManager = pluginManager; + _serializerOptions = JsonDefaults.GetOptions(); + _config = config; } /// <summary> @@ -139,7 +60,7 @@ namespace Jellyfin.Api.Controllers [Obsolete("This endpoint should not be used.")] [HttpGet("SecurityInfo")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<PluginSecurityInfo> GetPluginSecurityInfo() + public static ActionResult<PluginSecurityInfo> GetPluginSecurityInfo() { return new PluginSecurityInfo { @@ -148,21 +69,6 @@ namespace Jellyfin.Api.Controllers }; } - /// <summary> - /// Updates plugin security info. - /// </summary> - /// <param name="pluginSecurityInfo">Plugin security info.</param> - /// <response code="204">Plugin security info updated.</response> - /// <returns>An <see cref="NoContentResult"/>.</returns> - [Obsolete("This endpoint should not be used.")] - [HttpPost("SecurityInfo")] - [Authorize(Policy = Policies.RequiresElevation)] - [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult UpdatePluginSecurityInfo([FromBody, Required] PluginSecurityInfo pluginSecurityInfo) - { - return NoContent(); - } - /// <summary> /// Gets registration status for a feature. /// </summary> @@ -172,7 +78,7 @@ namespace Jellyfin.Api.Controllers [Obsolete("This endpoint should not be used.")] [HttpPost("RegistrationRecords/{name}")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<MBRegistrationRecord> GetRegistrationStatus([FromRoute, Required] string name) + public static ActionResult<MBRegistrationRecord> GetRegistrationStatus([FromRoute, Required] string name) { return new MBRegistrationRecord { @@ -194,11 +100,257 @@ namespace Jellyfin.Api.Controllers [Obsolete("Paid plugins are not supported")] [HttpGet("Registrations/{name}")] [ProducesResponseType(StatusCodes.Status501NotImplemented)] - public ActionResult GetRegistration([FromRoute, Required] string name) + public static ActionResult GetRegistration([FromRoute, Required] string name) { // TODO Once we have proper apps and plugins and decide to break compatibility with paid plugins, // delete all these registration endpoints. They are only kept for compatibility. throw new NotImplementedException(); } + + /// <summary> + /// Gets a list of currently installed plugins. + /// </summary> + /// <response code="200">Installed plugins returned.</response> + /// <returns>List of currently installed plugins.</returns> + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesFile(MediaTypeNames.Application.Json)] + public ActionResult<IEnumerable<PluginInfo>> GetPlugins() + { + return Ok(_pluginManager.Plugins + .OrderBy(p => p.Name) + .Select(p => p.GetPluginInfo())); + } + + /// <summary> + /// Enables a disabled plugin. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="204">Plugin enabled.</response> + /// <response code="404">Plugin not found.</response> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + [HttpPost("{pluginId}/Enable")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public ActionResult EnablePlugin([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return NotFound(); + } + + _pluginManager.EnablePlugin(plugin!); + return NoContent(); + } + + /// <summary> + /// Disable a plugin. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="204">Plugin disabled.</response> + /// <response code="404">Plugin not found.</response> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + [HttpPost("{pluginId}/Disable")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public ActionResult DisablePlugin([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return NotFound(); + } + + _pluginManager.DisablePlugin(plugin!); + return NoContent(); + } + + /// <summary> + /// Uninstalls a plugin. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="204">Plugin uninstalled.</response> + /// <response code="404">Plugin not found.</response> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + [HttpDelete("{pluginId}")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId, Version version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return NotFound(); + } + + _installationManager.UninstallPlugin(plugin!); + return NoContent(); + } + + /// <summary> + /// Gets plugin configuration. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="200">Plugin configuration returned.</response> + /// <response code="404">Plugin not found or plugin configuration not found.</response> + /// <returns>Plugin configuration.</returns> + [HttpGet("{pluginId}/Configuration")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesFile(MediaTypeNames.Application.Json)] + public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (_pluginManager.TryGetPlugin(pluginId, version, out var plugin) + && plugin!.Instance is IHasPluginConfiguration configPlugin) + { + return configPlugin.Configuration; + } + + return NotFound(); + } + + /// <summary> + /// Updates plugin configuration. + /// </summary> + /// <remarks> + /// Accepts plugin configuration as JSON body. + /// </remarks> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="204">Plugin configuration updated.</response> + /// <response code="404">Plugin not found or plugin does not have configuration.</response> + /// <returns> + /// A <see cref="Task" /> that represents the asynchronous operation to update plugin configuration. + /// The task result contains an <see cref="NoContentResult"/> indicating success, or <see cref="NotFoundResult"/> + /// when plugin not found or plugin doesn't have configuration. + /// </returns> + [HttpPost("{pluginId}/Configuration")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin) + || plugin?.Instance is not IHasPluginConfiguration configPlugin) + { + return NotFound(); + } + + var configuration = (BasePluginConfiguration?)await JsonSerializer.DeserializeAsync(Request.Body, configPlugin.ConfigurationType, _serializerOptions) + .ConfigureAwait(false); + + if (configuration != null) + { + configPlugin.UpdateConfiguration(configuration); + } + + return NoContent(); + } + + /// <summary> + /// Gets a plugin's image. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="200">Plugin image returned.</response> + /// <returns>Plugin's image.</returns> + [HttpGet("{pluginId}/Image")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + [AllowAnonymous] + public ActionResult GetPluginImage([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return NotFound(); + } + + var imgPath = Path.Combine(plugin!.Path, plugin!.Manifest.ImageUrl ?? string.Empty); + if (((ServerConfiguration)_config.CommonConfiguration).DisablePluginImages + || plugin!.Manifest.ImageUrl == null + || !System.IO.File.Exists(imgPath)) + { + // Use a blank image. + var type = GetType(); + var stream = type.Assembly.GetManifestResourceStream(type.Namespace + ".Plugins.blank.png"); + return File(stream, "image/png"); + } + + imgPath = Path.Combine(plugin.Path, plugin.Manifest.ImageUrl); + return PhysicalFile(imgPath, MimeTypes.GetMimeType(imgPath)); + } + + /// <summary> + /// Gets a plugin's status image. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="200">Plugin image returned.</response> + /// <returns>Plugin's image.</returns> + [HttpGet("{pluginId}/StatusImage")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesImageFile] + [AllowAnonymous] + public ActionResult GetPluginStatusImage([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return NotFound(); + } + + // Icons from http://www.fatcow.com/free-icons + var status = plugin!.Manifest.Status; + + var type = _pluginManager.GetType(); + var stream = type.Assembly.GetManifestResourceStream($"{type.Namespace}.Plugins.{status}.png"); + return File(stream, "image/png"); + } + + /// <summary> + /// Gets a plugin's manifest. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <param name="version">Plugin version.</param> + /// <response code="204">Plugin manifest returned.</response> + /// <response code="404">Plugin not found.</response> + /// <returns> + /// A <see cref="Task" /> that represents the asynchronous operation to get the plugin's manifest. + /// The task result contains an <see cref="NoContentResult"/> indicating success, or <see cref="NotFoundResult"/> + /// when plugin not found. + /// </returns> + [HttpPost("{pluginId}/Manifest")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesFile(MediaTypeNames.Application.Json)] + public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + { + if (_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + { + return Ok(plugin!.Manifest); + } + + return NotFound(); + } + + /// <summary> + /// Updates plugin security info. + /// </summary> + /// <param name="pluginSecurityInfo">Plugin security info.</param> + /// <response code="204">Plugin security info updated.</response> + /// <returns>An <see cref="NoContentResult"/>.</returns> + [Obsolete("This endpoint should not be used.")] + [HttpPost("SecurityInfo")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult UpdatePluginSecurityInfo([FromBody, Required] PluginSecurityInfo pluginSecurityInfo) + { + return NoContent(); + } } } diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index 2aa6373aa9..155e116a56 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Common.Plugins; +using MediaBrowser.Common.Plugins; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Plugins; @@ -32,16 +32,16 @@ namespace Jellyfin.Api.Models /// </summary> /// <param name="plugin">Instance of <see cref="IPlugin"/> interface.</param> /// <param name="page">Instance of <see cref="PluginPageInfo"/> interface.</param> - public ConfigurationPageInfo(IPlugin plugin, PluginPageInfo page) + public ConfigurationPageInfo(IPlugin? plugin, PluginPageInfo page) { Name = page.Name; EnableInMainMenu = page.EnableInMainMenu; MenuSection = page.MenuSection; MenuIcon = page.MenuIcon; - DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin.Name : page.DisplayName; + DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin?.Name ?? page.DisplayName : page.DisplayName; // Don't use "N" because it needs to match Plugin.Id - PluginId = plugin.Id.ToString(); + PluginId = plugin?.Id.ToString(); } /// <summary> diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index 849037ac46..ddcf2ac171 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -2,11 +2,16 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; -using MediaBrowser.Common.Plugins; -using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common { + /// <summary> + /// Delegate used with GetExports{T}. + /// </summary> + /// <param name="type">Type to create.</param> + /// <returns>New instance of type <param>type</param>.</returns> + public delegate object CreationDelegate(Type type); + /// <summary> /// An interface to be implemented by the applications hosting a kernel. /// </summary> @@ -53,6 +58,11 @@ namespace MediaBrowser.Common /// <value>The application version.</value> Version ApplicationVersion { get; } + /// <summary> + /// Gets or sets the service provider. + /// </summary> + IServiceProvider ServiceProvider { get; set; } + /// <summary> /// Gets the application version. /// </summary> @@ -71,12 +81,6 @@ namespace MediaBrowser.Common /// </summary> string ApplicationUserAgentAddress { get; } - /// <summary> - /// Gets the plugins. - /// </summary> - /// <value>The plugins.</value> - IReadOnlyList<IPlugin> Plugins { get; } - /// <summary> /// Gets all plugin assemblies which implement a custom rest api. /// </summary> @@ -101,6 +105,22 @@ namespace MediaBrowser.Common /// <returns><see cref="IReadOnlyCollection{T}" />.</returns> IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true); + /// <summary> + /// Gets the exports. + /// </summary> + /// <typeparam name="T">The type.</typeparam> + /// <param name="defaultFunc">Delegate function that gets called to create the object.</param> + /// <param name="manageLifetime">If set to <c>true</c> [manage lifetime].</param> + /// <returns><see cref="IReadOnlyCollection{T}" />.</returns> + IReadOnlyCollection<T> GetExports<T>(CreationDelegate defaultFunc, bool manageLifetime = true); + + /// <summary> + /// Gets the export types. + /// </summary> + /// <typeparam name="T">The type.</typeparam> + /// <returns>IEnumerable{Type}.</returns> + IEnumerable<Type> GetExportTypes<T>(); + /// <summary> /// Resolves this instance. /// </summary> @@ -114,12 +134,6 @@ namespace MediaBrowser.Common /// <returns>A task.</returns> Task Shutdown(); - /// <summary> - /// Removes the plugin. - /// </summary> - /// <param name="plugin">The plugin.</param> - void RemovePlugin(IPlugin plugin); - /// <summary> /// Initializes this instance. /// </summary> diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 084e91d500..b918fc4f6d 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -7,7 +7,6 @@ using System.Runtime.InteropServices; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; -using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common.Plugins { @@ -64,14 +63,12 @@ namespace MediaBrowser.Common.Plugins /// <returns>PluginInfo.</returns> public virtual PluginInfo GetPluginInfo() { - var info = new PluginInfo - { - Name = Name, - Version = Version.ToString(), - Description = Description, - Id = Id.ToString(), - CanUninstall = CanUninstall - }; + var info = new PluginInfo( + Name, + Version, + Description, + Id, + CanUninstall); return info; } diff --git a/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs new file mode 100644 index 0000000000..42ad85dd37 --- /dev/null +++ b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs @@ -0,0 +1,33 @@ +using System; +using MediaBrowser.Model.Plugins; + +namespace MediaBrowser.Common.Plugins +{ + /// <summary> + /// Defines the <see cref="IHasPluginConfiguration" />. + /// </summary> + public interface IHasPluginConfiguration + { + /// <summary> + /// Gets the type of configuration this plugin uses. + /// </summary> + Type ConfigurationType { get; } + + /// <summary> + /// Gets the plugin's configuration. + /// </summary> + BasePluginConfiguration Configuration { get; } + + /// <summary> + /// Completely overwrites the current configuration with a new copy. + /// </summary> + /// <param name="configuration">The configuration.</param> + void UpdateConfiguration(BasePluginConfiguration configuration); + + /// <summary> + /// Sets the startup directory creation function. + /// </summary> + /// <param name="directoryCreateFn">The directory function used to create the configuration folder.</param> + void SetStartupInfo(Action<string> directoryCreateFn); + } +} diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs index d583a58878..b2ba1179c1 100644 --- a/MediaBrowser.Common/Plugins/IPlugin.cs +++ b/MediaBrowser.Common/Plugins/IPlugin.cs @@ -1,44 +1,36 @@ -#pragma warning disable CS1591 - using System; using MediaBrowser.Model.Plugins; -using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common.Plugins { /// <summary> - /// Interface IPlugin. + /// Defines the <see cref="IPlugin" />. /// </summary> public interface IPlugin { /// <summary> /// Gets the name of the plugin. /// </summary> - /// <value>The name.</value> string Name { get; } /// <summary> - /// Gets the description. + /// Gets the Description. /// </summary> - /// <value>The description.</value> string Description { get; } /// <summary> /// Gets the unique id. /// </summary> - /// <value>The unique id.</value> Guid Id { get; } /// <summary> /// Gets the plugin version. /// </summary> - /// <value>The version.</value> Version Version { get; } /// <summary> /// Gets the path to the assembly file. /// </summary> - /// <value>The assembly file path.</value> string AssemblyFilePath { get; } /// <summary> @@ -49,11 +41,10 @@ namespace MediaBrowser.Common.Plugins /// <summary> /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed. /// </summary> - /// <value>The data folder path.</value> string DataFolderPath { get; } /// <summary> - /// Gets the plugin info. + /// Gets the <see cref="PluginInfo"/>. /// </summary> /// <returns>PluginInfo.</returns> PluginInfo GetPluginInfo(); @@ -63,29 +54,4 @@ namespace MediaBrowser.Common.Plugins /// </summary> void OnUninstalling(); } - - public interface IHasPluginConfiguration - { - /// <summary> - /// Gets the type of configuration this plugin uses. - /// </summary> - /// <value>The type of the configuration.</value> - Type ConfigurationType { get; } - - /// <summary> - /// Gets the plugin's configuration. - /// </summary> - /// <value>The configuration.</value> - BasePluginConfiguration Configuration { get; } - - /// <summary> - /// Completely overwrites the current configuration with a new copy - /// Returns true or false indicating success or failure. - /// </summary> - /// <param name="configuration">The configuration.</param> - /// <exception cref="ArgumentNullException"><c>configuration</c> is <c>null</c>.</exception> - void UpdateConfiguration(BasePluginConfiguration configuration); - - void SetStartupInfo(Action<string> directoryCreateFn); - } } diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs new file mode 100644 index 0000000000..071b51969f --- /dev/null +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -0,0 +1,86 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; + +namespace MediaBrowser.Common.Plugins +{ + /// <summary> + /// Defines the <see cref="IPluginManager" />. + /// </summary> + public interface IPluginManager + { + /// <summary> + /// Gets the Plugins. + /// </summary> + IList<LocalPlugin> Plugins { get; } + + /// <summary> + /// Creates the plugins. + /// </summary> + void CreatePlugins(); + + /// <summary> + /// Returns all the assemblies. + /// </summary> + /// <returns>An IEnumerable{Assembly}.</returns> + IEnumerable<Assembly> LoadAssemblies(); + + /// <summary> + /// Registers the plugin's services with the DI. + /// Note: DI is not yet instantiated yet. + /// </summary> + /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param> + void RegisterServices(IServiceCollection serviceCollection); + + /// <summary> + /// Saves the manifest back to disk. + /// </summary> + /// <param name="manifest">The <see cref="PluginManifest"/> to save.</param> + /// <param name="path">The path where to save the manifest.</param> + /// <returns>True if successful.</returns> + bool SaveManifest(PluginManifest manifest, string path); + + /// <summary> + /// Imports plugin details from a folder. + /// </summary> + /// <param name="folder">Folder of the plugin.</param> + void ImportPluginFrom(string folder); + + /// <summary> + /// Disable the plugin. + /// </summary> + /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param> + void FailPlugin(Assembly assembly); + + /// <summary> + /// Disable the plugin. + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param> + void DisablePlugin(LocalPlugin plugin); + + /// <summary> + /// Enables the plugin, disabling all other versions. + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param> + void EnablePlugin(LocalPlugin plugin); + + /// <summary> + /// Attempts to find the plugin with and id of <paramref name="id"/>. + /// </summary> + /// <param name="id">Id of plugin.</param> + /// <param name="version">The version of the plugin to locate.</param> + /// <param name="plugin">A <see cref="LocalPlugin"/> if found, otherwise null.</param> + /// <returns>Boolean value signifying the success of the search.</returns> + bool TryGetPlugin(Guid id, Version? version, out LocalPlugin? plugin); + + /// <summary> + /// Removes the plugin. + /// </summary> + /// <param name="plugin">The plugin.</param> + /// <returns>Outcome of the operation.</returns> + bool RemovePlugin(LocalPlugin plugin); + } +} diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index c97e75a3b2..ef9ab7a7dc 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -1,6 +1,9 @@ +#nullable enable using System; using System.Collections.Generic; using System.Globalization; +using System.Reflection; +using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins { @@ -9,36 +12,48 @@ namespace MediaBrowser.Common.Plugins /// </summary> public class LocalPlugin : IEquatable<LocalPlugin> { + private readonly bool _supported; + private Version? _version; + /// <summary> /// Initializes a new instance of the <see cref="LocalPlugin"/> class. /// </summary> - /// <param name="id">The plugin id.</param> - /// <param name="name">The plugin name.</param> - /// <param name="version">The plugin version.</param> /// <param name="path">The plugin path.</param> - public LocalPlugin(Guid id, string name, Version version, string path) + /// <param name="isSupported"><b>True</b> if Jellyfin supports this version of the plugin.</param> + /// <param name="manifest">The manifest record for this plugin, or null if one does not exist.</param> + public LocalPlugin(string path, bool isSupported, PluginManifest manifest) { - Id = id; - Name = name; - Version = version; Path = path; DllFiles = new List<string>(); + _supported = isSupported; + Manifest = manifest; } /// <summary> /// Gets the plugin id. /// </summary> - public Guid Id { get; } + public Guid Id => Manifest.Guid; /// <summary> /// Gets the plugin name. /// </summary> - public string Name { get; } + public string Name => Manifest.Name; /// <summary> /// Gets the plugin version. /// </summary> - public Version Version { get; } + public Version Version + { + get + { + if (_version == null) + { + _version = Version.Parse(Manifest.Version); + } + + return _version; + } + } /// <summary> /// Gets the plugin path. @@ -51,26 +66,24 @@ namespace MediaBrowser.Common.Plugins public List<string> DllFiles { get; } /// <summary> - /// == operator. + /// Gets or sets the instance of this plugin. /// </summary> - /// <param name="left">Left item.</param> - /// <param name="right">Right item.</param> - /// <returns>Comparison result.</returns> - public static bool operator ==(LocalPlugin left, LocalPlugin right) - { - return left.Equals(right); - } + public IPlugin? Instance { get; set; } /// <summary> - /// != operator. + /// Gets a value indicating whether Jellyfin supports this version of the plugin, and it's enabled. /// </summary> - /// <param name="left">Left item.</param> - /// <param name="right">Right item.</param> - /// <returns>Comparison result.</returns> - public static bool operator !=(LocalPlugin left, LocalPlugin right) - { - return !left.Equals(right); - } + public bool IsEnabledAndSupported => _supported && Manifest.Status >= PluginStatus.Active; + + /// <summary> + /// Gets a value indicating whether the plugin has a manifest. + /// </summary> + public PluginManifest Manifest { get; } + + /// <summary> + /// Gets or sets a value indicating the assembly of the plugin. + /// </summary> + public Assembly? Assembly { get; set; } /// <summary> /// Compare two <see cref="LocalPlugin"/>. @@ -80,10 +93,15 @@ namespace MediaBrowser.Common.Plugins /// <returns>Comparison result.</returns> public static int Compare(LocalPlugin a, LocalPlugin b) { + if (a == null || b == null) + { + throw new ArgumentNullException(a == null ? nameof(a) : nameof(b)); + } + var compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture); // Id is not equal but name is. - if (a.Id != b.Id && compare == 0) + if (!a.Id.Equals(b.Id) && compare == 0) { compare = a.Id.CompareTo(b.Id); } @@ -91,8 +109,20 @@ namespace MediaBrowser.Common.Plugins return compare == 0 ? a.Version.CompareTo(b.Version) : compare; } + /// <summary> + /// Returns the plugin information. + /// </summary> + /// <returns>A <see cref="PluginInfo"/> instance containing the information.</returns> + public PluginInfo GetPluginInfo() + { + var inst = Instance?.GetPluginInfo() ?? new PluginInfo(Manifest.Name, Version, Manifest.Description, Manifest.Guid, true); + inst.Status = Manifest.Status; + inst.HasImage = !string.IsNullOrEmpty(Manifest.ImageUrl); + return inst; + } + /// <inheritdoc /> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is LocalPlugin other && this.Equals(other); } @@ -104,16 +134,14 @@ namespace MediaBrowser.Common.Plugins } /// <inheritdoc /> - public bool Equals(LocalPlugin other) + public bool Equals(LocalPlugin? other) { - // Do not use == or != for comparison as this class overrides the operators. - if (object.ReferenceEquals(other, null)) + if (other == null) { return false; } - return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) - && Id.Equals(other.Id); + return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && Id.Equals(other.Id) && Version.Equals(other.Version); } } } diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs new file mode 100644 index 0000000000..b88275718a --- /dev/null +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -0,0 +1,85 @@ +#nullable enable +using System; +using MediaBrowser.Model.Plugins; + +namespace MediaBrowser.Common.Plugins +{ + /// <summary> + /// Defines a Plugin manifest file. + /// </summary> + public class PluginManifest + { + /// <summary> + /// Gets or sets the category of the plugin. + /// </summary> + public string Category { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the changelog information. + /// </summary> + public string Changelog { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the description of the plugin. + /// </summary> + public string Description { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the Global Unique Identifier for the plugin. + /// </summary> +#pragma warning disable CA1720 // Identifier contains type name + public Guid Guid { get; set; } +#pragma warning restore CA1720 // Identifier contains type name + + /// <summary> + /// Gets or sets the Name of the plugin. + /// </summary> + public string Name { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets an overview of the plugin. + /// </summary> + public string Overview { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the owner of the plugin. + /// </summary> + public string Owner { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the compatibility version for the plugin. + /// </summary> + public string TargetAbi { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the upper compatibility version for the plugin. + /// </summary> + public string MaxAbi { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the timestamp of the plugin. + /// </summary> + public DateTime Timestamp { get; set; } + + /// <summary> + /// Gets or sets the Version number of the plugin. + /// </summary> + public string Version { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets a value indicating whether this plugin should be ignored. + /// </summary> + public PluginStatus Status { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether this plugin should automatically update. + /// </summary> + public bool AutoUpdate { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether this plugin has an image. + /// Image must be located in the local plugin folder. + /// </summary> + public string? ImageUrl { get; set; } + } +} diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 585b1ee19e..dd9e0cc3f9 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#nullable enable using System; using System.Collections.Generic; @@ -9,6 +9,9 @@ using MediaBrowser.Model.Updates; namespace MediaBrowser.Common.Updates { + /// <summary> + /// Defines the <see cref="IInstallationManager" />. + /// </summary> public interface IInstallationManager : IDisposable { /// <summary> @@ -21,12 +24,13 @@ namespace MediaBrowser.Common.Updates /// </summary> /// <param name="manifestName">Name of the repository.</param> /// <param name="manifest">The URL to query.</param> + /// <param name="filterIncompatible">Filter out incompatible plugins.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task{IReadOnlyList{PackageInfo}}.</returns> - Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, CancellationToken cancellationToken = default); + Task<IList<PackageInfo>> GetPackages(string manifestName, string manifest, bool filterIncompatible, CancellationToken cancellationToken = default); /// <summary> - /// Gets all available packages. + /// Gets all available packages that are supported by this version. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Task{IReadOnlyList{PackageInfo}}.</returns> @@ -42,9 +46,11 @@ namespace MediaBrowser.Common.Updates /// <returns>All plugins matching the requirements.</returns> IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, - string name = null, - Guid guid = default, - Version specificVersion = null); + string? name = null, +#pragma warning disable CA1720 // Identifier contains type name + Guid? guid = default, +#pragma warning restore CA1720 // Identifier contains type name + Version? specificVersion = null); /// <summary> /// Returns all compatible versions ordered from newest to oldest. @@ -57,13 +63,15 @@ namespace MediaBrowser.Common.Updates /// <returns>All compatible versions ordered from newest to oldest.</returns> IEnumerable<InstallationInfo> GetCompatibleVersions( IEnumerable<PackageInfo> availablePackages, - string name = null, - Guid guid = default, - Version minVersion = null, - Version specificVersion = null); + string? name = null, +#pragma warning disable CA1720 // Identifier contains type name + Guid? guid = default, +#pragma warning restore CA1720 // Identifier contains type name + Version? minVersion = null, + Version? specificVersion = null); /// <summary> - /// Returns the available plugin updates. + /// Returns the available compatible plugin updates. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The available plugin updates.</returns> @@ -81,7 +89,7 @@ namespace MediaBrowser.Common.Updates /// Uninstalls a plugin. /// </summary> /// <param name="plugin">The plugin.</param> - void UninstallPlugin(IPlugin plugin); + void UninstallPlugin(LocalPlugin plugin); /// <summary> /// Cancels the installation. diff --git a/MediaBrowser.Common/Updates/InstallationEventArgs.cs b/MediaBrowser.Common/Updates/InstallationEventArgs.cs index 61178f631c..adf336313f 100644 --- a/MediaBrowser.Common/Updates/InstallationEventArgs.cs +++ b/MediaBrowser.Common/Updates/InstallationEventArgs.cs @@ -1,14 +1,21 @@ -#pragma warning disable CS1591 - using System; using MediaBrowser.Model.Updates; namespace MediaBrowser.Common.Updates { + /// <summary> + /// Defines the <see cref="InstallationEventArgs" />. + /// </summary> public class InstallationEventArgs : EventArgs { + /// <summary> + /// Gets or sets the <see cref="InstallationInfo"/>. + /// </summary> public InstallationInfo InstallationInfo { get; set; } + /// <summary> + /// Gets or sets the <see cref="VersionInfo"/>. + /// </summary> public VersionInfo VersionInfo { get; set; } } } diff --git a/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs index 7510b62b88..a111e6d829 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs @@ -1,18 +1,19 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; namespace MediaBrowser.Controller.Events.Updates { /// <summary> /// An event that occurs when a plugin is uninstalled. /// </summary> - public class PluginUninstalledEventArgs : GenericEventArgs<IPlugin> + public class PluginUninstalledEventArgs : GenericEventArgs<PluginInfo> { /// <summary> /// Initializes a new instance of the <see cref="PluginUninstalledEventArgs"/> class. /// </summary> /// <param name="arg">The plugin.</param> - public PluginUninstalledEventArgs(IPlugin arg) : base(arg) + public PluginUninstalledEventArgs(PluginInfo arg) : base(arg) { } } diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 2456da826f..92b2d43ce2 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -19,8 +19,6 @@ namespace MediaBrowser.Controller { event EventHandler HasUpdateAvailableChanged; - IServiceProvider ServiceProvider { get; } - bool CoreStartupHasCompleted { get; } bool CanLaunchWebBrowser { get; } @@ -122,13 +120,5 @@ namespace MediaBrowser.Controller string ExpandVirtualPath(string path); string ReverseVirtualPath(string path); - - /// <summary> - /// Gets the list of local plugins. - /// </summary> - /// <param name="path">Plugin base directory.</param> - /// <param name="cleanup">Cleanup old plugins.</param> - /// <returns>Enumerable of local plugins.</returns> - IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true); } } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 0dbd51bdc1..de3d3b6ff1 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -449,5 +449,15 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets the how many metadata refreshes can run concurrently. /// </summary> public int LibraryMetadataRefreshConcurrency { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether older plugins should automatically be deleted from the plugin folder. + /// </summary> + public bool RemoveOldPlugins { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether plugin image should be disabled. + /// </summary> + public bool DisablePluginImages { get; set; } } } diff --git a/MediaBrowser.Model/Plugins/PluginInfo.cs b/MediaBrowser.Model/Plugins/PluginInfo.cs index dd215192f9..52c99b9c3e 100644 --- a/MediaBrowser.Model/Plugins/PluginInfo.cs +++ b/MediaBrowser.Model/Plugins/PluginInfo.cs @@ -1,4 +1,7 @@ -#nullable disable +#nullable enable + +using System; + namespace MediaBrowser.Model.Plugins { /// <summary> @@ -6,34 +9,46 @@ namespace MediaBrowser.Model.Plugins /// </summary> public class PluginInfo { + /// <summary> + /// Initializes a new instance of the <see cref="PluginInfo"/> class. + /// </summary> + /// <param name="name">The plugin name.</param> + /// <param name="version">The plugin <see cref="Version"/>.</param> + /// <param name="description">The plugin description.</param> + /// <param name="id">The <see cref="Guid"/>.</param> + /// <param name="canUninstall">True if this plugin can be uninstalled.</param> + public PluginInfo(string name, Version version, string description, Guid id, bool canUninstall) + { + Name = name; + Version = version?.ToString() ?? throw new ArgumentNullException(nameof(version)); + Description = description; + Id = id.ToString(); + CanUninstall = canUninstall; + } + /// <summary> /// Gets or sets the name. /// </summary> - /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the version. /// </summary> - /// <value>The version.</value> public string Version { get; set; } /// <summary> /// Gets or sets the name of the configuration file. /// </summary> - /// <value>The name of the configuration file.</value> - public string ConfigurationFileName { get; set; } + public string? ConfigurationFileName { get; set; } /// <summary> /// Gets or sets the description. /// </summary> - /// <value>The description.</value> public string Description { get; set; } /// <summary> /// Gets or sets the unique id. /// </summary> - /// <value>The unique id.</value> public string Id { get; set; } /// <summary> @@ -42,9 +57,13 @@ namespace MediaBrowser.Model.Plugins public bool CanUninstall { get; set; } /// <summary> - /// Gets or sets the image URL. + /// Gets or sets a value indicating whether this plugin has a valid image. /// </summary> - /// <value>The image URL.</value> - public string ImageUrl { get; set; } + public bool HasImage { get; set; } + + /// <summary> + /// Gets or sets a value indicating the status of the plugin. + /// </summary> + public PluginStatus Status { get; set; } } } diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs new file mode 100644 index 0000000000..439968ba8a --- /dev/null +++ b/MediaBrowser.Model/Plugins/PluginStatus.cs @@ -0,0 +1,17 @@ +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member +#pragma warning disable SA1602 // Enumeration items should be documented +namespace MediaBrowser.Model.Plugins +{ + /// <summary> + /// Plugin load status. + /// </summary> + public enum PluginStatus + { + RestartRequired = 1, + Active = 0, + Disabled = -1, + NotSupported = -2, + Malfunction = -3, + Superceded = -4 + } +} diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 5e93043639..77e2d8d88a 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -1,4 +1,4 @@ -#nullable disable +#nullable enable using System; using System.Collections.Generic; @@ -9,55 +9,70 @@ namespace MediaBrowser.Model.Updates /// </summary> public class PackageInfo { + /// <summary> + /// Initializes a new instance of the <see cref="PackageInfo"/> class. + /// </summary> + public PackageInfo() + { + Versions = Array.Empty<VersionInfo>(); + Guid = string.Empty; + Category = string.Empty; + Name = string.Empty; + Overview = string.Empty; + Owner = string.Empty; + Description = string.Empty; + } + /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> - public string name { get; set; } + public string Name { get; set; } /// <summary> /// Gets or sets a long description of the plugin containing features or helpful explanations. /// </summary> /// <value>The description.</value> - public string description { get; set; } + public string Description { get; set; } /// <summary> /// Gets or sets a short overview of what the plugin does. /// </summary> /// <value>The overview.</value> - public string overview { get; set; } + public string Overview { get; set; } /// <summary> /// Gets or sets the owner. /// </summary> /// <value>The owner.</value> - public string owner { get; set; } + public string Owner { get; set; } /// <summary> /// Gets or sets the category. /// </summary> /// <value>The category.</value> - public string category { get; set; } + public string Category { get; set; } /// <summary> - /// The guid of the assembly associated with this plugin. + /// Gets or sets the guid of the assembly associated with this plugin. /// This is used to identify the proper item for automatic updates. /// </summary> /// <value>The name.</value> - public string guid { get; set; } +#pragma warning disable CA1720 // Identifier contains type name + public string Guid { get; set; } +#pragma warning restore CA1720 // Identifier contains type name /// <summary> /// Gets or sets the versions. /// </summary> /// <value>The versions.</value> - public IList<VersionInfo> versions { get; set; } +#pragma warning disable CA2227 // Collection properties should be read only + public IList<VersionInfo> Versions { get; set; } +#pragma warning restore CA2227 // Collection properties should be read only /// <summary> - /// Initializes a new instance of the <see cref="PackageInfo"/> class. + /// Gets or sets the image url for the package. /// </summary> - public PackageInfo() - { - versions = Array.Empty<VersionInfo>(); - } + public string? ImageUrl { get; set; } } } diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs index 844170999a..1e07c9f26b 100644 --- a/MediaBrowser.Model/Updates/VersionInfo.cs +++ b/MediaBrowser.Model/Updates/VersionInfo.cs @@ -1,6 +1,6 @@ -#nullable disable +#nullable enable -using System; +using SysVersion = System.Version; namespace MediaBrowser.Model.Updates { @@ -9,68 +9,68 @@ namespace MediaBrowser.Model.Updates /// </summary> public class VersionInfo { - private Version _version; + private SysVersion? _version; /// <summary> /// Gets or sets the version. /// </summary> /// <value>The version.</value> - public string version + public string Version { - get - { - return _version == null ? string.Empty : _version.ToString(); - } + get => _version == null ? string.Empty : _version.ToString(); - set - { - _version = Version.Parse(value); - } + set => _version = SysVersion.Parse(value); } /// <summary> - /// Gets the version as a <see cref="Version"/>. + /// Gets the version as a <see cref="SysVersion"/>. /// </summary> - public Version VersionNumber => _version; + public SysVersion VersionNumber => _version ?? new SysVersion(0, 0, 0); /// <summary> /// Gets or sets the changelog for this version. /// </summary> /// <value>The changelog.</value> - public string changelog { get; set; } + public string? Changelog { get; set; } /// <summary> /// Gets or sets the ABI that this version was built against. /// </summary> /// <value>The target ABI version.</value> - public string targetAbi { get; set; } + public string? TargetAbi { get; set; } + + /// <summary> + /// Gets or sets the maximum ABI that this version will work with. + /// </summary> + /// <value>The target ABI version.</value> + public string? MaxAbi { get; set; } /// <summary> /// Gets or sets the source URL. /// </summary> /// <value>The source URL.</value> - public string sourceUrl { get; set; } + public string? SourceUrl { get; set; } /// <summary> /// Gets or sets a checksum for the binary. /// </summary> /// <value>The checksum.</value> - public string checksum { get; set; } + public string? Checksum { get; set; } /// <summary> /// Gets or sets a timestamp of when the binary was built. /// </summary> /// <value>The timestamp.</value> - public string timestamp { get; set; } + public string? Timestamp { get; set; } /// <summary> /// Gets or sets the repository name. /// </summary> - public string repositoryName { get; set; } + public string RepositoryName { get; set; } = string.Empty; /// <summary> /// Gets or sets the repository url. /// </summary> - public string repositoryUrl { get; set; } + public string RepositoryUrl { get; set; } = string.Empty; } } diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 5a807372d7..36518377c4 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -70,7 +71,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\NetworkTesting\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From a246a77ada21466587eb7fe02cc50033ab91c2e3 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 14 Dec 2020 23:08:04 +0000 Subject: [PATCH 0727/1930] Delete plugin working. --- .../Plugins/PluginManager.cs | 51 ++++++++++++------- Jellyfin.Api/Controllers/PackageController.cs | 3 -- Jellyfin.Api/Controllers/PluginsController.cs | 32 +++++------- MediaBrowser.Model/Plugins/PluginStatus.cs | 3 +- 4 files changed, 48 insertions(+), 41 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 8596dfcf8a..1377c80eaa 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -78,8 +78,27 @@ namespace Emby.Server.Implementations /// <returns>An IEnumerable{Assembly}.</returns> public IEnumerable<Assembly> LoadAssemblies() { + // Attempt to remove any deleted plugins and change any successors to be active. + for (int a = _plugins.Count - 1; a >= 0; a--) + { + var plugin = _plugins[a]; + if (plugin.Manifest.Status == PluginStatus.DeleteOnStartup && DeletePlugin(plugin)) + { + UpdateSuccessors(plugin); + } + } + + // Now load the assemblies.. foreach (var plugin in _plugins) { + CheckIfStillSuperceded(plugin); + + if (plugin.IsEnabledAndSupported == false) + { + _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name); + continue; + } + foreach (var file in plugin.DllFiles) { try @@ -183,15 +202,13 @@ namespace Emby.Server.Implementations throw new ArgumentNullException(nameof(plugin)); } - plugin.Instance?.OnUninstalling(); - if (DeletePlugin(plugin)) { return true; } // Unable to delete, so disable. - return ChangePluginState(plugin, PluginStatus.Disabled); + return ChangePluginState(plugin, PluginStatus.DeleteOnStartup); } /// <summary> @@ -205,11 +222,18 @@ namespace Emby.Server.Implementations { if (version == null) { - // If no version is given, return the largest version number. (This is for backwards compatibility). - plugin = _plugins.Where(p => p.Id.Equals(id)).OrderByDescending(p => p.Version).FirstOrDefault(); + // If no version is given, return the current instance. + var plugins = _plugins.Where(p => p.Id.Equals(id)); + + plugin = plugins.FirstOrDefault(p => p.Instance != null); + if (plugin == null) + { + plugin = plugins.OrderByDescending(p => p.Version).FirstOrDefault(); + } } else { + // Match id and version number. plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version)); } @@ -264,7 +288,6 @@ namespace Emby.Server.Implementations var predecessor = _plugins.OrderByDescending(p => p.Version) .FirstOrDefault( p => p.Id.Equals(plugin.Id) - && p.Name.Equals(plugin.Name, StringComparison.OrdinalIgnoreCase) && p.IsEnabledAndSupported && p.Version != plugin.Version); @@ -381,17 +404,6 @@ namespace Emby.Server.Implementations // Find the record for this plugin. var plugin = GetPluginByType(type); - if (plugin != null) - { - CheckIfStillSuperceded(plugin); - - if (plugin.IsEnabledAndSupported == true) - { - _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name); - return null; - } - } - try { _logger.LogDebug("Creating instance of {Type}", type); @@ -489,6 +501,7 @@ namespace Emby.Server.Implementations { _logger.LogDebug("Deleting {Path}", plugin.Path); Directory.Delete(plugin.Path, true); + _plugins.Remove(plugin); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) @@ -661,8 +674,8 @@ namespace Emby.Server.Implementations continue; } - // Update the manifest so its not loaded next time. - manifest.Status = PluginStatus.Disabled; + manifest.Status = PluginStatus.DeleteOnStartup; + SaveManifest(manifest, entry.Path); } } diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 622a0fe00d..d139159aa0 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -46,7 +46,6 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="PackageInfo"/> containing package information.</returns> [HttpGet("Packages/{name}")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<ActionResult<PackageInfo>> GetPackageInfo( [FromRoute, Required] string name, [FromQuery] Guid? assemblyGuid) @@ -73,7 +72,6 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="PackageInfo"/> containing available packages information.</returns> [HttpGet("Packages")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<IEnumerable<PackageInfo>> GetPackages() { IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); @@ -148,7 +146,6 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="OkResult"/> containing the list of package repositories.</returns> [HttpGet("Repositories")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public ActionResult<IEnumerable<RepositoryInfo>> GetRepositories() { return _serverConfigurationManager.Configuration.PluginRepositories; diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 3f366dd79f..d7a67389d1 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -14,7 +14,6 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; -using MediaBrowser.Controller.Drawing; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Net; using MediaBrowser.Model.Plugins; @@ -130,7 +129,7 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Plugin enabled.</response> /// <response code="404">Plugin not found.</response> /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> - [HttpPost("{pluginId}/Enable")] + [HttpPost("{pluginId}/{version}/Enable")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] @@ -153,7 +152,7 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Plugin disabled.</response> /// <response code="404">Plugin not found.</response> /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> - [HttpPost("{pluginId}/Disable")] + [HttpPost("{pluginId}/{version}/Disable")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] @@ -176,11 +175,11 @@ namespace Jellyfin.Api.Controllers /// <response code="204">Plugin uninstalled.</response> /// <response code="404">Plugin not found.</response> /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> - [HttpDelete("{pluginId}")] + [HttpDelete("{pluginId}/{version}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId, Version version) + public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { @@ -195,7 +194,6 @@ namespace Jellyfin.Api.Controllers /// Gets plugin configuration. /// </summary> /// <param name="pluginId">Plugin id.</param> - /// <param name="version">Plugin version.</param> /// <response code="200">Plugin configuration returned.</response> /// <response code="404">Plugin not found or plugin configuration not found.</response> /// <returns>Plugin configuration.</returns> @@ -203,9 +201,9 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesFile(MediaTypeNames.Application.Json)] - public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId) { - if (_pluginManager.TryGetPlugin(pluginId, version, out var plugin) + if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin) && plugin!.Instance is IHasPluginConfiguration configPlugin) { return configPlugin.Configuration; @@ -221,7 +219,6 @@ namespace Jellyfin.Api.Controllers /// Accepts plugin configuration as JSON body. /// </remarks> /// <param name="pluginId">Plugin id.</param> - /// <param name="version">Plugin version.</param> /// <response code="204">Plugin configuration updated.</response> /// <response code="404">Plugin not found or plugin does not have configuration.</response> /// <returns> @@ -232,9 +229,9 @@ namespace Jellyfin.Api.Controllers [HttpPost("{pluginId}/Configuration")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId) { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin) + if (!_pluginManager.TryGetPlugin(pluginId, null, out var plugin) || plugin?.Instance is not IHasPluginConfiguration configPlugin) { return NotFound(); @@ -258,12 +255,12 @@ namespace Jellyfin.Api.Controllers /// <param name="version">Plugin version.</param> /// <response code="200">Plugin image returned.</response> /// <returns>Plugin's image.</returns> - [HttpGet("{pluginId}/Image")] + [HttpGet("{pluginId}/{version}/Image")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] [AllowAnonymous] - public ActionResult GetPluginImage([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult GetPluginImage([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { @@ -292,12 +289,12 @@ namespace Jellyfin.Api.Controllers /// <param name="version">Plugin version.</param> /// <response code="200">Plugin image returned.</response> /// <returns>Plugin's image.</returns> - [HttpGet("{pluginId}/StatusImage")] + [HttpGet("{pluginId}/{version}/StatusImage")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] [AllowAnonymous] - public ActionResult GetPluginStatusImage([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult GetPluginStatusImage([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { @@ -316,7 +313,6 @@ namespace Jellyfin.Api.Controllers /// Gets a plugin's manifest. /// </summary> /// <param name="pluginId">Plugin id.</param> - /// <param name="version">Plugin version.</param> /// <response code="204">Plugin manifest returned.</response> /// <response code="404">Plugin not found.</response> /// <returns> @@ -328,9 +324,9 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesFile(MediaTypeNames.Application.Json)] - public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId) { - if (_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin)) { return Ok(plugin!.Manifest); } diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs index 439968ba8a..a953206e89 100644 --- a/MediaBrowser.Model/Plugins/PluginStatus.cs +++ b/MediaBrowser.Model/Plugins/PluginStatus.cs @@ -12,6 +12,7 @@ namespace MediaBrowser.Model.Plugins Disabled = -1, NotSupported = -2, Malfunction = -3, - Superceded = -4 + Superceded = -4, + DeleteOnStartup = -5 } } From d2d45295fc2a948f9a6945f56197097d0f2ef9d6 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 14 Dec 2020 23:13:29 +0000 Subject: [PATCH 0728/1930] Rollback change. --- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index 155e116a56..3c553a1b50 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -38,7 +38,7 @@ namespace Jellyfin.Api.Models EnableInMainMenu = page.EnableInMainMenu; MenuSection = page.MenuSection; MenuIcon = page.MenuIcon; - DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin?.Name ?? page.DisplayName : page.DisplayName; + DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin?.Name : page.DisplayName; // Don't use "N" because it needs to match Plugin.Id PluginId = plugin?.Id.ToString(); From 494ace7984edab77df7f9da30e411d8d3d617036 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Mon, 14 Dec 2020 23:39:47 +0000 Subject: [PATCH 0729/1930] Mark plugin failure on DI Loop. --- Emby.Server.Implementations/ApplicationHost.cs | 5 +++++ Jellyfin.Api/Controllers/PackageController.cs | 5 +++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f88c6c6208..8df1ec3008 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -406,6 +406,11 @@ namespace Emby.Server.Implementations Logger.LogError("Called from: {stack}", entry.FullName); } + if (type is IPlugin) + { + _pluginManager.FailPlugin(type.Assembly); + } + throw new ExternalException("DI Loop detected."); } diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index d139159aa0..459e68da78 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -2,9 +2,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Net.Mime; using System.Threading.Tasks; -using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using MediaBrowser.Common.Json; using MediaBrowser.Common.Updates; @@ -46,6 +44,7 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="PackageInfo"/> containing package information.</returns> [HttpGet("Packages/{name}")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<ActionResult<PackageInfo>> GetPackageInfo( [FromRoute, Required] string name, [FromQuery] Guid? assemblyGuid) @@ -72,6 +71,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="PackageInfo"/> containing available packages information.</returns> [HttpGet("Packages")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<IEnumerable<PackageInfo>> GetPackages() { IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); @@ -146,6 +146,7 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="OkResult"/> containing the list of package repositories.</returns> [HttpGet("Repositories")] [ProducesResponseType(StatusCodes.Status200OK)] + [Produces(JsonDefaults.CamelCaseMediaType)] public ActionResult<IEnumerable<RepositoryInfo>> GetRepositories() { return _serverConfigurationManager.Configuration.PluginRepositories; From fbb20ebef6dee03de27e20d7e110e709ba2f20e9 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 00:42:59 +0000 Subject: [PATCH 0730/1930] Plugin setting migration to folders. --- .../ApplicationHost.cs | 5 +-- .../Plugins/PluginManager.cs | 11 ++++- MediaBrowser.Common/Plugins/BasePlugin.cs | 42 ++++++++++++++++++- 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 8df1ec3008..ddb48ff6e4 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -406,10 +406,7 @@ namespace Emby.Server.Implementations Logger.LogError("Called from: {stack}", entry.FullName); } - if (type is IPlugin) - { - _pluginManager.FailPlugin(type.Assembly); - } + _pluginManager.FailPlugin(type.Assembly); throw new ExternalException("DI Loop detected."); } diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 1377c80eaa..07b7297482 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -296,7 +296,7 @@ namespace Emby.Server.Implementations return; } - if (!ChangePluginState(predecessor, PluginStatus.Superceded)) + if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded)) { _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); } @@ -314,7 +314,10 @@ namespace Emby.Server.Implementations throw new ArgumentNullException(nameof(assembly)); } - var plugin = _plugins.Where(p => assembly.Equals(p.Assembly)).FirstOrDefault(); + var plugin = _plugins.Where( + p => assembly.Equals(p.Assembly) + || string.Equals(assembly.Location, assembly.Location, StringComparison.OrdinalIgnoreCase)) + .FirstOrDefault(); if (plugin == null) { // A plugin's assembly didn't cause this issue, so ignore it. @@ -403,6 +406,10 @@ namespace Emby.Server.Implementations { // Find the record for this plugin. var plugin = GetPluginByType(type); + if (plugin?.Manifest.Status < PluginStatus.Active) + { + return null; + } try { diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index b918fc4f6d..a0d6b8f836 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -134,7 +134,26 @@ namespace MediaBrowser.Common.Plugins var assemblyName = assembly.GetName(); var assemblyFilePath = assembly.Location; - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + // Find out the plugin folder. + bool inPluginFolder = assemblyFilePath.StartsWith(ApplicationPaths.PluginsPath, StringComparison.OrdinalIgnoreCase); + string path, dataFolderPath; + + var configurationFileName = Path.ChangeExtension(Path.GetFileName(assemblyFilePath), ".xml"); + if (inPluginFolder) + { + // Normal plugin. + path = assemblyFilePath.Substring(ApplicationPaths.PluginsPath.Length).Split('\\', StringSplitOptions.RemoveEmptyEntries)[0]; + dataFolderPath = Path.Combine( + Path.Combine(ApplicationPaths.PluginsPath, path), + configurationFileName); + ConfigurationFilePath = dataFolderPath; + } + else + { + // Provider + dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + ConfigurationFilePath = Path.Combine(ApplicationPaths.PluginConfigurationsPath, configurationFileName); + } assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); @@ -146,6 +165,25 @@ namespace MediaBrowser.Common.Plugins assemblyPlugin.SetId(assemblyId); } + + // TODO : Simplify this, once migration support is ceased. + if (inPluginFolder) + { + var oldConfigFilePath = Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); + + if (!File.Exists(ConfigurationFilePath) && File.Exists(oldConfigFilePath)) + { + // Migrate settings, as different plugin versions may have different settings. + try + { + File.Copy(oldConfigFilePath, ConfigurationFilePath); + } + catch + { + // Unable to migrate settings. + } + } + } } if (this is IHasPluginConfiguration hasPluginConfiguration) @@ -219,7 +257,7 @@ namespace MediaBrowser.Common.Plugins /// Gets the full path to the configuration file. /// </summary> /// <value>The configuration file path.</value> - public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); + public string ConfigurationFilePath { get; } /// <summary> /// Gets the plugin configuration. From 356d92cd71c698f91d76d6437166c90ee656a900 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 00:49:14 +0000 Subject: [PATCH 0731/1930] Fixed repository listing --- Jellyfin.Api/Controllers/PackageController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 459e68da78..906188026b 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -146,7 +146,6 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="OkResult"/> containing the list of package repositories.</returns> [HttpGet("Repositories")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public ActionResult<IEnumerable<RepositoryInfo>> GetRepositories() { return _serverConfigurationManager.Configuration.PluginRepositories; From 0d4aa6bad61a8d7ef74b88a161913c5a64663937 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 01:13:11 +0000 Subject: [PATCH 0732/1930] Enable local file repositories --- .../Updates/InstallationManager.cs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index b0a1750bdd..325955e207 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Security.Cryptography; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -105,8 +106,20 @@ namespace Emby.Server.Implementations.Updates { try { - var packages = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); + List<PackageInfo>? packages; + var uri = new Uri(manifest); + if (uri.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + packages = await _httpClientFactory.CreateClient(NamedClient.Default) + .GetFromJsonAsync<List<PackageInfo>>(uri, _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); + } + else + { + // Local Packages + var data = File.ReadAllText(manifest, Encoding.UTF8); + packages = JsonSerializer.Deserialize<List<PackageInfo>>(data, _jsonSerializerOptions); + } + if (packages == null) { return Array.Empty<PackageInfo>(); @@ -150,6 +163,11 @@ namespace Emby.Server.Implementations.Updates return packages; } + catch (IOException ex) + { + _logger.LogError(ex, "Cannot locate the plugin manifest {Manifest}", manifest); + return Array.Empty<PackageInfo>(); + } catch (JsonException ex) { _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest); From cddc87e2af241b6b2149a5c9e1a2b2714e482613 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 01:23:52 +0000 Subject: [PATCH 0733/1930] Fixed gitmerge. --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index e58f02d410..75a9ca0801 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -231,7 +231,7 @@ namespace Emby.Server.Implementations.Updates } // Don't add a package that doesn't have any compatible versions. - if (package.versions.Count == 0) + if (package.Versions.Count == 0) { continue; } From 2bb12793b29dc078b3f1597afc4ab8e366f098a7 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 01:31:56 +0000 Subject: [PATCH 0734/1930] Add files via upload --- Emby.Server.Implementations/Plugins/Disabled.png | Bin 0 -> 1790 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Emby.Server.Implementations/Plugins/Disabled.png diff --git a/Emby.Server.Implementations/Plugins/Disabled.png b/Emby.Server.Implementations/Plugins/Disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..eeb8ffefc2d008695cb1f8fbcce47ee84ae5c277 GIT binary patch literal 1790 zcmV<a1_AkrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000KXNkl<Zc-pmB zSxl2z6h2)k1*I)eq=;A}vb%tSOBoneozYPzGjE27D5wxMF(yV66O-{tBa5RE5HgvE z$xNJa2_stp83m0ZBJK(lL0MX)Wog;E&AGQUlto$}ILUdq=l=KJ@1Etm=VyR@Vdm!M zZg+9v|IK7_P*^ZFHl`mL8Tskx(WC$3yvcz*z9<ZPhhMmGVW+#h$Bnh?)`6?*B5KrX zhv8XM6STIr1fM&1?k$?k3k85zP*BjZAu>wb+pB^%Z{LF1Y=(%4aNu&-2;%9(!-o&Y z;&&4Z1wdF>SfEZ!+6MpJxCI<MlmHM41rQb*0uSo%zst<bip1}R77Bp4u&_}1ZCnCW zRo{h)iE)e3(-Q&${Gq<?err}%Rur1l3kAUA{Q2{LMTAGhvA9mq)YJ?l+%nk~P<D4g z<I~3CGiS~mN8`Xk0a)bf>bfc~H}6S&ViMfAd5ao<+`S7b%I`pWdPXP?+fhdr3IH2b zl7IDTdvr`3^L|}D=yX~Npt8Ia(lauAalQxDXuIh0<;%j%%uJ1=065pKT~lFl2}pv? z612Hs`9(%;ggd2W)RdHz2rphdg8{V$7>wC>;Pd$~K0Xd<X=zSir$WeT0VbLzA#p3s z@HzIQhcq`ohpz5!Iu;1sVDrXJFc)CU9t=#-dvN{wb?NQfw?EheAjVo(5&(BfOM%5= zO^c2d5R=KIO2lL`qY?r%QwCz#9Bwq4;QQ~kL6y85b0pmx%}SVusB8cvgS@JW9zt$l zt5z?}yy;xGHyVwQ5FZcnN(x}fBmny!h)+s}kDVW3@#4i`z)c1R2B5dMm)_KRb9-V1 z5E~l<@(K#T3(YFK04UkSC%}hx1*p|(q**R_ip3yucZXN6-@w?&s6!yE0A%0Dpz3P? z6crUISu8fRwY8Si*VmQ#`7K`-9v+^$Tq^Zi=^p^i&!1!9&2wh_Yyc+Mv^ff@Dk~fY zAWBV5{rSJz+Ac+V`zIW0Q8}m{7cX8c!t(Ri<EDK|m0d3o03>AVBO}lQ6_AmUK>+k$ zxpL(fHk+M-_$8RY_cR*K{*xz9wvr_T01wq|5)5H9Lipq)(VjhfcK@(*=cRz4AZUHx z=1>?&2-bzKg@(tEXdV%f`1rswzvbZU><lWU65hXi2mSq@WhYLYc)*xEnCwi_+P1mi zrKF^6-M(YT&49pQXjim51b}#e@4^RP-=)Cia;Z(H(?OrA4@Sqvz{|@En0VsT#s<TI z1L=$A3o2*-{<OHn<mB?;piubG(cy445D=CswUnxD?vOBrhJ;#qLNp%$r|j(PKSRS- z?-GdI@doyD!1j=tJYfYv?5q6!p{80+layGw#l^+rh+3u9YWE&HcC6yaks~~*RC-D* z_By?O!v^@&)lFkNQ|77)asZdZ0e386KHmksVFaC42kHS0==FN=@bCZze$)8mvEe{^ zx)0ewh>wvvBqR*utbk$dAks160S^ca3<8a20JQi5ve_K^$nbbPde8(uHd>6W(P)_E zVjqbQDB4<~v$F#@xXw>11wX%Kbl<){CA@n160qElWBLC!jf%%6#(>M_(oL}QMKHtk zRdaE10Rb{3d5ngKhrpmWfKVg?i9`Y;NK%7CgVS8>yVRFb@xg-!w_zeO&YnGc3Oynt z^9F-KT~=0hx}>B;j>B#Xfc$)ATtYH*_jJv2Esx6s4wns28XBOdr@L06P&^{`6)RS3 z^!Ap-kPsn7(LTWnK;kWdYIz0e7Xr~ViYfw2sgsvZ2NrT7IywaaJ)lx4XT?<@5W<V* zCa9~c`!z2w?{_o}PfoeU#>TEqP2F3#X-hQLbw611UW_zeQ%M03A|m~wGf8T&l)D}* zd_(#KN<`v(1VCCY@(#=t5xTlsUP)MO4Gz0ts{JAxF1eJKS0js!@irM5m=F4yYaDwE z@~H=sU}$h~+9Z?7LYErh(Zh$@Lx&C#carwYWV6;ICnu+Ni!3^r>*Pe@OD7h)xk1g> z04SIQKp1PL@G$}J)!v1)ef#Fx%pJjh-Ykoz151+vG-(NdbVmW;&xbMre?CY_O(PJ@ z2Nsggo7b<PwWZ|`{1;4tsRopllbxL-UAZzVZ1oy2Ax~J_G4irjRh9u#t;7958%ZiN zq0kwVRuD#$sT-Lq04%R1y=Y-UK?{?`@}?wZo@&n+7RDUL7cT&lv&S9)0jd;L2w!f~ zNpL@-cEVH@kUv$@mV1JweYX{Yg|y}5pJCpg7TT7R+n{n`ej(2^sQ~@tn5^T2r5ffE gQf4}v@8^{N0fxpCu>c)zWdHyG07*qoM6N<$f?{PtRsaA1 literal 0 HcmV?d00001 From 3cff64ee320b94ec915ba96d52d946701c1a7ff1 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 01:32:43 +0000 Subject: [PATCH 0735/1930] Delete disabled.png Should have a capital letter --- Emby.Server.Implementations/Plugins/disabled.png | Bin 1790 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Emby.Server.Implementations/Plugins/disabled.png diff --git a/Emby.Server.Implementations/Plugins/disabled.png b/Emby.Server.Implementations/Plugins/disabled.png deleted file mode 100644 index eeb8ffefc2d008695cb1f8fbcce47ee84ae5c277..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1790 zcmV<a1_AkrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000KXNkl<Zc-pmB zSxl2z6h2)k1*I)eq=;A}vb%tSOBoneozYPzGjE27D5wxMF(yV66O-{tBa5RE5HgvE z$xNJa2_stp83m0ZBJK(lL0MX)Wog;E&AGQUlto$}ILUdq=l=KJ@1Etm=VyR@Vdm!M zZg+9v|IK7_P*^ZFHl`mL8Tskx(WC$3yvcz*z9<ZPhhMmGVW+#h$Bnh?)`6?*B5KrX zhv8XM6STIr1fM&1?k$?k3k85zP*BjZAu>wb+pB^%Z{LF1Y=(%4aNu&-2;%9(!-o&Y z;&&4Z1wdF>SfEZ!+6MpJxCI<MlmHM41rQb*0uSo%zst<bip1}R77Bp4u&_}1ZCnCW zRo{h)iE)e3(-Q&${Gq<?err}%Rur1l3kAUA{Q2{LMTAGhvA9mq)YJ?l+%nk~P<D4g z<I~3CGiS~mN8`Xk0a)bf>bfc~H}6S&ViMfAd5ao<+`S7b%I`pWdPXP?+fhdr3IH2b zl7IDTdvr`3^L|}D=yX~Npt8Ia(lauAalQxDXuIh0<;%j%%uJ1=065pKT~lFl2}pv? z612Hs`9(%;ggd2W)RdHz2rphdg8{V$7>wC>;Pd$~K0Xd<X=zSir$WeT0VbLzA#p3s z@HzIQhcq`ohpz5!Iu;1sVDrXJFc)CU9t=#-dvN{wb?NQfw?EheAjVo(5&(BfOM%5= zO^c2d5R=KIO2lL`qY?r%QwCz#9Bwq4;QQ~kL6y85b0pmx%}SVusB8cvgS@JW9zt$l zt5z?}yy;xGHyVwQ5FZcnN(x}fBmny!h)+s}kDVW3@#4i`z)c1R2B5dMm)_KRb9-V1 z5E~l<@(K#T3(YFK04UkSC%}hx1*p|(q**R_ip3yucZXN6-@w?&s6!yE0A%0Dpz3P? z6crUISu8fRwY8Si*VmQ#`7K`-9v+^$Tq^Zi=^p^i&!1!9&2wh_Yyc+Mv^ff@Dk~fY zAWBV5{rSJz+Ac+V`zIW0Q8}m{7cX8c!t(Ri<EDK|m0d3o03>AVBO}lQ6_AmUK>+k$ zxpL(fHk+M-_$8RY_cR*K{*xz9wvr_T01wq|5)5H9Lipq)(VjhfcK@(*=cRz4AZUHx z=1>?&2-bzKg@(tEXdV%f`1rswzvbZU><lWU65hXi2mSq@WhYLYc)*xEnCwi_+P1mi zrKF^6-M(YT&49pQXjim51b}#e@4^RP-=)Cia;Z(H(?OrA4@Sqvz{|@En0VsT#s<TI z1L=$A3o2*-{<OHn<mB?;piubG(cy445D=CswUnxD?vOBrhJ;#qLNp%$r|j(PKSRS- z?-GdI@doyD!1j=tJYfYv?5q6!p{80+layGw#l^+rh+3u9YWE&HcC6yaks~~*RC-D* z_By?O!v^@&)lFkNQ|77)asZdZ0e386KHmksVFaC42kHS0==FN=@bCZze$)8mvEe{^ zx)0ewh>wvvBqR*utbk$dAks160S^ca3<8a20JQi5ve_K^$nbbPde8(uHd>6W(P)_E zVjqbQDB4<~v$F#@xXw>11wX%Kbl<){CA@n160qElWBLC!jf%%6#(>M_(oL}QMKHtk zRdaE10Rb{3d5ngKhrpmWfKVg?i9`Y;NK%7CgVS8>yVRFb@xg-!w_zeO&YnGc3Oynt z^9F-KT~=0hx}>B;j>B#Xfc$)ATtYH*_jJv2Esx6s4wns28XBOdr@L06P&^{`6)RS3 z^!Ap-kPsn7(LTWnK;kWdYIz0e7Xr~ViYfw2sgsvZ2NrT7IywaaJ)lx4XT?<@5W<V* zCa9~c`!z2w?{_o}PfoeU#>TEqP2F3#X-hQLbw611UW_zeQ%M03A|m~wGf8T&l)D}* zd_(#KN<`v(1VCCY@(#=t5xTlsUP)MO4Gz0ts{JAxF1eJKS0js!@irM5m=F4yYaDwE z@~H=sU}$h~+9Z?7LYErh(Zh$@Lx&C#carwYWV6;ICnu+Ni!3^r>*Pe@OD7h)xk1g> z04SIQKp1PL@G$}J)!v1)ef#Fx%pJjh-Ykoz151+vG-(NdbVmW;&xbMre?CY_O(PJ@ z2Nsggo7b<PwWZ|`{1;4tsRopllbxL-UAZzVZ1oy2Ax~J_G4irjRh9u#t;7958%ZiN zq0kwVRuD#$sT-Lq04%R1y=Y-UK?{?`@}?wZo@&n+7RDUL7cT&lv&S9)0jd;L2w!f~ zNpL@-cEVH@kUv$@mV1JweYX{Yg|y}5pJCpg7TT7R+n{n`ej(2^sQ~@tn5^T2r5ffE gQf4}v@8^{N0fxpCu>c)zWdHyG07*qoM6N<$f?{PtRsaA1 From 9f6000d845d40b58da193d61b1cf0229d3a39ca1 Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Tue, 15 Dec 2020 08:18:36 +0100 Subject: [PATCH 0736/1930] Add missing seasons during AfterMetadataRefresh --- .../TV/SeriesMetadataService.cs | 133 +++++++++++++++++- 1 file changed, 132 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/TV/SeriesMetadataService.cs b/MediaBrowser.Providers/TV/SeriesMetadataService.cs index c8fc568a22..9679081975 100644 --- a/MediaBrowser.Providers/TV/SeriesMetadataService.cs +++ b/MediaBrowser.Providers/TV/SeriesMetadataService.cs @@ -1,10 +1,16 @@ #pragma warning disable CS1591 +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Providers.Manager; using Microsoft.Extensions.Logging; @@ -13,14 +19,27 @@ namespace MediaBrowser.Providers.TV { public class SeriesMetadataService : MetadataService<Series, SeriesInfo> { + private readonly ILocalizationManager _localizationManager; + public SeriesMetadataService( IServerConfigurationManager serverConfigurationManager, ILogger<SeriesMetadataService> logger, IProviderManager providerManager, IFileSystem fileSystem, - ILibraryManager libraryManager) + ILibraryManager libraryManager, + ILocalizationManager localizationManager) : base(serverConfigurationManager, logger, providerManager, fileSystem, libraryManager) { + _localizationManager = localizationManager; + } + + /// <inheritdoc /> + protected override async Task AfterMetadataRefresh(Series item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) + { + await base.AfterMetadataRefresh(item, refreshOptions, cancellationToken).ConfigureAwait(false); + + RemoveObsoleteSeasons(item); + await FillInMissingSeasonsAsync(item, cancellationToken).ConfigureAwait(false); } /// <inheritdoc /> @@ -62,5 +81,117 @@ namespace MediaBrowser.Providers.TV targetItem.AirDays = sourceItem.AirDays; } } + + private void RemoveObsoleteSeasons(Series series) + { + // TODO Legacy. It's not really "physical" seasons as any virtual seasons are always converted to non-virtual in FillInMissingSeasonsAsync. + var physicalSeasonNumbers = new HashSet<int>(); + var virtualSeasons = new List<Season>(); + foreach (var existingSeason in series.Children.OfType<Season>()) + { + if (existingSeason.LocationType != LocationType.Virtual && existingSeason.IndexNumber.HasValue) + { + physicalSeasonNumbers.Add(existingSeason.IndexNumber.Value); + } + else if (existingSeason.LocationType == LocationType.Virtual) + { + virtualSeasons.Add(existingSeason); + } + } + + foreach (var virtualSeason in virtualSeasons) + { + var seasonNumber = virtualSeason.IndexNumber; + // If there's a physical season with the same number or no episodes in the season, delete it + if ((seasonNumber.HasValue && physicalSeasonNumbers.Contains(seasonNumber.Value)) + || !virtualSeason.GetEpisodes().Any()) + { + Logger.LogInformation("Removing virtual season {SeasonNumber} in series {SeriesName}", virtualSeason.IndexNumber, series.Name); + + LibraryManager.DeleteItem( + virtualSeason, + new DeleteOptions + { + DeleteFileLocation = true + }, + false); + } + } + } + + /// <summary> + /// Creates seasons for all episodes that aren't in a season folder. + /// If no season number can be determined, a dummy season will be created. + /// </summary> + /// <param name="series">The series.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The async task.</returns> + private async Task FillInMissingSeasonsAsync(Series series, CancellationToken cancellationToken) + { + var episodesInSeriesFolder = series.GetRecursiveChildren(i => i is Episode) + .Cast<Episode>() + .Where(i => !i.IsInSeasonFolder); + + List<Season> seasons = series.Children.OfType<Season>().ToList(); + + // Loop through the unique season numbers + foreach (var episode in episodesInSeriesFolder) + { + // Null season numbers will have a 'dummy' season created because seasons are always required. + var seasonNumber = episode.ParentIndexNumber >= 0 ? episode.ParentIndexNumber : null; + var existingSeason = seasons.FirstOrDefault(i => i.IndexNumber == seasonNumber); + + if (existingSeason == null) + { + var season = await CreateSeasonAsync(series, seasonNumber, cancellationToken).ConfigureAwait(false); + seasons.Add(season); + } + else if (existingSeason.IsVirtualItem) + { + existingSeason.IsVirtualItem = false; + await existingSeason.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); + } + } + } + + /// <summary> + /// Creates a new season, adds it to the database by linking it to the [series] and refreshes the metadata. + /// </summary> + /// <param name="series">The series.</param> + /// <param name="seasonNumber">The season number.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The newly created season.</returns> + private async Task<Season> CreateSeasonAsync( + Series series, + int? seasonNumber, + CancellationToken cancellationToken) + { + string seasonName = seasonNumber switch + { + null => _localizationManager.GetLocalizedString("NameSeasonUnknown"), + 0 => LibraryManager.GetLibraryOptions(series).SeasonZeroDisplayName, + _ => string.Format(CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("NameSeasonNumber"), seasonNumber.Value) + }; + + Logger.LogInformation("Creating Season {SeasonName} entry for {SeriesName}", seasonName, series.Name); + + var season = new Season + { + Name = seasonName, + IndexNumber = seasonNumber, + Id = LibraryManager.GetNewItemId( + series.Id + (seasonNumber ?? -1).ToString(CultureInfo.InvariantCulture) + seasonName, + typeof(Season)), + IsVirtualItem = false, + SeriesId = series.Id, + SeriesName = series.Name + }; + + series.AddChild(season, cancellationToken); + + await season.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken).ConfigureAwait(false); + + return season; + } } } From 1c6529c9eb195e3cb8c439df8805652090c49a0f Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 07:54:49 +0000 Subject: [PATCH 0737/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index d7a67389d1..3759f9f1c4 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -133,7 +133,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult EnablePlugin([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult EnablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { From 33385c1b8cbe46b58f19716c85a3da9ec66cd282 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 07:55:14 +0000 Subject: [PATCH 0738/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 3759f9f1c4..afb5dc5ff8 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -156,7 +156,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult DisablePlugin([FromRoute, Required] Guid pluginId, [FromRoute] Version? version) + public ActionResult DisablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { From 5b4eef741a0afc33a2f835a8feb3b0e600aaf47c Mon Sep 17 00:00:00 2001 From: cvium <clausvium@gmail.com> Date: Tue, 15 Dec 2020 09:27:33 +0100 Subject: [PATCH 0739/1930] Convert from base64 when saving item images --- Jellyfin.Api/Controllers/ImageController.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index e828a0801b..c606d327c5 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -325,9 +325,11 @@ namespace Jellyfin.Api.Controllers return NotFound(); } + await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false); + // Handle image/png; charset=utf-8 var mimeType = Request.ContentType.Split(';').FirstOrDefault(); - await _providerManager.SaveImage(item, Request.Body, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); + await _providerManager.SaveImage(item, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false); return NoContent(); @@ -358,9 +360,11 @@ namespace Jellyfin.Api.Controllers return NotFound(); } + await using var memoryStream = await GetMemoryStream(Request.Body).ConfigureAwait(false); + // Handle image/png; charset=utf-8 var mimeType = Request.ContentType.Split(';').FirstOrDefault(); - await _providerManager.SaveImage(item, Request.Body, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); + await _providerManager.SaveImage(item, memoryStream, mimeType, imageType, null, CancellationToken.None).ConfigureAwait(false); await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false); return NoContent(); From 41466c430de6ad8b3aa2599af9e6e41f1f63c785 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 09:17:06 +0000 Subject: [PATCH 0740/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index afb5dc5ff8..36e37b7ad0 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -113,7 +113,6 @@ namespace Jellyfin.Api.Controllers /// <returns>List of currently installed plugins.</returns> [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesFile(MediaTypeNames.Application.Json)] public ActionResult<IEnumerable<PluginInfo>> GetPlugins() { return Ok(_pluginManager.Plugins From dddcfa6dbbca04ed69597ec335007612e2e2b8e8 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 09:29:51 +0000 Subject: [PATCH 0741/1930] Suggested changes. --- .../ApplicationHost.cs | 3 +- .../Emby.Server.Implementations.csproj | 7 -- .../Plugins/Active.png | Bin 1422 -> 0 bytes .../Plugins/Disabled.png | Bin 1790 -> 0 bytes .../Plugins/Malfunction.png | Bin 2091 -> 0 bytes .../Plugins/NotSupported.png | Bin 2046 -> 0 bytes .../Plugins/PluginManager.cs | 3 - .../Plugins/RestartRequired.png | Bin 1996 -> 0 bytes .../Plugins/Superceded.png | Bin 2136 -> 0 bytes Emby.Server.Implementations/Plugins/blank.png | Bin 120 -> 0 bytes Jellyfin.Api/Controllers/PluginsController.cs | 60 +++++++++--------- 11 files changed, 32 insertions(+), 41 deletions(-) delete mode 100644 Emby.Server.Implementations/Plugins/Active.png delete mode 100644 Emby.Server.Implementations/Plugins/Disabled.png delete mode 100644 Emby.Server.Implementations/Plugins/Malfunction.png delete mode 100644 Emby.Server.Implementations/Plugins/NotSupported.png delete mode 100644 Emby.Server.Implementations/Plugins/RestartRequired.png delete mode 100644 Emby.Server.Implementations/Plugins/Superceded.png delete mode 100644 Emby.Server.Implementations/Plugins/blank.png diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 404e28bdcf..17cccdaf92 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -393,8 +393,7 @@ namespace Emby.Server.Implementations if (_creatingInstances.IndexOf(type) != -1) { - Logger.LogError("DI Loop detected."); - Logger.LogError("Attempted creation of {Type}", type.FullName); + Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName); foreach (var entry in _creatingInstances) { Logger.LogError("Called from: {stack}", entry.FullName); diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 7e0be78993..0c94f937ce 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -73,12 +73,5 @@ <EmbeddedResource Include="Localization\countries.json" /> <EmbeddedResource Include="Localization\Core\*.json" /> <EmbeddedResource Include="Localization\Ratings\*.csv" /> - <EmbeddedResource Include="Plugins\blank.png" /> - <EmbeddedResource Include="Plugins\Superceded.png" /> - <EmbeddedResource Include="Plugins\Disabled.png" /> - <EmbeddedResource Include="Plugins\NotSupported.png" /> - <EmbeddedResource Include="Plugins\Malfunction.png" /> - <EmbeddedResource Include="Plugins\RestartRequired.png" /> - <EmbeddedResource Include="Plugins\Active.png" /> </ItemGroup> </Project> diff --git a/Emby.Server.Implementations/Plugins/Active.png b/Emby.Server.Implementations/Plugins/Active.png deleted file mode 100644 index 3722ee5200f60eb51419a182b8e094c42c6291ec..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1422 zcmV;91#$X`P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D1tUpBK~z{ry_bD# z6jczwXWrYr-Mzc^+Hy3sRX(I7El3YRB@F=!NDwJSK?5z3hy<eujR_=11^KANs0kk$ z{}iMcJ{r@Kq6Q=(A`*}iLm^oFph)GTE#)XJy}RD-zUSM!J)rao{es_Ra+lfJH}hs^ z=ItRoLef{{LslMnPW(*coS!mGR{O{Tcy`YWDJ@xBo2<(3|J~S1C_~^Be|;nYjM+0i zC3AqgR3>ERUk$Awn+W1lWvaa3p$FjG^TLRcsR?^q0{Y0h8v#%l0Yb<xLCR*IDcs-u z&;ls<x&RuIjETZ|d7VGt^#{UY=L9Ih!vUG)SHHUdmSsmG*8NP@_AF=}$mjV6c@ETG zYxA~*3{ZiBgOU@vgBQe{Tl9Mda(7R~WKY7f$35D{n)+5rHyIF)Ksnav63aU__s2%t zG(x{-Aa7e93>uKMX0XS(<y=Fn#DRk-Ja7QH%2k+oY)(h#7X6liX?qJuibwfOwAl)) z(qo_jZCt_0hh|k)*{TloO9p1_n@v-b)y*lwd2Q1zkO)RZ^g5#|S#<rMi*cP>^f?3h z`>dU7o81n&{NL+swibZtVsQySzLIfab@fx#wze~U%0PZ)J`7BDe(F)B<(F;*#jZ(2 z&?-6!e?Zw>cR%MAkqnGGISzDLhts~(5oLFnb?`;>Iuk!iQlzyP{Q(g57J-Rx)8w_1 zg5xWmFK>!!yM|0SHvvYskC;2UIjf}b&?}0qzb`qZIgsk~EcI%RHJ6)1(PvJh!Wa)} z8ePyG=N2UU#^CvBZe=GjzDkV9gA0$&d(6HTm-O}N@bnWS=cKwEo37jpVzl6*sW(gx zno3u>Cnp}a%^!%k4VGNJ8FCP-Y7r))2~~@Z&Yv>vz%<*WBh#l&dL}JV-Co}klEqlP zvvbZtlE{9dvrSuZt8M*Yh{5<9VxeoXT~Ne9gu{WM3EmHu94Vx>U4%D}6=tL-s1^RU zup9Bt&c!{V1hCPqNsD()FK4!Sw;-mo=Awvvu}smt-M=U@%V7hRv0~|oq5+oS(%*_y zuS+QlhK&qUR9ei|65Rxrph<84nfu?B$f`Xc(gpAQ@iM?I=jS4iD<j&wK|C*7s?aIX zg%ogEb1-aQh|+F|vPUds?d<ifQ+C_E(0y(XqT;Frig-yl44jX*Rd+yacgj=_gvEIp z>o<Ybav>cqIW_cc8TYN<R`-YwlW^s!g~PeYe-}OyZPk4d$>6GrFKrxKT4}3#OovJ6 z@(nvLOQcv-HIG$ySHd{~#X)xY2l{*M+@jN2u=><%$SK{$8J}mXI>E)LZ8u1hs<P1= zp8TfXR`-fdXF<uB9l}2@7fpUS)@Jt#V-#E}zSj~y-zVo5aSx+)+1sv()_hB}Cc8KF zqDeuP=+DUX?O%>PV&Bnw;s#(nm_%>zdlAHrdv^~YwYxP|ye_BIj2ici_yGuty*q_N zTp>$X9~(HpB+wN2s`;vU#y0CST?Sy$Iz0Wl=!%t*^o!k7BGo%2zW$R*+iZ)z(_z-% zO>S;3xKFxK)1<S`447ydj$w*}zkA^e<+#u1LtWRQp`pRH?mck>C@Cqy%*@PWm&-Mj zHM+*I7D-i7%q;(RDL<)-<`&4=+1cSyqeg|Rs=9pL>lSezK`<CZ@$Z!gk%VBVRz2&l zO!^Q^3|o3}5>oN*fFh7ibEKzqxj<1-5eykJ1WnUKkqI;m11O~s4u`oVb#-;TtgOto c?kxcS0~w3NKFYLwmjD0&07*qoM6N<$g7!P0tN;K2 diff --git a/Emby.Server.Implementations/Plugins/Disabled.png b/Emby.Server.Implementations/Plugins/Disabled.png deleted file mode 100644 index eeb8ffefc2d008695cb1f8fbcce47ee84ae5c277..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1790 zcmV<a1_AkrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000KXNkl<Zc-pmB zSxl2z6h2)k1*I)eq=;A}vb%tSOBoneozYPzGjE27D5wxMF(yV66O-{tBa5RE5HgvE z$xNJa2_stp83m0ZBJK(lL0MX)Wog;E&AGQUlto$}ILUdq=l=KJ@1Etm=VyR@Vdm!M zZg+9v|IK7_P*^ZFHl`mL8Tskx(WC$3yvcz*z9<ZPhhMmGVW+#h$Bnh?)`6?*B5KrX zhv8XM6STIr1fM&1?k$?k3k85zP*BjZAu>wb+pB^%Z{LF1Y=(%4aNu&-2;%9(!-o&Y z;&&4Z1wdF>SfEZ!+6MpJxCI<MlmHM41rQb*0uSo%zst<bip1}R77Bp4u&_}1ZCnCW zRo{h)iE)e3(-Q&${Gq<?err}%Rur1l3kAUA{Q2{LMTAGhvA9mq)YJ?l+%nk~P<D4g z<I~3CGiS~mN8`Xk0a)bf>bfc~H}6S&ViMfAd5ao<+`S7b%I`pWdPXP?+fhdr3IH2b zl7IDTdvr`3^L|}D=yX~Npt8Ia(lauAalQxDXuIh0<;%j%%uJ1=065pKT~lFl2}pv? z612Hs`9(%;ggd2W)RdHz2rphdg8{V$7>wC>;Pd$~K0Xd<X=zSir$WeT0VbLzA#p3s z@HzIQhcq`ohpz5!Iu;1sVDrXJFc)CU9t=#-dvN{wb?NQfw?EheAjVo(5&(BfOM%5= zO^c2d5R=KIO2lL`qY?r%QwCz#9Bwq4;QQ~kL6y85b0pmx%}SVusB8cvgS@JW9zt$l zt5z?}yy;xGHyVwQ5FZcnN(x}fBmny!h)+s}kDVW3@#4i`z)c1R2B5dMm)_KRb9-V1 z5E~l<@(K#T3(YFK04UkSC%}hx1*p|(q**R_ip3yucZXN6-@w?&s6!yE0A%0Dpz3P? z6crUISu8fRwY8Si*VmQ#`7K`-9v+^$Tq^Zi=^p^i&!1!9&2wh_Yyc+Mv^ff@Dk~fY zAWBV5{rSJz+Ac+V`zIW0Q8}m{7cX8c!t(Ri<EDK|m0d3o03>AVBO}lQ6_AmUK>+k$ zxpL(fHk+M-_$8RY_cR*K{*xz9wvr_T01wq|5)5H9Lipq)(VjhfcK@(*=cRz4AZUHx z=1>?&2-bzKg@(tEXdV%f`1rswzvbZU><lWU65hXi2mSq@WhYLYc)*xEnCwi_+P1mi zrKF^6-M(YT&49pQXjim51b}#e@4^RP-=)Cia;Z(H(?OrA4@Sqvz{|@En0VsT#s<TI z1L=$A3o2*-{<OHn<mB?;piubG(cy445D=CswUnxD?vOBrhJ;#qLNp%$r|j(PKSRS- z?-GdI@doyD!1j=tJYfYv?5q6!p{80+layGw#l^+rh+3u9YWE&HcC6yaks~~*RC-D* z_By?O!v^@&)lFkNQ|77)asZdZ0e386KHmksVFaC42kHS0==FN=@bCZze$)8mvEe{^ zx)0ewh>wvvBqR*utbk$dAks160S^ca3<8a20JQi5ve_K^$nbbPde8(uHd>6W(P)_E zVjqbQDB4<~v$F#@xXw>11wX%Kbl<){CA@n160qElWBLC!jf%%6#(>M_(oL}QMKHtk zRdaE10Rb{3d5ngKhrpmWfKVg?i9`Y;NK%7CgVS8>yVRFb@xg-!w_zeO&YnGc3Oynt z^9F-KT~=0hx}>B;j>B#Xfc$)ATtYH*_jJv2Esx6s4wns28XBOdr@L06P&^{`6)RS3 z^!Ap-kPsn7(LTWnK;kWdYIz0e7Xr~ViYfw2sgsvZ2NrT7IywaaJ)lx4XT?<@5W<V* zCa9~c`!z2w?{_o}PfoeU#>TEqP2F3#X-hQLbw611UW_zeQ%M03A|m~wGf8T&l)D}* zd_(#KN<`v(1VCCY@(#=t5xTlsUP)MO4Gz0ts{JAxF1eJKS0js!@irM5m=F4yYaDwE z@~H=sU}$h~+9Z?7LYErh(Zh$@Lx&C#carwYWV6;ICnu+Ni!3^r>*Pe@OD7h)xk1g> z04SIQKp1PL@G$}J)!v1)ef#Fx%pJjh-Ykoz151+vG-(NdbVmW;&xbMre?CY_O(PJ@ z2Nsggo7b<PwWZ|`{1;4tsRopllbxL-UAZzVZ1oy2Ax~J_G4irjRh9u#t;7958%ZiN zq0kwVRuD#$sT-Lq04%R1y=Y-UK?{?`@}?wZo@&n+7RDUL7cT&lv&S9)0jd;L2w!f~ zNpL@-cEVH@kUv$@mV1JweYX{Yg|y}5pJCpg7TT7R+n{n`ej(2^sQ~@tn5^T2r5ffE gQf4}v@8^{N0fxpCu>c)zWdHyG07*qoM6N<$f?{PtRsaA1 diff --git a/Emby.Server.Implementations/Plugins/Malfunction.png b/Emby.Server.Implementations/Plugins/Malfunction.png deleted file mode 100644 index d4726150eb52857ff3ad25462517be0de9187b47..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2091 zcmV+`2-Nq9P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp) z=>Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D2f#^0K~z{rwO46u zRM!>$=FPmB@opS@yx|6?nP3~-;DUh~3sV%OB83v9CO_JwL83qCB30@FiNQ75N!q5$ zB9(+BRcX`~l|m4f6E(qLOaLb~v0~!}jPY(}jF+)J#<RbE=goMLV;E#9M>=}<oqOKB zXZg;#_ZbkKlv8`ZvpLCXIHIT))ntu>cWlT%=EV=c``q~|&WFNkUk@oCKDlOF(@PsQ z&*cv_ZS)ekh2syjrk6KrhkjO+Pn|n);+CXDp0^_NU9rl6yoYze;y(k_t=HLNyo%h7 zPr#mTeTO<~Sao3(&43sMn$40^0Cc`d?Kt`y3plD^j!#D@7)qgzHLSWYie>=4V}w07 zxlJ}-IW~|@3HpP{H&STQH5W+H3<wRl12xXZ6Tp(4fEEbz;>X}@sexlu^78e9Fd;ck zUHSQo8#K+`qiI#PFuS|8&nk;G&MzY~Ckv-&5twvM_;2_<6QRIpAJdRYk?iZ!CrP7Z zZ+JLEXZMvZiVUNYl#qJyg|Yzz{mG%wSEH#>7IRlNmOZ`)IR67m_(}0UaQWz481HX` zL7DA?7)Ru$*x(y?p{Tsh!q;hQ=OZy7`Qo!BBSpXa3lNY6WI+)}NJJXn+g<?%Yx%-) z!hOK<mpSC*ELB}uqZ5Q>>)RE0{djZkfsZ>oBa`!zd~R!adaZNiZ{A?+HdA6IPkA-9 zI^PXkRaj&?82ud2iI{AzF(ai_X#CSJu&T0Na^{p7eSRLAiJvTJWW<atYhw(V*fPe` zn?$|rV3K#4r-3HU>$0SIm~t)11$E=~_{rc_6fuCx2BvDsV?e=Efc=+1#slnwVhra@ z^xP=Sve%ho6I;YwRwGX^LNf;3mUIIYBOk#@I6E}7RsR?5XD-4uzJ$h<6H$z!bRC5o zE8I9LPZ@A$q#IzMN6iQSh?@7SPgJ~J`}6mX)$MPtI_&JK`3U&t4tmAV3odjcqA`tt z;N#9nv;)T*ojZ@z_xH8*jP>%}O;+~-)gM0@dM7C-$DW+B3K;%0Y{WD$=OdY;5d^6g znvTBl!oJeyObUKtfR+{13}>8f|4+C4q5dl8q`vgSgy_+~X4BUji|mwAzSX{M`<9~D z?VHPhu76QO!h1UdxM_%3%G-_0hyTVt(aY=^khZ)KnJbH-CMILF{R+BHokaie&C*RT zT{tHj$%cdE0rFVneUdz+7z|v2BLh)A4ZtXDVwLp$6H6c2j8(gLW96=0_(oYFRPR}! z=UpUag|Kw%R@mZAr@69443Jn!-OO!+L91$*4A(ZN1zcYN++3!PlxkoI!7GPw{+T`G zy$H4+qg&Ux1Hm~^1IywJXqv_k<hZ{zDJAzV+L^F8i<n}7^bP2tv|gQMJP%9Bn$2ka z#Etye@1r2JNgqR%{y~-!4oRkUQpEss)BX)w<MU<Cn!P2P_^!PAL}Bcy^0gHiS*Z_a z6fI|B+9;I>Ol>aA+~`j+EW(lg;Og}u=u1KJ(O4wC=7-vuiP1i0R<=tkhPU5AY$$rI zQi3?%Y;fPEb+*jRl<LnaOM>h3QYUg(*!Sc=`Ve8+#1wdFCc9r^E|6MGUQO68<${#S z3R4jg3@~G@CmmScQo?$o=cO^QH!MTz=^-|^hcIzN#h1rFLiHCncJs@CK+M+oOsVtR zzy2|AKE$B3QpuHX7?|j0_(zy2-iEAp47Ogw#NaRj9v_l&GLV{o50_wW$5~NQqO7%! zPaH@)a6jU^E%?#8Nq8BQ|C}&kU`GfYv1j2|ERMg{^;W)ny89&e?&mZe)M3c-8E)V} zhkb-e)(rUk>A3XXQFJ)nr<?oS^)geK9ltg=qp7Um(Fb5oVAu5Y!{hS6c}+oXQaZ5y z3-}DF;Z+JoU^~AAJzE#y@mJ4nZ*$zdOz91>*f&Ljbb@5|=29T>S?D^}fVwY--uTtu zTMkh;9-hOIN7iJmsIaI93wL~vs!p`kUdOjawgI0ratT&=i=?<naRgn*APO80;?3=Y zuWa1kw1!eaq9z%P5F=m|pwS2&a8gpVkLVri9RxQ&NTqA!t_WZKcYXiav5}kC11=Yw z%^nyN@)6t1OVU~g;Id$B%&#-dTxW$7F`XmG%3odZ!EcLr+J(KGF+k3Ey_6z=k|&Q{ zuah+$ZqGy!2nfAN3CneCC<w!dk6`Qk)QP+v0<)Lhyq%5JqoDSZ5w+6X@1YUhJlY!v zv9u~1DT#?MQmS9)BL>hI0}YT`l_OOZ&m{tERp~LX#HjpQKVfD!D?v^uF;*?;zHkM3 zUByriGeGnlZLE&F1E{<|8_(wCaAO+OMVSPAqz88I8k~Bnn7v(KOH!n!&Ga*lcgeYI z3L-Tx9kmtf{!CSxG)=~uigo)^^V8wJ?n2W42#vdGUk>dOWL>r5=|B%E+`P;V(3yNX zC}qmRTU0%Y#02veYQ;z%Yz@zswJRYlJ~VTJO_LlZ3hm_i)?Zv+%NXnF5Q=MfVMCj0 zR5HEZN&Y3#LHS-k-$=YKMn*7Bm=Lstpcy$YayqQ=qO<z<=h8$cnamCYx;y>NT#~LO z2NvNyT?K3yV0@8Ao>fhEOoFEl*^u!8fBGObcsr6)Qc7p)wjtliPYIL0AmTch_&>mp Vv#07tKs^8e002ovPDHLkV1ly-^R)l~ diff --git a/Emby.Server.Implementations/Plugins/NotSupported.png b/Emby.Server.Implementations/Plugins/NotSupported.png deleted file mode 100644 index a13c1f7c1c03605a5d7e0afdc6f4a81621330ab2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2046 zcmV<a2LbqrP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000NYNkl<Zc-pmB zdr(x@8UNj77Zz8_`)y(<@=^#dd4+`qnoP))M3RWM(~;U4r~RWE+Qc|&ND)C}<0R2& zgH6(O8cjwsj;WT0#GnBJEU#VV5d@KkAjsmnBF|m+ar@o9H?kJO`VVL3gL}Vo?stCY z_dU+H4D1ilcZDfAu2SZ#Na7?BOJy)j+%--Zurae#Sx)noN3ijegR!^y*SnK8__@o@ zh3D>qliy>cVqq8^Lf84jXzRbXHoxpjmsPn;0Hn?PQ*K6WF7k0Q)&K*4=l2RP#>Du~ z&{=*$nX*rrLCU%10^qLNpR9}9`2}z}miUm-{=~TJI_SOr4E1M4-KiywiL`EFxd8a6 z_NQp#w*M1QZ=!SFht=gCNieu?L-VPk8)+qtNu<;*7XYt{T?uDmpV^e<8$_q?KEMNr zF2i7BJ({X3KgoMv{TeC9mkWT4n@ke=U14fV%#M>lRXnfFXhF;2myuB197%8eBs0qe zKui+QRFu#k`}<=e@wGny`Vj)4BmlqW0B~t>o5XDUQSCmtyL?~my+;KgQ6E%{!EAK1 zSQe%<OFC!IK&;#H2B3U_|0Lmabf5bWlOsJ~L?YYO*1ygkKA4*vN9^A3onR+JH~?<y zlBe#)zFr2HI0K@GiQ!Z%z4yEeXsh`-mrx+`ZF*$?k3*Kv65_4%<2P~ae0$J|%7FoU z0DM}ClQr?L9VhN`NaIK%vY7@CiV^d|=~xqq5eteSw>fJ7<mFJk^GB>NYV;?q21^vG zc>u4z2Q>VOG{hR?AWS(3VCb1)Yyfd5UBsppz$}n-3aWPt2tb3M0KgstDa61b3a5*J zYz?`Bf_k!>vRg@qG|r#g?jQgb0ucWZ0oX|Zl)j`KvkO37nyQK2@g_8lHJBLehe)~t zo@>^@EhGr&{SYu{ZCJ4fKo7*ePXKm5I)E#0DKrie2|D_;|2eN7tB43(`FK`@`|lo) zj`v-il?7ZsLWV6iv9SaIE(W6i3iXk{Ail8vkpOt?+ZdjAwsB;*V`$<Qy-$%yNW3a{ zC;THm_oWawcXFey$-XN@6c-}Ox|kANd9N68uh((_?lv9HD3yTChnWp9nb;c5#N4)= zw;OMO&o4+xTm{QqMKgfUMUTB3LSEeZeC)B190hRmG_8;<4uBE9pah!innr(>AMRAQ zK_qeD<DZCeiS$Oqj$C@MpzoV+F>+^Go_(mHp0W8{So&Z{3v)xW^Pi9TG9*V144qpX zfRHSZGU)kOi`(Bbc;dOI;TatTu}o&QYMPmWuB{CN6%|<ZLNr!yNkZ$%Gp4vbH7-j< zm83K;ENj!VQD2ATqyi&fE$#vlzj^1;QH)=gA?B6sF!r>;&{PA{o!izWVsC#)6VoAH z6N%PiM-lLB7{-}?#O$p0SPFpC<vq!#BNU0be(PMwlWHLoY>sX%<P0WzW^m=L3B>Oz zfT8>}Ov3}j3W5ExOmhKjHbETt1f)5eDL#(ES?-AVgLS@~3CF94G7M%jJ9dB8xHYS^ z{+pw}jgmeYDBJ7n@AXE+CaVA1N;05d=zcCMoJD9Y9e`(8E?h>tVC<z1&B0;u!eur? z5*&`{RS~#x>5FMaMf=aW74GT->AH~T<hZ45!_=4#VyP3{gI8g-B89@T1DK}d5IfUm zRM;H7c*90&PV_@WzX=zgxeEENSD^p*zrfN-S+f}nt1m+YI*=E|Sn={!G?aaS%!X@L z2B_<iYvNx04H=})N=$THsMgO>lQTU?8_})m97r35K-<}eX{`<>{Ty5$^MhApFzLr| zG4V7Mn|}$tsur&2Tb4?D+~2UC;vo&nuP!39zSCDI#d1yjpYo_`*9x@R(C6rmIa2_B zI8%v!%~VzU@Khr=6BW2JIViwI5xp%Nmoh&=+SAFH8|;P4+1e!mOm39JF=!2xN)<Be zI&1;F1l&<Qyg5gsTNrx2Y(Yg$@9~0@9iMVGgvph8$pJC@x5a!ke7p}&#f6faO;m|z z>9RB}ysRiDIQm6WXL5xEja_}ntZlaiKv%Jj0*JLKw+z>SMo?Y9fc3?7(WDv1eEY>U z8-B`z>6aa@nfwE1W$^ZKgN6LhT7zyu2oMGaBFYZ!_<c0@4yiXZbY{;3D99!U^$W$3 z;ZILU4YMw2{j6>(skkm2eEVgYHwmwrB6(G4T=3eS5;c;Os6`Zu=<t@s2!KeqOPbrS z;ncur{@?mWE(ie9h=E^F&}kk<&dthv&{|fFnB7&2T`Zoel5}m{_B8Z<pu$-BD3TJR zsbF#-SgY`xGgg6xMN7vI=+;eK*wWHnKvN_9bzG9JiQP%{e$KoQ0G(*~+aC0)ZhfvO zsmsTF1L|<8F!f0Alm6RRzqppxG3bBiDn`!TL}+LbynQKMC1QRh#e`O?#f^bM+I;fA zTh-V1koG1QPdoz$6ulw~yV7D=*yULLMj$A=M-ui{hk?H>xgl#gn9)Ne$DcJ@IDV;_ zVqm^!hW`2t=5Fa9#54EruF2eX;kNF?r-Ng)LM(B=a?IAIlq85NNcicymckm;m0-{& z3#ed#Ys<aCx9>|0vjCj4!TpMw{*g&*HRnzP>t(v+FbEl76yCY-RtVW(Z*bId?fI<m c{R6812UxKZ7X$tn8UO$Q07*qoM6N<$f>PAuAOHXW diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 07b7297482..cf25ccf485 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -1,7 +1,6 @@ #nullable enable using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -23,8 +22,6 @@ namespace Emby.Server.Implementations /// </summary> public class PluginManager : IPluginManager { - private const int OffsetFromTopRightCorner = 38; - private readonly string _pluginsPath; private readonly Version _appVersion; private readonly JsonSerializerOptions _jsonOptions; diff --git a/Emby.Server.Implementations/Plugins/RestartRequired.png b/Emby.Server.Implementations/Plugins/RestartRequired.png deleted file mode 100644 index 65fd102a2ca7ffb99c7843fa46b1c5274ec0e76b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1996 zcmV;-2Q&DIP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000M*Nkl<Zc-pmB zeN>cX7XQr`GXw;Kd?{+jT}C0~W0?5L5s0=A&*Dm@R@;$vPaQpbjN?|W8G<l?rc$hC zyOz~frX8$SqAbk-fdyf3X58=-5&2TqK|~lp83yLv`_B6k!-ow2@SJlw^W5is?)^RY zx%c;61aLfrr_y7S++~7qgc7MlEOUX`blYMwW94JH)yHVvIt?559Rf$rPi%=^;U{-F z8koEpQonhmVqm`6hRa2HsB60OaLWF(mu<=!0w6n+9orJ}e5Q}oQUNr7$oUG?z|{R9 zE*|@!IyS31fs}(Y1wgLPj_Hcn^c7I5q<FZHe~P$!Fb2F{gW+&y{gNDQ6n$r!DF8nD z>{w&OtDgdf)pX7t*sk0&8fN(`ICCiT>e3u-G%34g3V_$~&5=ixPpnS#T|lR=-_8LD z+mBZ5Y1Eb%|7+EIhBrvrJyQVOJX|CTPo*!>g{OW2l&Lsvf)2X8=MbqmvzTU0BzI>D zfS6=XZDwSXa@{_m_|ke{pq&6z6Mz?40Bl+Ok7U?>Q)QM~uFk5wGhF}@!;bh43|l;` z)`=y}kj{CQKZ4h61*-qRZHfF6^+yk&x4i)Zq0s(o+h1o-9}M<(Lz(s;DI8P?3&6vW z^XMJr-}VDTtO4QJz_2QY<_-BkXF0d#wh&mnn|?CmV#sh+LUFtJaR&Akom=ohadWdH z06scRj8XN*`xLt*(m0U_?UuoT5{Nlrb<7Zn1rtb+b<UUp^)cw*-GE0jwX;cU#1up| z3gGp>12r#@hN31A@k=5e4E+`e>;SPRoy4XMz&#-P5cK&Q2|$e>55Q3bVkrVUDV<IN zE&+5El+?ZTRNd8dNXzKS9S#CuB><|A2*4%+Q0+^~4u=2?xl4@7)C?H46)?3nK`46w zvjT$Qp;!Pk9stapc2RKzU;t3QM*y}=AHdnS<BcMT1m~}HeqUthI3DEhIzKT;{^$8& zD&L0^6M-vx$gtHeH>LtWIS{ss0Ax%XfM?dqz*XO9+i#q2GhL^7ABlv-t9VP~C#vLU z6&`ZB#;)3FTm=tcaW-`CW)V-+umEmrHA{0vLMBDPFmr|(L4~o;^2+i&?NxB~1sRDu zZ<%E@vS6!4&$JbaXVxxP?o%Yi11$ygg~R~>N=z%2ec+q8a^!Q|yLl5*krTW_LNF^l z9B_4msj(i-r%KS?byvM?SIy~>)E08P$JCW9J$d2NDa*qP6-jEK?dbFXFhq(nN`Akm zD4~52zGoRiy}WTSZUs@&O*&Q#%)M^7@b%Y2s*FmvsjNwIS1n3h{Zz;aMbZ+W{m03# zKrk{F@Mqx3h$ShB6QT;g#}mJyR^pZrhadkvS78C`VaVSL)wU|nsQ^ez--;;+ijPY6 z3wEQMH1L&Rmp&{Fv%)5)U=mYeF`^3!@JY&B_^j$}cnta=Jt_v6zY=Hj4<KS&r7ye7 z>AyP@%)`S>N6$UW+Qi(`KkfZfh%D6KCCzuX*Vdrb#Q&Ye^xO=LJ3LLq66DmD<KIoU zFup!mJhsB6Kz#bL2A%zv@U5W$vjhrkRc%1skwQyYM)_RUq};GQu1m2@jqBBQ=<Dc$ zSSE%1w{!7Od@QBqd7z()L+nhi4Bf4h7w3G4njni2;Rip*x2XqUvV2F{iC4rBZ96ef zqO3j@!Tu>Isyhf=@`S6_?=PBT7r(OcfIeGojClPedTPn2n8Ix(t{<c(r@xh)(5vd~ zPl=^K=f!L2@9e_Rz#u&5&w)HF2&%p7aA^GwlsBY7fQc!}@WC3np<w^D__6LYl<M(A zjRr69RIE0t{<?}-yOK9yXUa*A!J#?0aHJSb#=f$1H~O^fO6c4NW5WEs;-9x1$3NF@ zfUfNylL8n~jHIYkEQODI0QMfefS)$Q-44LBz%Bh)=j;}bMQAA0;dn*k`y0PFPw_)9 zzv%kM=y_p{$!#C+PI(6P9fkKTP{ul%7nGN1rJkmu3S}iZc+L(0J;hzr;xl&XBw!oR zAfnap@Q9`=j5Iee+J3RkhTo&RaVc|66xw@gC#_EQ(Hyq$ML}8FOzBiwf{Kb=NF`O% zD1ePm13gVVIr0G$NnpO`hF=a>^+ju{0>QOkBV=XU`_gu){t9FEXIljD{RvyGB08yv ztyI##{2~XWr3EPY+2;H;`iv3`-8_J$6oJPn>5OAr2X>X%?3exJ2;WjR*~8*}Is11V zi`EfSO78LmL|SKWG`>@UfNdvN#O*}Ux;4Pn20Hl<<UH?J=WNe7%st0BaYp4P;`_nj zi2%ex-1xZxjr!|f#^+R}V6*`hm8Prr1cds%I&b;IRF+mQHa2Dv;apxhLNm%@;@&~c zlSHHyCAfVu9mLOQ8FBt=7<Jp@8--TJ)oPvC<p}69g#=;<OnYQn`66(yB|BVnI}#cw z+Ow_XoU!YWghICNL_HDdr_>4gI485fbmC3W9pf5Fr`;jArj%p>OGvo?OEbi8Y_+Qb zA`Gx?xi`4>eN5tm`){e6w=3oo_!fy}e3i0KoC_N`Og+qe1&kPA_dUQ@!(?NS|5n1! e`^P(H$NvG|Dd5z6`yu`S0000<MNUMnLSTZEn#wZ( diff --git a/Emby.Server.Implementations/Plugins/Superceded.png b/Emby.Server.Implementations/Plugins/Superceded.png deleted file mode 100644 index 251e70535b861efd0401761c5eaa0c8d546748e5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2136 zcmV-e2&eanP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000OdNkl<Zc-pmB zc~p~E7XKwA5DJt8si4$_Vicq<At0bAlsP@(9Bk==w$*9XnbA&Npe`MYS`geu(LwYS zEmUo*9<2_YDq7p&2q=m{5;tT~0a-+YEJ6qn0?FK$e3mE*_7A>uUe5R3_wKvDci;W} z-U|=?Km4q<f#HrK-f_OrMko;3LD$ltZ_(lXH#X#DP`}{?=6LSI>o543)&6h0O6<}- zBffx*>o77Ip?gq`lApKXdPURNk5jIcn2ZAiKy*1iuyWk&*uggXbHLrb=2)KV(emhJ z6lLtm3yjMPA!Fx20gx!;0~&o+{s^3vQ9kS_K4sj|8y(J{Lv<*&bV`C^5{+vaC;)?% z@quceCHn!@ELvwXOk3{c51r(1xO_17&eQ~jKN%Yb3V`!3U-%uBy*Vq?#hq4Py3q_^ zLJF!B7m=Tnxi2zVwStU~1`2?K*iJY)YweVRiA#R~vgKxLNC67Ay$8SbmtUu^3TkZw z1wcS;Xnw3;g>2z2zMyy!&{0bO@(93(3;?6WeQMp7PPuVGlAyTUrWXYuRBZ~bL$_XR zF!ZLhk!-eu+~EC}H9+25W*5K1C{6zcn%djo@%fgcO~1BIgVCvZ1X;{^8}!2v20*Mz znA{{=l>&6J3HVPYhMA1?eR~H`pJVQG7!AC>m0pcc<<Mwm3FWOQZ7q`0uZ>L2s;=ZZ zt*>p((iyuuG4adkzXN0LgA3LNsO2kmQ|`jaVoi;2fe&U-Jb}3}o3V?U9=$}61vlz| zpbV(Ce+GGM{t&XNS(b}8<>>6arO>psqOI^6d^bj#K=c4u{%_#Y2Q)v~c~)F-D-I03 z^LQ43*h-%vekK6zK)^u)u#5mGT*=yW;Ls6WOM5eBScgK>u0?BG2Sk;{n3Oc%h64~t z8Q4PQ^c!F|infA^T2o5w&Z9-@dsg1>LjVi}z&DiuEN1|Qr5!#|9VqjJSmJ=R@Ao5& z|0bH-+u(4&1c6^Kaxwu>ZJ45#EnNq-;v8D4D!>=Lgh8XcA(pxWW#0h0dW)>|2cQFx zB}2Jw71ebM?)dG-RR3`(FS~`3(o&SxRAJ5o5BTo=B!C=lnE+hb9IUny3Q<^IfAVKl z-7j8l_QONHB=d()kh_cs4W(g8G_k>=Hu?a-YHR#foQqwIX^Y<j+~#8Up&Q`qwJ0jO zi7ufn_9n(pgIPc77yzfZ_dO$zD{Ai*R=3p9cPlFzYR;Lf{l1k)yekz;sE!)*``-#a z)rD0TvVUks$dY$SK^6dtIAYK-EWNuP9a;@OviWb$fr||*zt6pQ{c#bBs5x>oGey&J zTy%<gTl&ttnX+Bd@L-_w2#pXv9{}?Z7?Ay4BSIEOQ1E%A8wr%X6XasRp8VnXG${t! z(pxCYI*WS^+9`kjmm=?RY4bV8Tk=Y@Hez(x$1^AXBn=M&s?(nh;IX$A1>g6O3qGHM z$5Zf=rU6O$qYxc8j?PR<uu}kZnwN3&*s(78x?G38s!F&aa!lx~>Eq5w!>0hXr+aU~ z@4=18PQ6EIf9Dy&rHEcFp}dk>cXylhWAvv`?ns93R~MZ60$_9Y%YY+Z!IL6fy&ZrC z6~_dN=vG|ty;V;IKVj<MneTz9m_ZbrlH1KQYX^@2xPJs?QW^u`!T?xb-4def?l#sn zx9jJHZn*gC&QHdP#=F_YxD0V#<28%)zdn;D=y)>weEJaZkeyP_1-IC9>Px=tfn|H5 z01_T(DD{tS(i~J`PUE>PI89q{-i=KuQEi;oD4h|6n!M|1t!sopWCMxEs~8a+NM%_F zXlVk0EuAtXY}T)s({9ipd&?;b&ZuS)oKPk!J@DadIn8&C%0_@8KHhMV)5$HehW1V+ z?);jIlLfUa)*UN3VA26)e305_`5ZcG>1HLMbQ?(PJL!_6tpfCPs@l4dvlR8k<<LHC zL{~>AYE*>?W;{2gJ%QVEV5j0WM5Qgnl}-EM^HuH)k&w^(ahW{E&Cw=^^>=m~8~2^B zS(AFU@_+PM%SmyNS{@xq$3`w!Sr)o)EkS43P!t`_MA?JZ%$$;joDY2L6DBXDv=3Qe z5u6H6;eqH)B;}5ipiDdp-`HGF>S$+_=BUo9M#}_<YwZ>QNH`uUpA62JDISB{KNa9~ zPT9`rgN26|O?M4i_0NB7_n5YXZb+Y#$ec1!AxS}0+cK64j$}maLq(R(0Jy+>U$kXK z&2dK0=?y!MjTQjtC~l-HzR^N%dF%q}MU*)S-}SlU*<@$GU3~kE1>0=9D(F8+@o@;M zGAZp+L~Wl;YojeR5Y;4}1R&!vfVw`Ih8_S>VL)>Qhlyuiy_FEUb_ZNLctPVIe_`yd z&%DCs%neVKjPOO*gA!cN%g3dw5ApYv!4QgxCAxOApQAgJJJ0+P08=Rgf1(wrpZt%* zdhG_|MoJFGug)G3y<kR>qw`R^WnuP6|IcsQBU#m(6KBiTP5A3%8=jTcyn2(*E0lpO z0&xDt0H_kCsb#bZD$(8mgnXzoZ{gDArn_I?a2xrWb-A9`a(hS0nfs@XF7=%oICbR0 zVKcpYd`-$?g)50U@L6~61v9WQxQuTw+8YeLZ#hhFh`u;pKL)o-u5Lb<Q9zoEdRD>8 zO(7Slf2cukAd&0w<&)9C=V@jpD#qMz>bTz@05LUpCP;YxS<7bc;3}Fm4a`UOtJIvi z_ov6RYdJgf`~1_w<DBhS;?Vcg1v97Fac$uIUV@ok&w3cm80YnUP5OVqj#1y3_noHz O0000<MNUMnLSTZte-C;9 diff --git a/Emby.Server.Implementations/Plugins/blank.png b/Emby.Server.Implementations/Plugins/blank.png deleted file mode 100644 index f81ae32438880c574cd298bff484e6b2d72e3ca7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 120 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1|;Q0k92}K#X;^)4C~IxyaaMs(j9#r85lP9 zbN@+X1@buyJR*x382Ao>Fr%o3R|8Ox*VDx@L?S#n0SJIxRtCl{<HtY-1B0ilpUXO@ GgeCwzs~B_u diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 36e37b7ad0..c84dc6a130 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -167,7 +167,7 @@ namespace Jellyfin.Api.Controllers } /// <summary> - /// Uninstalls a plugin. + /// Uninstalls a plugin by version. /// </summary> /// <param name="pluginId">Plugin id.</param> /// <param name="version">Plugin version.</param> @@ -178,7 +178,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) + public ActionResult UninstallPluginByVersion([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) { @@ -189,6 +189,35 @@ namespace Jellyfin.Api.Controllers return NoContent(); } + /// <summary> + /// Uninstalls a plugin. + /// </summary> + /// <param name="pluginId">Plugin id.</param> + /// <response code="204">Plugin uninstalled.</response> + /// <response code="404">Plugin not found.</response> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + [HttpDelete("{pluginId}")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [Obsolete("Please use the UninstallByVersion API.")] + public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId) + { + // If no version is given, return the current instance. + var plugins = _pluginManager.Plugins.Where(p => p.Id.Equals(pluginId)); + + // Select the un-instanced one first. + var plugin = plugins.FirstOrDefault(p => p.Instance != null); + if (plugin == null) + { + // Then by the status. + plugin = plugins.OrderBy(p => p.Manifest.Status).FirstOrDefault(); + } + + _installationManager.UninstallPlugin(plugin!); + return NoContent(); + } + /// <summary> /// Gets plugin configuration. /// </summary> @@ -281,33 +310,6 @@ namespace Jellyfin.Api.Controllers return PhysicalFile(imgPath, MimeTypes.GetMimeType(imgPath)); } - /// <summary> - /// Gets a plugin's status image. - /// </summary> - /// <param name="pluginId">Plugin id.</param> - /// <param name="version">Plugin version.</param> - /// <response code="200">Plugin image returned.</response> - /// <returns>Plugin's image.</returns> - [HttpGet("{pluginId}/{version}/StatusImage")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesImageFile] - [AllowAnonymous] - public ActionResult GetPluginStatusImage([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) - { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) - { - return NotFound(); - } - - // Icons from http://www.fatcow.com/free-icons - var status = plugin!.Manifest.Status; - - var type = _pluginManager.GetType(); - var stream = type.Assembly.GetManifestResourceStream($"{type.Namespace}.Plugins.{status}.png"); - return File(stream, "image/png"); - } - /// <summary> /// Gets a plugin's manifest. /// </summary> From 208d545cfefd5ce7a2092f4ac669e58cae115d37 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 10:05:04 +0000 Subject: [PATCH 0742/1930] Changed as suggested. --- .../Plugins/PluginManager.cs | 27 ++++++++------- .../Updates/InstallationManager.cs | 3 +- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- MediaBrowser.Common/Json/JsonDefaults.cs | 1 + MediaBrowser.Model/Plugins/PluginStatus.cs | 33 +++++++++++++++++-- 5 files changed, 50 insertions(+), 16 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index cf25ccf485..010d2829c4 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -53,9 +53,7 @@ namespace Emby.Server.Implementations _logger = loggerfactory.CreateLogger<PluginManager>(); _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); - _jsonOptions = JsonDefaults.GetOptions(); - _jsonOptions.PropertyNameCaseInsensitive = true; - _jsonOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + _jsonOptions = JsonDefaults.GetCamelCaseOptions(); _config = config; _appHost = appHost; _imagesPath = imagesPath; @@ -137,7 +135,8 @@ namespace Emby.Server.Implementations var plugin = GetPluginByType(pluginServiceRegistrator.Assembly.GetType()); if (plugin == null) { - throw new NullReferenceException(); + _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName); + continue; } CheckIfStillSuperceded(plugin); @@ -440,6 +439,7 @@ namespace Emby.Server.Implementations plugin.Instance = (IPlugin)instance; var manifest = plugin.Manifest; var pluginStr = plugin.Instance.Version.ToString(); + bool changed = false; if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)) { // If a plugin without a manifest failed to load due to an external issue (eg config), @@ -447,10 +447,16 @@ namespace Emby.Server.Implementations manifest.Version = pluginStr; manifest.Name = plugin.Instance.Name; manifest.Description = plugin.Instance.Description; + changed = true; } + changed = changed || manifest.Status != PluginStatus.Active; manifest.Status = PluginStatus.Active; - SaveManifest(manifest, plugin.Path); + + if (changed) + { + SaveManifest(manifest, plugin.Path); + } } _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version); @@ -577,8 +583,6 @@ namespace Emby.Server.Implementations } // Auto-create a plugin manifest, so we can disable it, if it fails to load. - // NOTE: This Plugin is marked as valid for two upgrades, at which point, it can be assumed the - // code base will have changed sufficiently to make it invalid. manifest = new PluginManifest { Status = PluginStatus.RestartRequired, @@ -586,7 +590,6 @@ namespace Emby.Server.Implementations AutoUpdate = false, Guid = metafile.GetMD5(), TargetAbi = _appVersion.ToString(), - MaxAbi = _nextVersion.ToString(), Version = version.ToString() }; @@ -678,9 +681,11 @@ namespace Emby.Server.Implementations continue; } - manifest.Status = PluginStatus.DeleteOnStartup; - - SaveManifest(manifest, entry.Path); + if (manifest.Status != PluginStatus.DeleteOnStartup) + { + manifest.Status = PluginStatus.DeleteOnStartup; + SaveManifest(manifest, entry.Path); + } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 75a9ca0801..b7bbbd3482 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -93,8 +93,7 @@ namespace Emby.Server.Implementations.Updates _httpClientFactory = httpClientFactory; _config = config; _zipClient = zipClient; - _jsonSerializerOptions = JsonDefaults.GetOptions(); - _jsonSerializerOptions.PropertyNameCaseInsensitive = true; + _jsonSerializerOptions = JsonDefaults.GetCamelCaseOptions(); _pluginManager = pluginManager; } diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index c84dc6a130..eb6b770d67 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -47,7 +47,7 @@ namespace Jellyfin.Api.Controllers { _installationManager = installationManager; _pluginManager = pluginManager; - _serializerOptions = JsonDefaults.GetOptions(); + _serializerOptions = JsonDefaults.GetCamelCaseOptions(); _config = config; } diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index b76edd2bc7..50393b909a 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -56,6 +56,7 @@ namespace MediaBrowser.Common.Json { var options = GetOptions(); options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + options.PropertyNameCaseInsensitive = true; return options; } diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs index a953206e89..2acc56811e 100644 --- a/MediaBrowser.Model/Plugins/PluginStatus.cs +++ b/MediaBrowser.Model/Plugins/PluginStatus.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member -#pragma warning disable SA1602 // Enumeration items should be documented namespace MediaBrowser.Model.Plugins { /// <summary> @@ -7,12 +5,43 @@ namespace MediaBrowser.Model.Plugins /// </summary> public enum PluginStatus { + /// <summary> + /// This plugin requires a restart in order for it to load. This is a memory only status. + /// The actual status of the plugin after reload is present in the manifest. + /// eg. A disabled plugin will still be active until the next restart, and so will have a memory status of RestartRequired, + /// but a disk manifest status of Disabled. + /// </summary> RestartRequired = 1, + + /// <summary> + /// This plugin is currently running. + /// </summary> Active = 0, + + /// <summary> + /// This plugin has been marked as disabled. + /// </summary> Disabled = -1, + + /// <summary> + /// This plugin does not meet the TargetAbi / MaxAbi requirements. + /// </summary> NotSupported = -2, + + /// <summary> + /// This plugin caused an error when instantiated. (Either DI loop, or exception) + /// </summary> Malfunction = -3, + + /// <summary> + /// This plugin has been superceded by another version. + /// </summary> Superceded = -4, + + /// <summary> + /// An attempt to remove this plugin from disk will happen at every restart. + /// It will not be loaded, if unable to do so. + /// </summary> DeleteOnStartup = -5 } } From c761cbff0e2d8bbf6b348db09c664760c4ccd1eb Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 10:20:28 +0000 Subject: [PATCH 0743/1930] more changes. --- MediaBrowser.Model/Plugins/PluginInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Model/Plugins/PluginInfo.cs b/MediaBrowser.Model/Plugins/PluginInfo.cs index 52c99b9c3e..25216610d4 100644 --- a/MediaBrowser.Model/Plugins/PluginInfo.cs +++ b/MediaBrowser.Model/Plugins/PluginInfo.cs @@ -20,9 +20,9 @@ namespace MediaBrowser.Model.Plugins public PluginInfo(string name, Version version, string description, Guid id, bool canUninstall) { Name = name; - Version = version?.ToString() ?? throw new ArgumentNullException(nameof(version)); + Version = version; Description = description; - Id = id.ToString(); + Id = id; CanUninstall = canUninstall; } @@ -34,7 +34,7 @@ namespace MediaBrowser.Model.Plugins /// <summary> /// Gets or sets the version. /// </summary> - public string Version { get; set; } + public Version Version { get; set; } /// <summary> /// Gets or sets the name of the configuration file. @@ -49,7 +49,7 @@ namespace MediaBrowser.Model.Plugins /// <summary> /// Gets or sets the unique id. /// </summary> - public string Id { get; set; } + public Guid Id { get; set; } /// <summary> /// Gets or sets a value indicating whether the plugin can be uninstalled. From eb2439f23b05a9b92a81ee96c7801d10ccfbb25d Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 16:37:11 +0000 Subject: [PATCH 0744/1930] Changes as recommended. --- .../ApplicationHost.cs | 2 +- .../Plugins/PluginManager.cs | 59 ++++++++----------- .../Updates/InstallationManager.cs | 15 +---- Jellyfin.Api/Controllers/PackageController.cs | 2 - MediaBrowser.Common/Plugins/LocalPlugin.cs | 5 -- MediaBrowser.Model/Updates/PackageInfo.cs | 9 +++ 6 files changed, 35 insertions(+), 57 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 17cccdaf92..216cb5e758 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -396,7 +396,7 @@ namespace Emby.Server.Implementations Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName); foreach (var entry in _creatingInstances) { - Logger.LogError("Called from: {stack}", entry.FullName); + Logger.LogError("Called from: {TypeName}", entry.FullName); } _pluginManager.FailPlugin(type.Assembly); diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 010d2829c4..944b746528 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -96,9 +96,10 @@ namespace Emby.Server.Implementations foreach (var file in plugin.DllFiles) { + Assembly assembly; try { - plugin.Assembly = Assembly.LoadFrom(file); + assembly = Assembly.LoadFrom(file); } catch (FileLoadException ex) { @@ -107,8 +108,8 @@ namespace Emby.Server.Implementations continue; } - _logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugin.Assembly.FullName, file); - yield return plugin.Assembly; + _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file); + yield return assembly; } } } @@ -203,6 +204,7 @@ namespace Emby.Server.Implementations return true; } + _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path); // Unable to delete, so disable. return ChangePluginState(plugin, PluginStatus.DeleteOnStartup); } @@ -310,10 +312,7 @@ namespace Emby.Server.Implementations throw new ArgumentNullException(nameof(assembly)); } - var plugin = _plugins.Where( - p => assembly.Equals(p.Assembly) - || string.Equals(assembly.Location, assembly.Location, StringComparison.OrdinalIgnoreCase)) - .FirstOrDefault(); + var plugin = _plugins.Where(p => p.DllFiles.Contains(assembly.Location)).FirstOrDefault(); if (plugin == null) { // A plugin's assembly didn't cause this issue, so ignore it. @@ -366,20 +365,7 @@ namespace Emby.Server.Implementations } plugin.Manifest.Status = state; - SaveManifest(plugin.Manifest, plugin.Path); - try - { - var data = JsonSerializer.Serialize(plugin.Manifest, _jsonOptions); - File.WriteAllText(Path.Combine(plugin.Path, "meta.json"), data, Encoding.UTF8); - return true; - } -#pragma warning disable CA1031 // Do not catch general exception types - catch (Exception e) -#pragma warning restore CA1031 // Do not catch general exception types - { - _logger.LogWarning(e, "Unable to disable plugin {Path}", plugin.Path); - return false; - } + return SaveManifest(plugin.Manifest, plugin.Path); } /// <summary> @@ -509,15 +495,14 @@ namespace Emby.Server.Implementations // Attempt a cleanup of old folders. try { - _logger.LogDebug("Deleting {Path}", plugin.Path); Directory.Delete(plugin.Path, true); + _logger.LogDebug("Deleted {Path}", plugin.Path); _plugins.Remove(plugin); } #pragma warning disable CA1031 // Do not catch general exception types - catch (Exception e) + catch #pragma warning restore CA1031 // Do not catch general exception types { - _logger.LogWarning(e, "Unable to delete {Path}", plugin.Path); return false; } @@ -670,21 +655,23 @@ namespace Emby.Server.Implementations _logger.LogWarning(e, "Unable to delete {Path}", path); } - versions.RemoveAt(x); - } - - if (!cleaned) - { - if (manifest == null) + if (cleaned) { - _logger.LogWarning("Unable to disable plugin {Path}", entry.Path); - continue; + versions.RemoveAt(x); } - - if (manifest.Status != PluginStatus.DeleteOnStartup) + else { - manifest.Status = PluginStatus.DeleteOnStartup; - SaveManifest(manifest, entry.Path); + if (manifest == null) + { + _logger.LogWarning("Unable to disable plugin {Path}", entry.Path); + continue; + } + + if (manifest.Status != PluginStatus.DeleteOnStartup) + { + manifest.Status = PluginStatus.DeleteOnStartup; + SaveManifest(manifest, entry.Path); + } } } } diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index b7bbbd3482..fc80bdd756 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Security.Cryptography; -using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -106,18 +105,8 @@ namespace Emby.Server.Implementations.Updates try { List<PackageInfo>? packages; - var uri = new Uri(manifest); - if (uri.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - packages = await _httpClientFactory.CreateClient(NamedClient.Default) - .GetFromJsonAsync<List<PackageInfo>>(uri, _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); - } - else - { - // Local Packages - var data = File.ReadAllText(manifest, Encoding.UTF8); - packages = JsonSerializer.Deserialize<List<PackageInfo>>(data, _jsonSerializerOptions); - } + packages = await _httpClientFactory.CreateClient(NamedClient.Default) + .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); if (packages == null) { diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 906188026b..9ab8e0bdcf 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -44,7 +44,6 @@ namespace Jellyfin.Api.Controllers /// <returns>A <see cref="PackageInfo"/> containing package information.</returns> [HttpGet("Packages/{name}")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<ActionResult<PackageInfo>> GetPackageInfo( [FromRoute, Required] string name, [FromQuery] Guid? assemblyGuid) @@ -71,7 +70,6 @@ namespace Jellyfin.Api.Controllers /// <returns>An <see cref="PackageInfo"/> containing available packages information.</returns> [HttpGet("Packages")] [ProducesResponseType(StatusCodes.Status200OK)] - [Produces(JsonDefaults.CamelCaseMediaType)] public async Task<IEnumerable<PackageInfo>> GetPackages() { IEnumerable<PackageInfo> packages = await _installationManager.GetAvailablePackages().ConfigureAwait(false); diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index ef9ab7a7dc..e48ebbfa5c 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -80,11 +80,6 @@ namespace MediaBrowser.Common.Plugins /// </summary> public PluginManifest Manifest { get; } - /// <summary> - /// Gets or sets a value indicating the assembly of the plugin. - /// </summary> - public Assembly? Assembly { get; set; } - /// <summary> /// Compare two <see cref="LocalPlugin"/>. /// </summary> diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 77e2d8d88a..63fd717429 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Collections.Generic; +using System.Text.Json.Serialization; namespace MediaBrowser.Model.Updates { @@ -27,30 +28,35 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the name. /// </summary> /// <value>The name.</value> + [JsonPropertyName("name")] public string Name { get; set; } /// <summary> /// Gets or sets a long description of the plugin containing features or helpful explanations. /// </summary> /// <value>The description.</value> + /// [JsonPropertyName("description")] public string Description { get; set; } /// <summary> /// Gets or sets a short overview of what the plugin does. /// </summary> /// <value>The overview.</value> + [JsonPropertyName("overview")] public string Overview { get; set; } /// <summary> /// Gets or sets the owner. /// </summary> /// <value>The owner.</value> + [JsonPropertyName("owner")] public string Owner { get; set; } /// <summary> /// Gets or sets the category. /// </summary> /// <value>The category.</value> + [JsonPropertyName("category")] public string Category { get; set; } /// <summary> @@ -58,6 +64,7 @@ namespace MediaBrowser.Model.Updates /// This is used to identify the proper item for automatic updates. /// </summary> /// <value>The name.</value> + [JsonPropertyName("guid")] #pragma warning disable CA1720 // Identifier contains type name public string Guid { get; set; } #pragma warning restore CA1720 // Identifier contains type name @@ -66,6 +73,7 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the versions. /// </summary> /// <value>The versions.</value> + [JsonPropertyName("versions")] #pragma warning disable CA2227 // Collection properties should be read only public IList<VersionInfo> Versions { get; set; } #pragma warning restore CA2227 // Collection properties should be read only @@ -73,6 +81,7 @@ namespace MediaBrowser.Model.Updates /// <summary> /// Gets or sets the image url for the package. /// </summary> + [JsonPropertyName("imageUrl")] public string? ImageUrl { get; set; } } } From c197dca759ee7353d7e9f477b3cc189eac0c14e0 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 18:27:31 +0000 Subject: [PATCH 0745/1930] Changed PluginId to guid so its the same type as plugin.id --- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 9 ++++----- MediaBrowser.Model/Updates/VersionInfo.cs | 12 +++++++++++- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index 3c553a1b50..c15ed05d39 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -1,3 +1,4 @@ +using System; using MediaBrowser.Common.Plugins; using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Plugins; @@ -23,7 +24,7 @@ namespace Jellyfin.Api.Models { DisplayName = page.Plugin.Name; // Don't use "N" because it needs to match Plugin.Id - PluginId = page.Plugin.Id.ToString(); + PluginId = page.Plugin.Id; } } @@ -39,9 +40,7 @@ namespace Jellyfin.Api.Models MenuSection = page.MenuSection; MenuIcon = page.MenuIcon; DisplayName = string.IsNullOrWhiteSpace(page.DisplayName) ? plugin?.Name : page.DisplayName; - - // Don't use "N" because it needs to match Plugin.Id - PluginId = plugin?.Id.ToString(); + PluginId = plugin?.Id; } /// <summary> @@ -80,6 +79,6 @@ namespace Jellyfin.Api.Models /// Gets or sets the plugin id. /// </summary> /// <value>The plugin id.</value> - public string? PluginId { get; set; } + public Guid? PluginId { get; set; } } } diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs index 1e07c9f26b..503dba0a14 100644 --- a/MediaBrowser.Model/Updates/VersionInfo.cs +++ b/MediaBrowser.Model/Updates/VersionInfo.cs @@ -1,11 +1,12 @@ #nullable enable +using System.Text.Json.Serialization; using SysVersion = System.Version; namespace MediaBrowser.Model.Updates { /// <summary> - /// Class PackageVersionInfo. + /// Defines the <see cref="VersionInfo"/> class. /// </summary> public class VersionInfo { @@ -15,6 +16,7 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the version. /// </summary> /// <value>The version.</value> + [JsonPropertyName("version")] public string Version { get => _version == null ? string.Empty : _version.ToString(); @@ -31,46 +33,54 @@ namespace MediaBrowser.Model.Updates /// Gets or sets the changelog for this version. /// </summary> /// <value>The changelog.</value> + [JsonPropertyName("changelog")] public string? Changelog { get; set; } /// <summary> /// Gets or sets the ABI that this version was built against. /// </summary> /// <value>The target ABI version.</value> + [JsonPropertyName("targetAbi")] public string? TargetAbi { get; set; } /// <summary> /// Gets or sets the maximum ABI that this version will work with. /// </summary> /// <value>The target ABI version.</value> + [JsonPropertyName("maxAbi")] public string? MaxAbi { get; set; } /// <summary> /// Gets or sets the source URL. /// </summary> /// <value>The source URL.</value> + [JsonPropertyName("sourceUrl")] public string? SourceUrl { get; set; } /// <summary> /// Gets or sets a checksum for the binary. /// </summary> /// <value>The checksum.</value> + [JsonPropertyName("checksum")] public string? Checksum { get; set; } /// <summary> /// Gets or sets a timestamp of when the binary was built. /// </summary> /// <value>The timestamp.</value> + [JsonPropertyName("timestamp")] public string? Timestamp { get; set; } /// <summary> /// Gets or sets the repository name. /// </summary> + [JsonPropertyName("repositoryName")] public string RepositoryName { get; set; } = string.Empty; /// <summary> /// Gets or sets the repository url. /// </summary> + [JsonPropertyName("repositoryUrl")] public string RepositoryUrl { get; set; } = string.Empty; } } From 3f1ad7f963f4d631861d8b6ac30acd7e4753ccf0 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:22:54 +0000 Subject: [PATCH 0746/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index eb6b770d67..9b731f88a9 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -200,7 +200,7 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - [Obsolete("Please use the UninstallByVersion API.")] + [Obsolete("Please use the UninstallPluginByVersion API.")] public ActionResult UninstallPlugin([FromRoute, Required] Guid pluginId) { // If no version is given, return the current instance. From 2afa963fc134853e86ab30029be3ea22e9c72366 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:24:39 +0000 Subject: [PATCH 0747/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 9b731f88a9..1e658890eb 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -127,7 +127,7 @@ namespace Jellyfin.Api.Controllers /// <param name="version">Plugin version.</param> /// <response code="204">Plugin enabled.</response> /// <response code="404">Plugin not found.</response> - /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpPost("{pluginId}/{version}/Enable")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] From e4993ae574b0b01304297770e58bb9b86e34ef6e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:24:52 +0000 Subject: [PATCH 0748/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 1e658890eb..9a4d0c40b7 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -173,7 +173,7 @@ namespace Jellyfin.Api.Controllers /// <param name="version">Plugin version.</param> /// <response code="204">Plugin uninstalled.</response> /// <response code="404">Plugin not found.</response> - /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpDelete("{pluginId}/{version}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] From 24ab152e9d340e041dc57cfd6dbd60d6d35f9cc9 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:30:23 +0000 Subject: [PATCH 0749/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 9a4d0c40b7..c3c9460e65 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -150,7 +150,7 @@ namespace Jellyfin.Api.Controllers /// <param name="version">Plugin version.</param> /// <response code="204">Plugin disabled.</response> /// <response code="404">Plugin not found.</response> - /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpPost("{pluginId}/{version}/Disable")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] From aecd35d30668595b761e878265bb0ed61826ec50 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:31:36 +0000 Subject: [PATCH 0750/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index c3c9460e65..565bf23119 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -324,7 +324,6 @@ namespace Jellyfin.Api.Controllers [HttpPost("{pluginId}/Manifest")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesFile(MediaTypeNames.Application.Json)] public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId) { if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin)) From 00ff3b90962ff616629fab675c6e0108d3af58ae Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:35:26 +0000 Subject: [PATCH 0751/1930] remove attribute --- Jellyfin.Api/Controllers/PluginsController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 565bf23119..b5976fbbdf 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -228,7 +228,6 @@ namespace Jellyfin.Api.Controllers [HttpGet("{pluginId}/Configuration")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesFile(MediaTypeNames.Application.Json)] public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId) { if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin) From 0337e39bae80ba78d19821373603f19bd6a5a95f Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 19:39:41 +0000 Subject: [PATCH 0752/1930] Updated JsonDefaults --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 1 + MediaBrowser.Common/Json/JsonDefaults.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index cd594b5c5e..bbfc4fbd4c 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -227,6 +227,7 @@ namespace Jellyfin.Server.Extensions options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented; options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition; options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling; + options.JsonSerializerOptions.PropertyNameCaseInsensitive = jsonOptions.PropertyNameCaseInsensitive; options.JsonSerializerOptions.Converters.Clear(); foreach (var converter in jsonOptions.Converters) diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 50393b909a..f232ebdc7f 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -36,7 +36,8 @@ namespace MediaBrowser.Common.Json ReadCommentHandling = JsonCommentHandling.Disallow, WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - NumberHandling = JsonNumberHandling.AllowReadingFromString + NumberHandling = JsonNumberHandling.AllowReadingFromString, + PropertyNameCaseInsensitive = true }; options.Converters.Add(new JsonGuidConverter()); @@ -56,7 +57,6 @@ namespace MediaBrowser.Common.Json { var options = GetOptions(); options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; - options.PropertyNameCaseInsensitive = true; return options; } From 532388754053957a1b3066900b7b54e1894206f3 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Tue, 15 Dec 2020 20:27:42 +0000 Subject: [PATCH 0753/1930] Replaced TryGetPlugin with GetPlugin --- .../Plugins/PluginManager.cs | 13 +++---- .../Updates/InstallationManager.cs | 5 +-- Jellyfin.Api/Controllers/PluginsController.cs | 34 +++++++++++-------- MediaBrowser.Common/Plugins/IPluginManager.cs | 5 ++- 4 files changed, 32 insertions(+), 25 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 944b746528..26a029f712 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -212,12 +212,13 @@ namespace Emby.Server.Implementations /// <summary> /// Attempts to find the plugin with and id of <paramref name="id"/>. /// </summary> - /// <param name="id">Id of plugin.</param> - /// <param name="version">The version of the plugin to locate.</param> - /// <param name="plugin">A <see cref="LocalPlugin"/> if found, otherwise null.</param> - /// <returns>Boolean value signifying the success of the search.</returns> - public bool TryGetPlugin(Guid id, Version? version, out LocalPlugin? plugin) + /// <param name="id">The <see cref="Guid"/> of plugin.</param> + /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param> + /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns> + public LocalPlugin? GetPlugin(Guid id, Version? version = null) { + LocalPlugin? plugin; + if (version == null) { // If no version is given, return the current instance. @@ -235,7 +236,7 @@ namespace Emby.Server.Implementations plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version)); } - return plugin != null; + return plugin; } /// <summary> diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index fc80bdd756..7cab77c85d 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -197,10 +197,11 @@ namespace Emby.Server.Implementations.Updates { var version = package.Versions[i]; + var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber); // Update the manifests, if anything changes. - if (_pluginManager.TryGetPlugin(packageGuid, version.VersionNumber, out LocalPlugin? plugin)) + if (plugin != null) { - bool noChange = string.Equals(plugin!.Manifest.MaxAbi, version.MaxAbi, StringComparison.Ordinal) + bool noChange = string.Equals(plugin.Manifest.MaxAbi, version.MaxAbi, StringComparison.Ordinal) || string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal); if (!noChange) { diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index b5976fbbdf..49ccac1375 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -134,12 +134,13 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult EnablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + var plugin = _pluginManager.GetPlugin(pluginId, version); + if (plugin == null) { return NotFound(); } - _pluginManager.EnablePlugin(plugin!); + _pluginManager.EnablePlugin(plugin); return NoContent(); } @@ -157,12 +158,13 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult DisablePlugin([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + var plugin = _pluginManager.GetPlugin(pluginId, version); + if (plugin == null) { return NotFound(); } - _pluginManager.DisablePlugin(plugin!); + _pluginManager.DisablePlugin(plugin); return NoContent(); } @@ -180,7 +182,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult UninstallPluginByVersion([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + var plugin = _pluginManager.GetPlugin(pluginId, version); + if (plugin == null) { return NotFound(); } @@ -230,8 +233,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult<BasePluginConfiguration> GetPluginConfiguration([FromRoute, Required] Guid pluginId) { - if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin) - && plugin!.Instance is IHasPluginConfiguration configPlugin) + var plugin = _pluginManager.GetPlugin(pluginId); + if (plugin?.Instance is IHasPluginConfiguration configPlugin) { return configPlugin.Configuration; } @@ -258,8 +261,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> UpdatePluginConfiguration([FromRoute, Required] Guid pluginId) { - if (!_pluginManager.TryGetPlugin(pluginId, null, out var plugin) - || plugin?.Instance is not IHasPluginConfiguration configPlugin) + var plugin = _pluginManager.GetPlugin(pluginId); + if (plugin?.Instance is not IHasPluginConfiguration configPlugin) { return NotFound(); } @@ -289,14 +292,15 @@ namespace Jellyfin.Api.Controllers [AllowAnonymous] public ActionResult GetPluginImage([FromRoute, Required] Guid pluginId, [FromRoute, Required] Version version) { - if (!_pluginManager.TryGetPlugin(pluginId, version, out var plugin)) + var plugin = _pluginManager.GetPlugin(pluginId, version); + if (plugin == null) { return NotFound(); } - var imgPath = Path.Combine(plugin!.Path, plugin!.Manifest.ImageUrl ?? string.Empty); + var imgPath = Path.Combine(plugin.Path, plugin.Manifest.ImageUrl ?? string.Empty); if (((ServerConfiguration)_config.CommonConfiguration).DisablePluginImages - || plugin!.Manifest.ImageUrl == null + || plugin.Manifest.ImageUrl == null || !System.IO.File.Exists(imgPath)) { // Use a blank image. @@ -325,9 +329,11 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult<PluginManifest> GetPluginManifest([FromRoute, Required] Guid pluginId) { - if (_pluginManager.TryGetPlugin(pluginId, null, out var plugin)) + var plugin = _pluginManager.GetPlugin(pluginId); + + if (plugin != null) { - return Ok(plugin!.Manifest); + return Ok(plugin.Manifest); } return NotFound(); diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index 071b51969f..7f7381b033 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -72,9 +72,8 @@ namespace MediaBrowser.Common.Plugins /// </summary> /// <param name="id">Id of plugin.</param> /// <param name="version">The version of the plugin to locate.</param> - /// <param name="plugin">A <see cref="LocalPlugin"/> if found, otherwise null.</param> - /// <returns>Boolean value signifying the success of the search.</returns> - bool TryGetPlugin(Guid id, Version? version, out LocalPlugin? plugin); + /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns> + LocalPlugin? GetPlugin(Guid id, Version? version = null); /// <summary> /// Removes the plugin. From 1b3fcab6a400a9370b54287f4371638530a00e19 Mon Sep 17 00:00:00 2001 From: Ryan Petris <ryan@petris.net> Date: Tue, 15 Dec 2020 22:02:08 -0700 Subject: [PATCH 0754/1930] If requestContext is HttpRequest, get the context from it properly. --- .../HttpServer/Security/SessionContext.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index 86914dea20..049291f7f6 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -45,6 +45,11 @@ namespace Emby.Server.Implementations.HttpServer.Security public User GetUser(object requestContext) { + if (requestContext is HttpRequest request) + { + return GetUser(request.HttpContext); + } + return GetUser((HttpContext)requestContext); } } From 875562e580a1f36d0364c04af22bfd9c7234ef95 Mon Sep 17 00:00:00 2001 From: Ryan Petris <ryan@petris.net> Date: Tue, 15 Dec 2020 22:17:04 -0700 Subject: [PATCH 0755/1930] This is only used in one place and therefore will always be HttpRequest. --- .../HttpServer/Security/SessionContext.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index 049291f7f6..040b6b9e4e 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -45,12 +45,7 @@ namespace Emby.Server.Implementations.HttpServer.Security public User GetUser(object requestContext) { - if (requestContext is HttpRequest request) - { - return GetUser(request.HttpContext); - } - - return GetUser((HttpContext)requestContext); + return GetUser(((HttpRequest)requestContext).HttpContext); } } } From 7c3f2e7c599908bb4cdf027794950875efd5fb50 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Wed, 16 Dec 2020 21:20:29 +0800 Subject: [PATCH 0756/1930] Correct DLNA audio codecs for PS3 and PS4 * https://manuals.playstation.net/document/en/ps3/current/video/filetypes.html * https://manuals.playstation.net/document/en/ps4/music/mp_format_m.html --- Emby.Dlna/Profiles/SonyPs3Profile.cs | 4 ++-- Emby.Dlna/Profiles/SonyPs4Profile.cs | 4 ++-- Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml | 4 ++-- Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/Profiles/SonyPs3Profile.cs b/Emby.Dlna/Profiles/SonyPs3Profile.cs index d56b1df507..e4a7a3a596 100644 --- a/Emby.Dlna/Profiles/SonyPs3Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs3Profile.cs @@ -52,7 +52,7 @@ namespace Emby.Dlna.Profiles Container = "ts,mpegts", Type = DlnaProfileType.Video, VideoCodec = "mpeg1video,mpeg2video,h264", - AudioCodec = "ac3,mp2,mp3,aac" + AudioCodec = "aac,ac3,mp2" }, new DirectPlayProfile { @@ -92,7 +92,7 @@ namespace Emby.Dlna.Profiles { Container = "ts", VideoCodec = "h264", - AudioCodec = "ac3,aac,mp3", + AudioCodec = "aac,ac3,mp2", Type = DlnaProfileType.Video }, new TranscodingProfile diff --git a/Emby.Dlna/Profiles/SonyPs4Profile.cs b/Emby.Dlna/Profiles/SonyPs4Profile.cs index db56094e2b..985df0c9a5 100644 --- a/Emby.Dlna/Profiles/SonyPs4Profile.cs +++ b/Emby.Dlna/Profiles/SonyPs4Profile.cs @@ -52,7 +52,7 @@ namespace Emby.Dlna.Profiles Container = "ts,mpegts", Type = DlnaProfileType.Video, VideoCodec = "mpeg1video,mpeg2video,h264", - AudioCodec = "ac3,mp2,mp3,aac" + AudioCodec = "aac,ac3,mp2" }, new DirectPlayProfile { @@ -94,7 +94,7 @@ namespace Emby.Dlna.Profiles { Container = "ts", VideoCodec = "h264", - AudioCodec = "mp3", + AudioCodec = "aac,ac3,mp2", Type = DlnaProfileType.Video }, new TranscodingProfile diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml index bafa44b828..129b188e2a 100644 --- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml +++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 3.xml @@ -38,7 +38,7 @@ <XmlRootAttributes /> <DirectPlayProfiles> <DirectPlayProfile container="avi" audioCodec="mp2,mp3" videoCodec="mpeg4" type="Video" /> - <DirectPlayProfile container="ts,mpegts" audioCodec="ac3,mp2,mp3,aac" videoCodec="mpeg1video,mpeg2video,h264" type="Video" /> + <DirectPlayProfile container="ts,mpegts" audioCodec="aac,ac3,mp2" videoCodec="mpeg1video,mpeg2video,h264" type="Video" /> <DirectPlayProfile container="mpeg" audioCodec="mp2" videoCodec="mpeg1video,mpeg2video" type="Video" /> <DirectPlayProfile container="mp4" audioCodec="aac,ac3" videoCodec="h264,mpeg4" type="Video" /> <DirectPlayProfile container="aac,mp3,wav" type="Audio" /> @@ -46,7 +46,7 @@ </DirectPlayProfiles> <TranscodingProfiles> <TranscodingProfile container="mp3" type="Audio" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> - <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="ac3,aac,mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> + <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="aac,ac3,mp2" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> <TranscodingProfile container="jpeg" type="Photo" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> </TranscodingProfiles> <ContainerProfiles> diff --git a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml index eb8e645b31..592119305e 100644 --- a/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml +++ b/Emby.Dlna/Profiles/Xml/Sony PlayStation 4.xml @@ -38,7 +38,7 @@ <XmlRootAttributes /> <DirectPlayProfiles> <DirectPlayProfile container="avi" audioCodec="mp2,mp3" videoCodec="mpeg4" type="Video" /> - <DirectPlayProfile container="ts,mpegts" audioCodec="ac3,mp2,mp3,aac" videoCodec="mpeg1video,mpeg2video,h264" type="Video" /> + <DirectPlayProfile container="ts,mpegts" audioCodec="aac,ac3,mp2" videoCodec="mpeg1video,mpeg2video,h264" type="Video" /> <DirectPlayProfile container="mpeg" audioCodec="mp2" videoCodec="mpeg1video,mpeg2video" type="Video" /> <DirectPlayProfile container="mp4,mkv,m4v" audioCodec="aac,ac3" videoCodec="h264,mpeg4" type="Video" /> <DirectPlayProfile container="aac,mp3,wav" type="Audio" /> @@ -46,7 +46,7 @@ </DirectPlayProfiles> <TranscodingProfiles> <TranscodingProfile container="mp3" type="Audio" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Bytes" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> - <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="mp3" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> + <TranscodingProfile container="ts" type="Video" videoCodec="h264" audioCodec="aac,ac3,mp2" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> <TranscodingProfile container="jpeg" type="Photo" estimateContentLength="false" enableMpegtsM2TsMode="false" transcodeSeekInfo="Auto" copyTimestamps="false" context="Streaming" enableSubtitlesInManifest="false" minSegments="0" segmentLength="0" breakOnNonKeyFrames="false" /> </TranscodingProfiles> <ContainerProfiles> From 6d3e1d6b5726201d7c943ba007ef873810ffd7bc Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 16 Dec 2020 19:37:23 +0000 Subject: [PATCH 0757/1930] Small Optimization --- MediaBrowser.Common/Plugins/LocalPlugin.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index e48ebbfa5c..8aded8b9bc 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Common.Plugins throw new ArgumentNullException(a == null ? nameof(a) : nameof(b)); } - var compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture); + var compare = string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); // Id is not equal but name is. if (!a.Id.Equals(b.Id) && compare == 0) From ebbb57efc3274663b515b4accc52f4a4e9920e77 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 16 Dec 2020 21:40:52 +0000 Subject: [PATCH 0758/1930] Change json default settings. --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 49ccac1375..4f65e18e15 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -47,7 +47,7 @@ namespace Jellyfin.Api.Controllers { _installationManager = installationManager; _pluginManager = pluginManager; - _serializerOptions = JsonDefaults.GetCamelCaseOptions(); + _serializerOptions = JsonDefaults.GetOptions(); _config = config; } From 1ed25ebd9a11f3fc1838e347a34621dcde0b7bd5 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 16 Dec 2020 22:36:25 +0000 Subject: [PATCH 0759/1930] Corrections as recommended. --- .../Updates/InstallationManager.cs | 5 ++--- Jellyfin.Api/Controllers/PluginsController.cs | 16 +++++++++------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 7cab77c85d..70424369bd 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.Updates _httpClientFactory = httpClientFactory; _config = config; _zipClient = zipClient; - _jsonSerializerOptions = JsonDefaults.GetCamelCaseOptions(); + _jsonSerializerOptions = JsonDefaults.GetOptions(); _pluginManager = pluginManager; } @@ -104,8 +104,7 @@ namespace Emby.Server.Implementations.Updates { try { - List<PackageInfo>? packages; - packages = await _httpClientFactory.CreateClient(NamedClient.Default) + List<PackageInfo>? packages = await _httpClientFactory.CreateClient(NamedClient.Default) .GetFromJsonAsync<List<PackageInfo>>(new Uri(manifest), _jsonSerializerOptions, cancellationToken).ConfigureAwait(false); if (packages == null) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 4f65e18e15..6db74571cc 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -217,8 +217,13 @@ namespace Jellyfin.Api.Controllers plugin = plugins.OrderBy(p => p.Manifest.Status).FirstOrDefault(); } - _installationManager.UninstallPlugin(plugin!); - return NoContent(); + if (plugin != null) + { + _installationManager.UninstallPlugin(plugin!); + return NoContent(); + } + + return NotFound(); } /// <summary> @@ -303,10 +308,7 @@ namespace Jellyfin.Api.Controllers || plugin.Manifest.ImageUrl == null || !System.IO.File.Exists(imgPath)) { - // Use a blank image. - var type = GetType(); - var stream = type.Assembly.GetManifestResourceStream(type.Namespace + ".Plugins.blank.png"); - return File(stream, "image/png"); + return NotFound(); } imgPath = Path.Combine(plugin.Path, plugin.Manifest.ImageUrl); @@ -333,7 +335,7 @@ namespace Jellyfin.Api.Controllers if (plugin != null) { - return Ok(plugin.Manifest); + return plugin.Manifest; } return NotFound(); From d9aaba36ec807b12d58fdf9498ee60574ba44a54 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Wed, 16 Dec 2020 23:19:09 +0000 Subject: [PATCH 0760/1930] Copy previous plugin settings if they don't exist. --- .../Plugins/PluginManager.cs | 29 +++++++++++++++++++ MediaBrowser.Common/Plugins/BasePlugin.cs | 4 +-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 26a029f712..e7589a0f92 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -274,6 +274,32 @@ namespace Emby.Server.Implementations } } + private void CopyFiles(string source, string destination, bool overwrite, string searchPattern) + { + FileInfo[] files; + try + { + files = new DirectoryInfo(source).GetFiles(searchPattern); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Error retrieving file list."); + return; + } + + foreach (FileInfo file in files) + { + try + { + file.CopyTo(Path.Combine(destination, file.Name), overwrite); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Error copying file {Name}", file.Name); + } + } + } + /// <summary> /// Changes the status of the other versions of the plugin to "Superceded". /// </summary> @@ -295,6 +321,9 @@ namespace Emby.Server.Implementations return; } + // migrate settings across from the last active version if they don't exist. + CopyFiles(predecessor.Path, plugin.Path, false, "*.xml"); + if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded)) { _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index a0d6b8f836..5756f8852c 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -166,14 +166,14 @@ namespace MediaBrowser.Common.Plugins assemblyPlugin.SetId(assemblyId); } - // TODO : Simplify this, once migration support is ceased. + // TODO : Remove this, once migration support is ceased. if (inPluginFolder) { var oldConfigFilePath = Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); if (!File.Exists(ConfigurationFilePath) && File.Exists(oldConfigFilePath)) { - // Migrate settings, as different plugin versions may have different settings. + // Migrate pre 10.7 settings, as different plugin versions may have different settings. try { File.Copy(oldConfigFilePath, ConfigurationFilePath); From 212c76102daa679e6bba387a5501ae0092e13fb5 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 17 Dec 2020 13:37:13 +0000 Subject: [PATCH 0761/1930] Update PluginManifest.cs --- MediaBrowser.Common/Plugins/PluginManifest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index b88275718a..1bd17933c4 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -67,7 +67,7 @@ namespace MediaBrowser.Common.Plugins public string Version { get; set; } = string.Empty; /// <summary> - /// Gets or sets a value indicating whether this plugin should be ignored. + /// Gets or sets a value indicating the operational status of this plugin. /// </summary> public PluginStatus Status { get; set; } From a4a40407a047de2f10aa0f9d0ba9fe0f600ffdb0 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Thu, 17 Dec 2020 13:44:38 +0000 Subject: [PATCH 0762/1930] Change PluginStatus states. --- .../Plugins/PluginManager.cs | 20 +++++++++---------- MediaBrowser.Model/Plugins/PluginStatus.cs | 8 ++++---- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index e7589a0f92..975b708435 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations for (int a = _plugins.Count - 1; a >= 0; a--) { var plugin = _plugins[a]; - if (plugin.Manifest.Status == PluginStatus.DeleteOnStartup && DeletePlugin(plugin)) + if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin)) { UpdateSuccessors(plugin); } @@ -104,7 +104,7 @@ namespace Emby.Server.Implementations catch (FileLoadException ex) { _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin.", file); - ChangePluginState(plugin, PluginStatus.Malfunction); + ChangePluginState(plugin, PluginStatus.Malfunctioned); continue; } @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations #pragma warning restore CA1031 // Do not catch general exception types { _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName); - if (ChangePluginState(plugin, PluginStatus.Malfunction)) + if (ChangePluginState(plugin, PluginStatus.Malfunctioned)) { _logger.LogInformation("Disabling plugin {Path}", plugin.Path); } @@ -206,7 +206,7 @@ namespace Emby.Server.Implementations _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path); // Unable to delete, so disable. - return ChangePluginState(plugin, PluginStatus.DeleteOnStartup); + return ChangePluginState(plugin, PluginStatus.Deleted); } /// <summary> @@ -307,7 +307,7 @@ namespace Emby.Server.Implementations private void UpdateSuccessors(LocalPlugin plugin) { // This value is memory only - so that the web will show restart required. - plugin.Manifest.Status = PluginStatus.RestartRequired; + plugin.Manifest.Status = PluginStatus.Restart; // Detect whether there is another version of this plugin that needs disabling. var predecessor = _plugins.OrderByDescending(p => p.Version) @@ -349,7 +349,7 @@ namespace Emby.Server.Implementations return; } - ChangePluginState(plugin, PluginStatus.Malfunction); + ChangePluginState(plugin, PluginStatus.Malfunctioned); } /// <summary> @@ -486,7 +486,7 @@ namespace Emby.Server.Implementations _logger.LogError(ex, "Error creating {Type}", type.FullName); if (plugin != null) { - if (ChangePluginState(plugin, PluginStatus.Malfunction)) + if (ChangePluginState(plugin, PluginStatus.Malfunctioned)) { _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path); return null; @@ -600,7 +600,7 @@ namespace Emby.Server.Implementations // Auto-create a plugin manifest, so we can disable it, if it fails to load. manifest = new PluginManifest { - Status = PluginStatus.RestartRequired, + Status = PluginStatus.Restart, Name = metafile, AutoUpdate = false, Guid = metafile.GetMD5(), @@ -697,9 +697,9 @@ namespace Emby.Server.Implementations continue; } - if (manifest.Status != PluginStatus.DeleteOnStartup) + if (manifest.Status != PluginStatus.Deleted) { - manifest.Status = PluginStatus.DeleteOnStartup; + manifest.Status = PluginStatus.Deleted; SaveManifest(manifest, entry.Path); } } diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs index 2acc56811e..3ea05174fd 100644 --- a/MediaBrowser.Model/Plugins/PluginStatus.cs +++ b/MediaBrowser.Model/Plugins/PluginStatus.cs @@ -8,10 +8,10 @@ namespace MediaBrowser.Model.Plugins /// <summary> /// This plugin requires a restart in order for it to load. This is a memory only status. /// The actual status of the plugin after reload is present in the manifest. - /// eg. A disabled plugin will still be active until the next restart, and so will have a memory status of RestartRequired, + /// eg. A disabled plugin will still be active until the next restart, and so will have a memory status of Restart, /// but a disk manifest status of Disabled. /// </summary> - RestartRequired = 1, + Restart = 1, /// <summary> /// This plugin is currently running. @@ -31,7 +31,7 @@ namespace MediaBrowser.Model.Plugins /// <summary> /// This plugin caused an error when instantiated. (Either DI loop, or exception) /// </summary> - Malfunction = -3, + Malfunctioned = -3, /// <summary> /// This plugin has been superceded by another version. @@ -42,6 +42,6 @@ namespace MediaBrowser.Model.Plugins /// An attempt to remove this plugin from disk will happen at every restart. /// It will not be loaded, if unable to do so. /// </summary> - DeleteOnStartup = -5 + Deleted = -5 } } From 0ed3c2def2017f775cb9ab3e31aa9aa95cdea7f4 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 17 Dec 2020 13:50:24 +0000 Subject: [PATCH 0763/1930] Update MediaBrowser.sln --- MediaBrowser.sln | 1 - 1 file changed, 1 deletion(-) diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 36518377c4..c654e8ef36 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,3 @@ - Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 From cf8aa37f5bd9bc76a78aac4e4232328f82fa4596 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 17 Dec 2020 23:33:44 +0800 Subject: [PATCH 0764/1930] Fix some video profile for Android client * Fix constrained high profile for some encoders * Extended profile is not supported by any known h264 encoders * Replace HEVC 10-bit profiles with main profile --- .../MediaEncoding/EncodingHelper.cs | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 91a03e6472..a8a094e63d 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1130,10 +1130,22 @@ namespace MediaBrowser.Controller.MediaEncoding var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault(); profile = Regex.Replace(profile, @"\s+", String.Empty); + // We only transcode to HEVC 8-bit for now, force Main Profile. + if (profile.Contains("main 10", StringComparison.OrdinalIgnoreCase) + || profile.Contains("main still", StringComparison.OrdinalIgnoreCase)) + { + profile = "main"; + } + + // Extended Profile is not supported by any known h264 encoders, force Main Profile. + if (profile.Contains("extended", StringComparison.OrdinalIgnoreCase)) + { + profile = "main"; + } + // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) - && profile != null - && profile.IndexOf("high 10", StringComparison.OrdinalIgnoreCase) != -1) + && profile.Contains("high 10", StringComparison.OrdinalIgnoreCase)) { profile = "high"; } @@ -1141,8 +1153,7 @@ namespace MediaBrowser.Controller.MediaEncoding // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case, // which is compatible (and ugly). if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase) - && profile != null - && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) + && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase)) { profile = "constrained_baseline"; } @@ -1151,16 +1162,24 @@ namespace MediaBrowser.Controller.MediaEncoding if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)) - && profile != null - && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1) + && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase)) { profile = "baseline"; } + // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case. + if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) + || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)) + && profile.Contains("high", StringComparison.OrdinalIgnoreCase)) + { + profile = "high"; + } + // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile. - if (!string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase) - && profile != null - && profile.IndexOf("main 10", StringComparison.OrdinalIgnoreCase) != -1) + if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase) + && profile.Contains("main 10", StringComparison.OrdinalIgnoreCase)) { profile = "main"; } From 9bf51aeb6b95272c278b15ad40d11e3837e9e8b2 Mon Sep 17 00:00:00 2001 From: nlspln <nielspolin@gmail.com> Date: Thu, 17 Dec 2020 15:20:43 +0000 Subject: [PATCH 0765/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index b6672a554a..1e80d0b5f9 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -1,7 +1,7 @@ { "Albums": "Albums", "AppDeviceValues": "App: {0}, Apparaat: {1}", - "Application": "Programma", + "Application": "Applicatie", "Artists": "Artiesten", "AuthenticationSucceededWithUserName": "{0} is succesvol geverifieerd", "Books": "Boeken", From e515b696d11fc0df34389ec5cb5f68e5c5eebde7 Mon Sep 17 00:00:00 2001 From: Miko Dela Cruz <mikomiks22@gmail.com> Date: Thu, 17 Dec 2020 15:41:50 +0000 Subject: [PATCH 0766/1930] Translated using Weblate (Japanese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ja/ --- Emby.Server.Implementations/Localization/Core/ja.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ja.json b/Emby.Server.Implementations/Localization/Core/ja.json index 02bf8496ff..fa0ab8b927 100644 --- a/Emby.Server.Implementations/Localization/Core/ja.json +++ b/Emby.Server.Implementations/Localization/Core/ja.json @@ -4,7 +4,7 @@ "Application": "アプリケーション", "Artists": "アーティスト", "AuthenticationSucceededWithUserName": "{0} 認証に成功しました", - "Books": "ブック", + "Books": "ブックス", "CameraImageUploadedFrom": "新しいカメライメージが {0}からアップロードされました", "Channels": "チャンネル", "ChapterNameValue": "チャプター {0}", @@ -114,5 +114,8 @@ "TaskRefreshChapterImages": "チャプター画像を抽出する", "TaskDownloadMissingSubtitles": "不足している字幕をダウンロードする", "TaskCleanActivityLogDescription": "設定された期間よりも古いアクティビティの履歴を削除します。", - "TaskCleanActivityLog": "アクティビティの履歴を消去" + "TaskCleanActivityLog": "アクティビティの履歴を消去", + "Undefined": "未定義", + "Forced": "強制", + "Default": "デフォルト" } From 56ae63433f15c78aaebc2fe278829552fb8c5dd6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 17 Dec 2020 13:05:44 -0700 Subject: [PATCH 0767/1930] Set filename when downloading file --- Jellyfin.Api/Controllers/LibraryController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 184843b397..c1538a4316 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -667,7 +667,7 @@ namespace Jellyfin.Api.Controllers } // TODO determine non-ASCII validity. - return PhysicalFile(path, MimeTypes.GetMimeType(path)); + return PhysicalFile(path, MimeTypes.GetMimeType(path), filename); } /// <summary> From be3129e012ab862bf80537a1668f32dda5db8554 Mon Sep 17 00:00:00 2001 From: SecularSteve <fairfull.playing@gmail.com> Date: Thu, 17 Dec 2020 19:50:35 +0000 Subject: [PATCH 0768/1930] Translated using Weblate (English (United Kingdom)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/en_GB/ --- Emby.Server.Implementations/Localization/Core/en-GB.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/en-GB.json b/Emby.Server.Implementations/Localization/Core/en-GB.json index cd64cdde45..7667612b90 100644 --- a/Emby.Server.Implementations/Localization/Core/en-GB.json +++ b/Emby.Server.Implementations/Localization/Core/en-GB.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Library", "TasksMaintenanceCategory": "Maintenance", "TaskCleanActivityLogDescription": "Deletes activity log entries older than the configured age.", - "TaskCleanActivityLog": "Clean Activity Log" + "TaskCleanActivityLog": "Clean Activity Log", + "Undefined": "Undefined", + "Forced": "Forced", + "Default": "Default" } From e445c2932afe8107846f85e308941d75350be013 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:23:15 +0000 Subject: [PATCH 0769/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 6db74571cc..5a3a3eef9f 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -219,7 +219,7 @@ namespace Jellyfin.Api.Controllers if (plugin != null) { - _installationManager.UninstallPlugin(plugin!); + _installationManager.UninstallPlugin(plugin); return NoContent(); } From 5d5b198525bd3a45f6c3f61dda559597e24b7d45 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:23:28 +0000 Subject: [PATCH 0770/1930] Update Jellyfin.Api/Controllers/PluginsController.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 5a3a3eef9f..1365764fba 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -188,7 +188,7 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - _installationManager.UninstallPlugin(plugin!); + _installationManager.UninstallPlugin(plugin); return NoContent(); } From 3a8d395c9c88fb5a6e170504ee8d865d880d7ed6 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:23:46 +0000 Subject: [PATCH 0771/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 975b708435..34e8219e15 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -27,7 +27,6 @@ namespace Emby.Server.Implementations private readonly JsonSerializerOptions _jsonOptions; private readonly ILogger<PluginManager> _logger; private readonly IApplicationHost _appHost; - private readonly string _imagesPath; private readonly ServerConfiguration _config; private readonly IList<LocalPlugin> _plugins; private readonly Version _nextVersion; From 2d094bedf5d8b8e0e33e5bc0f59f9f39cb7b40c7 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:24:00 +0000 Subject: [PATCH 0772/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 34e8219e15..66a233fbe7 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -425,7 +425,7 @@ namespace Emby.Server.Implementations try { _logger.LogDebug("Creating instance of {Type}", type); - var instance = ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type); + var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type); if (plugin == null) { // Create a dummy record for the providers. From 30645e72654e0d4918c86b610cbe9e8c2e4f4907 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:24:12 +0000 Subject: [PATCH 0773/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 66a233fbe7..6eeb8613c6 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -429,7 +429,6 @@ namespace Emby.Server.Implementations if (plugin == null) { // Create a dummy record for the providers. - var pInstance = (IPlugin)instance; plugin = new LocalPlugin( pInstance.AssemblyFilePath, true, From 591ad3b04b7816d447ccd60c096a7fe730b3dea6 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:24:26 +0000 Subject: [PATCH 0774/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 6eeb8613c6..e92b02191a 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -450,7 +450,7 @@ namespace Emby.Server.Implementations } else { - plugin.Instance = (IPlugin)instance; + plugin.Instance = instance; var manifest = plugin.Manifest; var pluginStr = plugin.Instance.Version.ToString(); bool changed = false; From 8ce765c4d1cd289c88673f79a8137bf2f5cbc241 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:25:04 +0000 Subject: [PATCH 0775/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index e92b02191a..8c0cd9a36d 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -15,7 +15,7 @@ using MediaBrowser.Model.Plugins; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Emby.Server.Implementations +namespace Emby.Server.Implementations.Plugins { /// <summary> /// Defines the <see cref="PluginManager" />. From 0dcf6b09c1ad7913a27bf56b19716a0da957054e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:25:39 +0000 Subject: [PATCH 0776/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 8c0cd9a36d..874e88c574 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -42,7 +42,7 @@ namespace Emby.Server.Implementations.Plugins /// <param name="imagesPath">The image cache path.</param> /// <param name="appVersion">The application version.</param> public PluginManager( - ILoggerFactory loggerfactory, + ILogger<PluginManager> logger, IApplicationHost appHost, ServerConfiguration config, string pluginsPath, From 4153551dfcd498114d240b0311b20df8799c1593 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 08:26:11 +0000 Subject: [PATCH 0777/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 874e88c574..2e4b23bcf8 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -413,7 +413,7 @@ namespace Emby.Server.Implementations.Plugins /// </summary> /// <param name="type">The type.</param> /// <returns>System.Object.</returns> - private object? CreatePluginInstance(Type type) + private IPlugin? CreatePluginInstance(Type type) { // Find the record for this plugin. var plugin = GetPluginByType(type); From 5a3efc526631b7f774b17ea5a8a54130696b6e25 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 09:04:40 +0000 Subject: [PATCH 0778/1930] Changes as required. --- .../ApplicationHost.cs | 3 +- .../Plugins/PluginManager.cs | 102 +++++++----------- MediaBrowser.Common/Plugins/BasePlugin.cs | 41 +------ 3 files changed, 42 insertions(+), 104 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 216cb5e758..d7bc83f3a5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -35,6 +35,7 @@ using Emby.Server.Implementations.LiveTv; using Emby.Server.Implementations.Localization; using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Playlists; +using Emby.Server.Implementations.Plugins; using Emby.Server.Implementations.QuickConnect; using Emby.Server.Implementations.ScheduledTasks; using Emby.Server.Implementations.Security; @@ -281,7 +282,7 @@ namespace Emby.Server.Implementations ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; _pluginManager = new PluginManager( - LoggerFactory, + LoggerFactory.CreateLogger<PluginManager>(), this, ServerConfigurationManager.Configuration, ApplicationPaths.PluginsPath, diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 2e4b23bcf8..151e2c2036 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -35,7 +35,7 @@ namespace Emby.Server.Implementations.Plugins /// <summary> /// Initializes a new instance of the <see cref="PluginManager"/> class. /// </summary> - /// <param name="loggerfactory">The <see cref="ILoggerFactory"/>.</param> + /// <param name="logger">The <see cref="ILogger"/>.</param> /// <param name="appHost">The <see cref="IApplicationHost"/>.</param> /// <param name="config">The <see cref="ServerConfiguration"/>.</param> /// <param name="pluginsPath">The plugin path.</param> @@ -49,13 +49,12 @@ namespace Emby.Server.Implementations.Plugins string imagesPath, Version appVersion) { - _logger = loggerfactory.CreateLogger<PluginManager>(); + _logger = _logger ?? throw new ArgumentNullException(nameof(logger)); _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); - _jsonOptions = JsonDefaults.GetCamelCaseOptions(); + _jsonOptions = JsonDefaults.GetOptions(); _config = config; _appHost = appHost; - _imagesPath = imagesPath; _nextVersion = new Version(_appVersion.Major, _appVersion.Minor + 2, _appVersion.Build, _appVersion.Revision); _minimumVersion = new Version(0, 0, 0, 1); _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>(); @@ -273,62 +272,6 @@ namespace Emby.Server.Implementations.Plugins } } - private void CopyFiles(string source, string destination, bool overwrite, string searchPattern) - { - FileInfo[] files; - try - { - files = new DirectoryInfo(source).GetFiles(searchPattern); - } - catch (Exception ex) - { - _logger.LogDebug(ex, "Error retrieving file list."); - return; - } - - foreach (FileInfo file in files) - { - try - { - file.CopyTo(Path.Combine(destination, file.Name), overwrite); - } - catch (Exception ex) - { - _logger.LogDebug(ex, "Error copying file {Name}", file.Name); - } - } - } - - /// <summary> - /// Changes the status of the other versions of the plugin to "Superceded". - /// </summary> - /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param> - private void UpdateSuccessors(LocalPlugin plugin) - { - // This value is memory only - so that the web will show restart required. - plugin.Manifest.Status = PluginStatus.Restart; - - // Detect whether there is another version of this plugin that needs disabling. - var predecessor = _plugins.OrderByDescending(p => p.Version) - .FirstOrDefault( - p => p.Id.Equals(plugin.Id) - && p.IsEnabledAndSupported - && p.Version != plugin.Version); - - if (predecessor == null) - { - return; - } - - // migrate settings across from the last active version if they don't exist. - CopyFiles(predecessor.Path, plugin.Path, false, "*.xml"); - - if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded)) - { - _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); - } - } - /// <summary> /// Disable the plugin. /// </summary> @@ -429,19 +372,19 @@ namespace Emby.Server.Implementations.Plugins if (plugin == null) { // Create a dummy record for the providers. + // TODO: remove this code, if all provided have been released as separate plugins. plugin = new LocalPlugin( - pInstance.AssemblyFilePath, + instance.AssemblyFilePath, true, new PluginManifest { - Guid = pInstance.Id, + Guid = instance.Id, Status = PluginStatus.Active, - Name = pInstance.Name, - Version = pInstance.Version.ToString(), - MaxAbi = _nextVersion.ToString() + Name = instance.Name, + Version = instance.Version.ToString() }) { - Instance = pInstance + Instance = instance }; _plugins.Add(plugin); @@ -707,5 +650,32 @@ namespace Emby.Server.Implementations.Plugins // Only want plugin folders which have files. return versions.Where(p => p.DllFiles.Count != 0); } + + /// <summary> + /// Changes the status of the other versions of the plugin to "Superceded". + /// </summary> + /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param> + private void UpdateSuccessors(LocalPlugin plugin) + { + // This value is memory only - so that the web will show restart required. + plugin.Manifest.Status = PluginStatus.Restart; + + // Detect whether there is another version of this plugin that needs disabling. + var predecessor = _plugins.OrderByDescending(p => p.Version) + .FirstOrDefault( + p => p.Id.Equals(plugin.Id) + && p.IsEnabledAndSupported + && p.Version != plugin.Version); + + if (predecessor == null) + { + return; + } + + if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded)) + { + _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); + } + } } } diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 5756f8852c..5750c59c42 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -134,25 +134,11 @@ namespace MediaBrowser.Common.Plugins var assemblyName = assembly.GetName(); var assemblyFilePath = assembly.Location; - // Find out the plugin folder. - bool inPluginFolder = assemblyFilePath.StartsWith(ApplicationPaths.PluginsPath, StringComparison.OrdinalIgnoreCase); - string path, dataFolderPath; - - var configurationFileName = Path.ChangeExtension(Path.GetFileName(assemblyFilePath), ".xml"); - if (inPluginFolder) + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + if (!Directory.Exists(dataFolderPath)) { - // Normal plugin. - path = assemblyFilePath.Substring(ApplicationPaths.PluginsPath.Length).Split('\\', StringSplitOptions.RemoveEmptyEntries)[0]; - dataFolderPath = Path.Combine( - Path.Combine(ApplicationPaths.PluginsPath, path), - configurationFileName); - ConfigurationFilePath = dataFolderPath; - } - else - { - // Provider - dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - ConfigurationFilePath = Path.Combine(ApplicationPaths.PluginConfigurationsPath, configurationFileName); + // Try again with the version number appended to the folder name. + dataFolderPath = dataFolderPath + "_" + Version.ToString(); } assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); @@ -165,25 +151,6 @@ namespace MediaBrowser.Common.Plugins assemblyPlugin.SetId(assemblyId); } - - // TODO : Remove this, once migration support is ceased. - if (inPluginFolder) - { - var oldConfigFilePath = Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); - - if (!File.Exists(ConfigurationFilePath) && File.Exists(oldConfigFilePath)) - { - // Migrate pre 10.7 settings, as different plugin versions may have different settings. - try - { - File.Copy(oldConfigFilePath, ConfigurationFilePath); - } - catch - { - // Unable to migrate settings. - } - } - } } if (this is IHasPluginConfiguration hasPluginConfiguration) From 486148dd6b18ec336ca076b8ec0a23d257789683 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 09:44:57 +0000 Subject: [PATCH 0779/1930] Removed maxAbi --- .../ApplicationHost.cs | 1 - .../Plugins/PluginManager.cs | 11 +- .../Updates/InstallationManager.cs | 18 +- MediaBrowser.Common/Plugins/BasePlugin.cs | 210 ----------------- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 218 ++++++++++++++++++ MediaBrowser.Model/Updates/VersionInfo.cs | 7 - 6 files changed, 224 insertions(+), 241 deletions(-) create mode 100644 MediaBrowser.Common/Plugins/BasePluginOfT.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d7bc83f3a5..b91ba6b6ca 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -286,7 +286,6 @@ namespace Emby.Server.Implementations this, ServerConfigurationManager.Configuration, ApplicationPaths.PluginsPath, - ApplicationPaths.CachePath, ApplicationVersion); } diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 151e2c2036..4c508279c5 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -39,17 +39,15 @@ namespace Emby.Server.Implementations.Plugins /// <param name="appHost">The <see cref="IApplicationHost"/>.</param> /// <param name="config">The <see cref="ServerConfiguration"/>.</param> /// <param name="pluginsPath">The plugin path.</param> - /// <param name="imagesPath">The image cache path.</param> /// <param name="appVersion">The application version.</param> public PluginManager( ILogger<PluginManager> logger, IApplicationHost appHost, ServerConfiguration config, string pluginsPath, - string imagesPath, Version appVersion) { - _logger = _logger ?? throw new ArgumentNullException(nameof(logger)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); _jsonOptions = JsonDefaults.GetOptions(); @@ -509,17 +507,12 @@ namespace Emby.Server.Implementations.Plugins targetAbi = _minimumVersion; } - if (!Version.TryParse(manifest.MaxAbi, out var maxAbi)) - { - maxAbi = _appVersion; - } - if (!Version.TryParse(manifest.Version, out version)) { manifest.Version = _minimumVersion.ToString(); } - return new LocalPlugin(dir, _appVersion >= targetAbi && _appVersion <= maxAbi, manifest); + return new LocalPlugin(dir, _appVersion >= targetAbi, manifest); } // No metafile, so lets see if the folder is versioned. diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 70424369bd..cf059fb97f 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -132,13 +132,8 @@ namespace Emby.Server.Implementations.Updates targetAbi = minimumVersion; } - if (!Version.TryParse(ver.MaxAbi, out var maxAbi)) - { - maxAbi = _applicationHost.ApplicationVersion; - } - // Only show plugins that fall between targetAbi and maxAbi - if (_applicationHost.ApplicationVersion >= targetAbi && _applicationHost.ApplicationVersion <= maxAbi) + if (_applicationHost.ApplicationVersion >= targetAbi) { continue; } @@ -200,19 +195,15 @@ namespace Emby.Server.Implementations.Updates // Update the manifests, if anything changes. if (plugin != null) { - bool noChange = string.Equals(plugin.Manifest.MaxAbi, version.MaxAbi, StringComparison.Ordinal) - || string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal); - if (!noChange) + if (!string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal)) { - plugin.Manifest.MaxAbi = version.MaxAbi ?? string.Empty; plugin.Manifest.TargetAbi = version.TargetAbi ?? string.Empty; _pluginManager.SaveManifest(plugin.Manifest, plugin.Path); } } // Remove versions with a target abi that is greater then the current application version. - if ((Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi) - || (Version.TryParse(version.MaxAbi, out var maxAbi) && _applicationHost.ApplicationVersion > maxAbi)) + if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi) { package.Versions.RemoveAt(i); } @@ -283,8 +274,7 @@ namespace Emby.Server.Implementations.Updates var appVer = _applicationHost.ApplicationVersion; var availableVersions = package.Versions - .Where(x => (string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer) - && (string.IsNullOrEmpty(x.MaxAbi) || Version.Parse(x.MaxAbi) >= appVer)); + .Where(x => string.IsNullOrEmpty(x.TargetAbi) || Version.Parse(x.TargetAbi) <= appVer); if (specificVersion != null) { diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 5750c59c42..e228ae7ec5 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -1,5 +1,3 @@ -#pragma warning disable SA1402 - using System; using System.IO; using System.Reflection; @@ -94,212 +92,4 @@ namespace MediaBrowser.Common.Plugins Id = assemblyId; } } - - /// <summary> - /// Provides a common base class for all plugins. - /// </summary> - /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam> - public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration - where TConfigurationType : BasePluginConfiguration - { - /// <summary> - /// The configuration sync lock. - /// </summary> - private readonly object _configurationSyncLock = new object(); - - /// <summary> - /// The configuration save lock. - /// </summary> - private readonly object _configurationSaveLock = new object(); - - private Action<string> _directoryCreateFn; - - /// <summary> - /// The configuration. - /// </summary> - private TConfigurationType _configuration; - - /// <summary> - /// Initializes a new instance of the <see cref="BasePlugin{TConfigurationType}" /> class. - /// </summary> - /// <param name="applicationPaths">The application paths.</param> - /// <param name="xmlSerializer">The XML serializer.</param> - protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) - { - ApplicationPaths = applicationPaths; - XmlSerializer = xmlSerializer; - if (this is IPluginAssembly assemblyPlugin) - { - var assembly = GetType().Assembly; - var assemblyName = assembly.GetName(); - var assemblyFilePath = assembly.Location; - - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - if (!Directory.Exists(dataFolderPath)) - { - // Try again with the version number appended to the folder name. - dataFolderPath = dataFolderPath + "_" + Version.ToString(); - } - - assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); - - var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); - if (idAttributes.Length > 0) - { - var attribute = (GuidAttribute)idAttributes[0]; - var assemblyId = new Guid(attribute.Value); - - assemblyPlugin.SetId(assemblyId); - } - } - - if (this is IHasPluginConfiguration hasPluginConfiguration) - { - hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); - } - } - - /// <summary> - /// Gets the application paths. - /// </summary> - /// <value>The application paths.</value> - protected IApplicationPaths ApplicationPaths { get; private set; } - - /// <summary> - /// Gets the XML serializer. - /// </summary> - /// <value>The XML serializer.</value> - protected IXmlSerializer XmlSerializer { get; private set; } - - /// <summary> - /// Gets the type of configuration this plugin uses. - /// </summary> - /// <value>The type of the configuration.</value> - public Type ConfigurationType => typeof(TConfigurationType); - - /// <summary> - /// Gets or sets the event handler that is triggered when this configuration changes. - /// </summary> - public EventHandler<BasePluginConfiguration> ConfigurationChanged { get; set; } - - /// <summary> - /// Gets the name the assembly file. - /// </summary> - /// <value>The name of the assembly file.</value> - protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath); - - /// <summary> - /// Gets or sets the plugin configuration. - /// </summary> - /// <value>The configuration.</value> - public TConfigurationType Configuration - { - get - { - // Lazy load - if (_configuration == null) - { - lock (_configurationSyncLock) - { - if (_configuration == null) - { - _configuration = LoadConfiguration(); - } - } - } - - return _configuration; - } - - protected set => _configuration = value; - } - - /// <summary> - /// Gets the name of the configuration file. Subclasses should override. - /// </summary> - /// <value>The name of the configuration file.</value> - public virtual string ConfigurationFileName => Path.ChangeExtension(AssemblyFileName, ".xml"); - - /// <summary> - /// Gets the full path to the configuration file. - /// </summary> - /// <value>The configuration file path.</value> - public string ConfigurationFilePath { get; } - - /// <summary> - /// Gets the plugin configuration. - /// </summary> - /// <value>The configuration.</value> - BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration; - - /// <inheritdoc /> - public void SetStartupInfo(Action<string> directoryCreateFn) - { - // hack alert, until the .net core transition is complete - _directoryCreateFn = directoryCreateFn; - } - - private TConfigurationType LoadConfiguration() - { - var path = ConfigurationFilePath; - - try - { - return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path); - } - catch - { - var config = (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); - SaveConfiguration(config); - return config; - } - } - - /// <summary> - /// Saves the current configuration to the file system. - /// </summary> - /// <param name="config">Configuration to save.</param> - public virtual void SaveConfiguration(TConfigurationType config) - { - lock (_configurationSaveLock) - { - _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); - - XmlSerializer.SerializeToFile(config, ConfigurationFilePath); - } - } - - /// <summary> - /// Saves the current configuration to the file system. - /// </summary> - public virtual void SaveConfiguration() - { - SaveConfiguration(Configuration); - } - - /// <inheritdoc /> - public virtual void UpdateConfiguration(BasePluginConfiguration configuration) - { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - Configuration = (TConfigurationType)configuration; - - SaveConfiguration(Configuration); - - ConfigurationChanged?.Invoke(this, configuration); - } - - /// <inheritdoc /> - public override PluginInfo GetPluginInfo() - { - var info = base.GetPluginInfo(); - - info.ConfigurationFileName = ConfigurationFileName; - - return info; - } - } } diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs new file mode 100644 index 0000000000..66aec92ab6 --- /dev/null +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -0,0 +1,218 @@ +#pragma warning disable SA1649 // File name should match first type name +using System; +using System.IO; +using System.Runtime.InteropServices; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace MediaBrowser.Common.Plugins +{ + /// <summary> + /// Provides a common base class for all plugins. + /// </summary> + /// <typeparam name="TConfigurationType">The type of the T configuration type.</typeparam> + public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration + where TConfigurationType : BasePluginConfiguration + { + /// <summary> + /// The configuration sync lock. + /// </summary> + private readonly object _configurationSyncLock = new object(); + + /// <summary> + /// The configuration save lock. + /// </summary> + private readonly object _configurationSaveLock = new object(); + + private Action<string> _directoryCreateFn; + + /// <summary> + /// The configuration. + /// </summary> + private TConfigurationType _configuration; + + /// <summary> + /// Initializes a new instance of the <see cref="BasePlugin{TConfigurationType}" /> class. + /// </summary> + /// <param name="applicationPaths">The application paths.</param> + /// <param name="xmlSerializer">The XML serializer.</param> + protected BasePlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + { + ApplicationPaths = applicationPaths; + XmlSerializer = xmlSerializer; + if (this is IPluginAssembly assemblyPlugin) + { + var assembly = GetType().Assembly; + var assemblyName = assembly.GetName(); + var assemblyFilePath = assembly.Location; + + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + if (!Directory.Exists(dataFolderPath)) + { + // Try again with the version number appended to the folder name. + dataFolderPath = dataFolderPath + "_" + Version.ToString(); + } + + assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); + + var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); + if (idAttributes.Length > 0) + { + var attribute = (GuidAttribute)idAttributes[0]; + var assemblyId = new Guid(attribute.Value); + + assemblyPlugin.SetId(assemblyId); + } + } + + if (this is IHasPluginConfiguration hasPluginConfiguration) + { + hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); + } + } + + /// <summary> + /// Gets the application paths. + /// </summary> + /// <value>The application paths.</value> + protected IApplicationPaths ApplicationPaths { get; private set; } + + /// <summary> + /// Gets the XML serializer. + /// </summary> + /// <value>The XML serializer.</value> + protected IXmlSerializer XmlSerializer { get; private set; } + + /// <summary> + /// Gets the type of configuration this plugin uses. + /// </summary> + /// <value>The type of the configuration.</value> + public Type ConfigurationType => typeof(TConfigurationType); + + /// <summary> + /// Gets or sets the event handler that is triggered when this configuration changes. + /// </summary> + public EventHandler<BasePluginConfiguration> ConfigurationChanged { get; set; } + + /// <summary> + /// Gets the name the assembly file. + /// </summary> + /// <value>The name of the assembly file.</value> + protected string AssemblyFileName => Path.GetFileName(AssemblyFilePath); + + /// <summary> + /// Gets or sets the plugin configuration. + /// </summary> + /// <value>The configuration.</value> + public TConfigurationType Configuration + { + get + { + // Lazy load + if (_configuration == null) + { + lock (_configurationSyncLock) + { + if (_configuration == null) + { + _configuration = LoadConfiguration(); + } + } + } + + return _configuration; + } + + protected set => _configuration = value; + } + + /// <summary> + /// Gets the name of the configuration file. Subclasses should override. + /// </summary> + /// <value>The name of the configuration file.</value> + public virtual string ConfigurationFileName => Path.ChangeExtension(AssemblyFileName, ".xml"); + + /// <summary> + /// Gets the full path to the configuration file. + /// </summary> + /// <value>The configuration file path.</value> + public string ConfigurationFilePath { get; } + + /// <summary> + /// Gets the plugin configuration. + /// </summary> + /// <value>The configuration.</value> + BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration; + + /// <inheritdoc /> + public void SetStartupInfo(Action<string> directoryCreateFn) + { + // hack alert, until the .net core transition is complete + _directoryCreateFn = directoryCreateFn; + } + + /// <summary> + /// Saves the current configuration to the file system. + /// </summary> + /// <param name="config">Configuration to save.</param> + public virtual void SaveConfiguration(TConfigurationType config) + { + lock (_configurationSaveLock) + { + _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); + + XmlSerializer.SerializeToFile(config, ConfigurationFilePath); + } + } + + /// <summary> + /// Saves the current configuration to the file system. + /// </summary> + public virtual void SaveConfiguration() + { + SaveConfiguration(Configuration); + } + + /// <inheritdoc /> + public virtual void UpdateConfiguration(BasePluginConfiguration configuration) + { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + + Configuration = (TConfigurationType)configuration; + + SaveConfiguration(Configuration); + + ConfigurationChanged?.Invoke(this, configuration); + } + + /// <inheritdoc /> + public override PluginInfo GetPluginInfo() + { + var info = base.GetPluginInfo(); + + info.ConfigurationFileName = ConfigurationFileName; + + return info; + } + + private TConfigurationType LoadConfiguration() + { + var path = ConfigurationFilePath; + + try + { + return (TConfigurationType)XmlSerializer.DeserializeFromFile(typeof(TConfigurationType), path); + } + catch + { + var config = (TConfigurationType)Activator.CreateInstance(typeof(TConfigurationType)); + SaveConfiguration(config); + return config; + } + } + } +} diff --git a/MediaBrowser.Model/Updates/VersionInfo.cs b/MediaBrowser.Model/Updates/VersionInfo.cs index 503dba0a14..209092265e 100644 --- a/MediaBrowser.Model/Updates/VersionInfo.cs +++ b/MediaBrowser.Model/Updates/VersionInfo.cs @@ -43,13 +43,6 @@ namespace MediaBrowser.Model.Updates [JsonPropertyName("targetAbi")] public string? TargetAbi { get; set; } - /// <summary> - /// Gets or sets the maximum ABI that this version will work with. - /// </summary> - /// <value>The target ABI version.</value> - [JsonPropertyName("maxAbi")] - public string? MaxAbi { get; set; } - /// <summary> /// Gets or sets the source URL. /// </summary> From ac03ef57c927ca27900b415ae45194e5d23be664 Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 19 Dec 2020 01:47:31 +0800 Subject: [PATCH 0780/1930] allow empty video encoder profile Co-authored-by: Cody Robibero <cody@robibe.ro> --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index a8a094e63d..73ede7c5a4 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1127,8 +1127,8 @@ namespace MediaBrowser.Controller.MediaEncoding targetVideoCodec = "hevc"; } - var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault(); - profile = Regex.Replace(profile, @"\s+", String.Empty); + var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault() ?? string.Empty; + profile = Regex.Replace(profile, @"\s+", string.Empty); // We only transcode to HEVC 8-bit for now, force Main Profile. if (profile.Contains("main 10", StringComparison.OrdinalIgnoreCase) From 07ee98b65f3933770aedca3cf995d1dc0c3f39e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Predrag=20Ljubenovi=C4=87?= <predragljubenovic@gmail.com> Date: Fri, 18 Dec 2020 16:42:21 +0000 Subject: [PATCH 0781/1930] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- Emby.Server.Implementations/Localization/Core/sr.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 8da92f3099..2984ed972e 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -114,5 +114,8 @@ "TasksLibraryCategory": "Библиотека", "TasksMaintenanceCategory": "Одржавање", "TaskCleanActivityLogDescription": "Брише историју активности старију од конфигурисаног броја година.", - "TaskCleanActivityLog": "Очисти историју активности" + "TaskCleanActivityLog": "Очисти историју активности", + "Undefined": "Недефинисано", + "Forced": "Форсирано", + "Default": "Подразумевано" } From ce19f2be55c7484488bebfd29bd42c1f082ae888 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 20:37:35 +0000 Subject: [PATCH 0782/1930] Renamed Guid property to Id --- .../Plugins/PluginManager.cs | 4 +-- .../Updates/InstallationManager.cs | 12 +++---- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 17 ++++++++-- MediaBrowser.Common/Plugins/LocalPlugin.cs | 6 ++-- MediaBrowser.Common/Plugins/PluginManifest.cs | 6 ++-- MediaBrowser.Model/Plugins/PluginPageInfo.cs | 34 +++++++++++++++---- .../Updates/InstallationInfo.cs | 8 +++-- MediaBrowser.Model/Updates/PackageInfo.cs | 6 ++-- .../Plugins/AudioDb/Plugin.cs | 2 +- .../Plugins/MusicBrainz/Plugin.cs | 2 +- MediaBrowser.Providers/Plugins/Omdb/Plugin.cs | 2 +- 11 files changed, 65 insertions(+), 34 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 4c508279c5..613e610d3f 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -376,7 +376,7 @@ namespace Emby.Server.Implementations.Plugins true, new PluginManifest { - Guid = instance.Id, + Id = instance.Id, Status = PluginStatus.Active, Name = instance.Name, Version = instance.Version.ToString() @@ -537,7 +537,7 @@ namespace Emby.Server.Implementations.Plugins Status = PluginStatus.Restart, Name = metafile, AutoUpdate = false, - Guid = metafile.GetMD5(), + Id = metafile.GetMD5(), TargetAbi = _appVersion.ToString(), Version = version.ToString() }; diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index cf059fb97f..267a338750 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -178,7 +178,7 @@ namespace Emby.Server.Implementations.Updates // Where repositories have the same content, the details from the first is taken. foreach (var package in await GetPackages(repository.Name ?? "Unnamed Repo", repository.Url, true, cancellationToken).ConfigureAwait(true)) { - if (!Guid.TryParse(package.Guid, out var packageGuid)) + if (!Guid.TryParse(package.Id, out var packageGuid)) { // Package doesn't have a valid GUID, skip. continue; @@ -245,7 +245,7 @@ namespace Emby.Server.Implementations.Updates if (guid != Guid.Empty) { - availablePackages = availablePackages.Where(x => Guid.Parse(x.Guid) == guid); + availablePackages = availablePackages.Where(x => Guid.Parse(x.Id) == guid); } if (specificVersion != null) @@ -290,7 +290,7 @@ namespace Emby.Server.Implementations.Updates yield return new InstallationInfo { Changelog = v.Changelog, - Guid = new Guid(package.Guid), + Id = new Guid(package.Id), Name = package.Name, Version = v.VersionNumber, SourceUrl = v.SourceUrl, @@ -414,7 +414,7 @@ namespace Emby.Server.Implementations.Updates { lock (_currentInstallationsLock) { - var install = _currentInstallations.Find(x => x.info.Guid == id); + var install = _currentInstallations.Find(x => x.info.Id == id); if (install == default((InstallationInfo, CancellationTokenSource))) { return false; @@ -512,7 +512,7 @@ namespace Emby.Server.Implementations.Updates var compatibleVersions = GetCompatibleVersions(pluginCatalog, plugin.Name, plugin.Id, minVersion: plugin.Version); var version = compatibleVersions.FirstOrDefault(y => y.Version > plugin.Version); - if (version != null && CompletedInstallations.All(x => x.Guid != version.Guid)) + if (version != null && CompletedInstallations.All(x => x.Id != version.Id)) { yield return version; } @@ -577,7 +577,7 @@ namespace Emby.Server.Implementations.Updates private async Task<bool> InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) { // Set last update time if we were installed before - LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Guid) && p.Version.Equals(package.Version)) + LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version)) ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version)); if (plugin != null) { diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index 66aec92ab6..e4e766472c 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Common.Plugins var assemblyFilePath = assembly.Location; var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - if (!Directory.Exists(dataFolderPath)) + if (!Directory.Exists(dataFolderPath) && Version != null) { // Try again with the version number appended to the folder name. dataFolderPath = dataFolderPath + "_" + Version.ToString(); @@ -137,7 +137,20 @@ namespace MediaBrowser.Common.Plugins /// Gets the full path to the configuration file. /// </summary> /// <value>The configuration file path.</value> - public string ConfigurationFilePath { get; } + public string ConfigurationFilePath + { + get + { + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(AssemblyFilePath)); + if (!Directory.Exists(dataFolderPath) && Version != null) + { + // Try again with the version number appended to the folder name. + return dataFolderPath + "_" + Version.ToString(); + } + + return dataFolderPath; + } + } /// <summary> /// Gets the plugin configuration. diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 8aded8b9bc..40ecb0a67b 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -1,8 +1,6 @@ #nullable enable using System; using System.Collections.Generic; -using System.Globalization; -using System.Reflection; using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins @@ -32,7 +30,7 @@ namespace MediaBrowser.Common.Plugins /// <summary> /// Gets the plugin id. /// </summary> - public Guid Id => Manifest.Guid; + public Guid Id => Manifest.Id; /// <summary> /// Gets the plugin name. @@ -110,7 +108,7 @@ namespace MediaBrowser.Common.Plugins /// <returns>A <see cref="PluginInfo"/> instance containing the information.</returns> public PluginInfo GetPluginInfo() { - var inst = Instance?.GetPluginInfo() ?? new PluginInfo(Manifest.Name, Version, Manifest.Description, Manifest.Guid, true); + var inst = Instance?.GetPluginInfo() ?? new PluginInfo(Manifest.Name, Version, Manifest.Description, Manifest.Id, true); inst.Status = Manifest.Status; inst.HasImage = !string.IsNullOrEmpty(Manifest.ImageUrl); return inst; diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 1bd17933c4..39ee450a6e 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -1,5 +1,6 @@ #nullable enable using System; +using System.Text.Json.Serialization; using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins @@ -27,9 +28,8 @@ namespace MediaBrowser.Common.Plugins /// <summary> /// Gets or sets the Global Unique Identifier for the plugin. /// </summary> -#pragma warning disable CA1720 // Identifier contains type name - public Guid Guid { get; set; } -#pragma warning restore CA1720 // Identifier contains type name + [JsonPropertyName("Guid")] + public Guid Id { get; set; } /// <summary> /// Gets or sets the Name of the plugin. diff --git a/MediaBrowser.Model/Plugins/PluginPageInfo.cs b/MediaBrowser.Model/Plugins/PluginPageInfo.cs index ca72e19ee1..85c0aa204b 100644 --- a/MediaBrowser.Model/Plugins/PluginPageInfo.cs +++ b/MediaBrowser.Model/Plugins/PluginPageInfo.cs @@ -1,20 +1,40 @@ -#nullable disable -#pragma warning disable CS1591 +#nullable enable namespace MediaBrowser.Model.Plugins { + /// <summary> + /// Defines the <see cref="PluginPageInfo" />. + /// </summary> public class PluginPageInfo { - public string Name { get; set; } + /// <summary> + /// Gets or sets the name. + /// </summary> + public string Name { get; set; } = string.Empty; - public string DisplayName { get; set; } + /// <summary> + /// Gets or sets the display name. + /// </summary> + public string? DisplayName { get; set; } - public string EmbeddedResourcePath { get; set; } + /// <summary> + /// Gets or sets the resource path. + /// </summary> + public string EmbeddedResourcePath { get; set; } = string.Empty; + /// <summary> + /// Gets or sets a value indicating whether this plugin should appear in the main menu. + /// </summary> public bool EnableInMainMenu { get; set; } - public string MenuSection { get; set; } + /// <summary> + /// Gets or sets the menu section. + /// </summary> + public string? MenuSection { get; set; } - public string MenuIcon { get; set; } + /// <summary> + /// Gets or sets the menu icon. + /// </summary> + public string? MenuIcon { get; set; } } } diff --git a/MediaBrowser.Model/Updates/InstallationInfo.cs b/MediaBrowser.Model/Updates/InstallationInfo.cs index a6d80dba62..eebe1a9034 100644 --- a/MediaBrowser.Model/Updates/InstallationInfo.cs +++ b/MediaBrowser.Model/Updates/InstallationInfo.cs @@ -1,5 +1,6 @@ #nullable disable using System; +using System.Text.Json.Serialization; namespace MediaBrowser.Model.Updates { @@ -9,10 +10,11 @@ namespace MediaBrowser.Model.Updates public class InstallationInfo { /// <summary> - /// Gets or sets the guid. + /// Gets or sets the Id. /// </summary> - /// <value>The guid.</value> - public Guid Guid { get; set; } + /// <value>The Id.</value> + [JsonPropertyName("Guid")] + public Guid Id { get; set; } /// <summary> /// Gets or sets the name. diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 63fd717429..2d05ed636a 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Model.Updates public PackageInfo() { Versions = Array.Empty<VersionInfo>(); - Guid = string.Empty; + Id = string.Empty; Category = string.Empty; Name = string.Empty; Overview = string.Empty; @@ -65,9 +65,7 @@ namespace MediaBrowser.Model.Updates /// </summary> /// <value>The name.</value> [JsonPropertyName("guid")] -#pragma warning disable CA1720 // Identifier contains type name - public string Guid { get; set; } -#pragma warning restore CA1720 // Identifier contains type name + public string Id { get; set; } /// <summary> /// Gets or sets the versions. diff --git a/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs b/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs index b5bd72ff0d..ba0d7b5697 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/Plugin.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs index 90266e4409..43bd3a472f 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/Plugin.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using System; using System.Collections.Generic; diff --git a/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs b/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs index 41ca561643..d7f6781e50 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/Plugin.cs @@ -1,4 +1,4 @@ -#pragma warning disable CS1591 +#pragma warning disable CS1591 using System; using System.Collections.Generic; From 5d748c0e9f1ad87bece090934c5da6c4edacb8f7 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 20:52:44 +0000 Subject: [PATCH 0783/1930] Renamed to ImagePath --- Jellyfin.Api/Controllers/PluginsController.cs | 10 +++++----- MediaBrowser.Common/Plugins/LocalPlugin.cs | 2 +- MediaBrowser.Common/Plugins/PluginManifest.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 1365764fba..365bb2248c 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -303,16 +303,16 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - var imgPath = Path.Combine(plugin.Path, plugin.Manifest.ImageUrl ?? string.Empty); + var imagePath = Path.Combine(plugin.Path, plugin.Manifest.ImagePath ?? string.Empty); if (((ServerConfiguration)_config.CommonConfiguration).DisablePluginImages - || plugin.Manifest.ImageUrl == null - || !System.IO.File.Exists(imgPath)) + || plugin.Manifest.ImagePath == null + || !System.IO.File.Exists(imagePath)) { return NotFound(); } - imgPath = Path.Combine(plugin.Path, plugin.Manifest.ImageUrl); - return PhysicalFile(imgPath, MimeTypes.GetMimeType(imgPath)); + imagePath = Path.Combine(plugin.Path, plugin.Manifest.ImagePath); + return PhysicalFile(imagePath, MimeTypes.GetMimeType(imagePath)); } /// <summary> diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 40ecb0a67b..23b6cfa81a 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -110,7 +110,7 @@ namespace MediaBrowser.Common.Plugins { var inst = Instance?.GetPluginInfo() ?? new PluginInfo(Manifest.Name, Version, Manifest.Description, Manifest.Id, true); inst.Status = Manifest.Status; - inst.HasImage = !string.IsNullOrEmpty(Manifest.ImageUrl); + inst.HasImage = !string.IsNullOrEmpty(Manifest.ImagePath); return inst; } diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 39ee450a6e..755ccafda1 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -80,6 +80,6 @@ namespace MediaBrowser.Common.Plugins /// Gets or sets a value indicating whether this plugin has an image. /// Image must be located in the local plugin folder. /// </summary> - public string? ImageUrl { get; set; } + public string? ImagePath { get; set; } } } From 5c4fdaa2530cd1b0b9dc88352d92c546ce176430 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:05:27 +0000 Subject: [PATCH 0784/1930] MaxAbi property removed. --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- MediaBrowser.Common/Plugins/PluginManifest.cs | 5 ----- MediaBrowser.Model/Plugins/PluginStatus.cs | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 267a338750..630ede667c 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -132,7 +132,7 @@ namespace Emby.Server.Implementations.Updates targetAbi = minimumVersion; } - // Only show plugins that fall between targetAbi and maxAbi + // Only show plugins that fall between targetAbi. if (_applicationHost.ApplicationVersion >= targetAbi) { continue; diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 755ccafda1..9c45e5d950 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -51,11 +51,6 @@ namespace MediaBrowser.Common.Plugins /// </summary> public string TargetAbi { get; set; } = string.Empty; - /// <summary> - /// Gets or sets the upper compatibility version for the plugin. - /// </summary> - public string MaxAbi { get; set; } = string.Empty; - /// <summary> /// Gets or sets the timestamp of the plugin. /// </summary> diff --git a/MediaBrowser.Model/Plugins/PluginStatus.cs b/MediaBrowser.Model/Plugins/PluginStatus.cs index 3ea05174fd..4b9b9bbeee 100644 --- a/MediaBrowser.Model/Plugins/PluginStatus.cs +++ b/MediaBrowser.Model/Plugins/PluginStatus.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Model.Plugins Disabled = -1, /// <summary> - /// This plugin does not meet the TargetAbi / MaxAbi requirements. + /// This plugin does not meet the TargetAbi requirements. /// </summary> NotSupported = -2, From 46a64deb66a01ad95481147de977796e01e73329 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:07:24 +0000 Subject: [PATCH 0785/1930] Update MediaBrowser.Model/Updates/PackageInfo.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- MediaBrowser.Model/Updates/PackageInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 2d05ed636a..8f7d7ede6a 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -79,7 +79,7 @@ namespace MediaBrowser.Model.Updates /// <summary> /// Gets or sets the image url for the package. /// </summary> - [JsonPropertyName("imageUrl")] - public string? ImageUrl { get; set; } + [JsonPropertyName("imagePath")] + public string? ImagePath { get; set; } } } From cb793af30e5785f2063e98802cfa65917cde0a46 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:11:29 +0000 Subject: [PATCH 0786/1930] Renamed guid to id --- .../Updates/InstallationManager.cs | 10 +++++----- MediaBrowser.Common/Updates/IInstallationManager.cs | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 630ede667c..fa62c08589 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -235,7 +235,7 @@ namespace Emby.Server.Implementations.Updates public IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, string? name = null, - Guid? guid = default, + Guid? id = default, Version? specificVersion = null) { if (name != null) @@ -243,9 +243,9 @@ namespace Emby.Server.Implementations.Updates availablePackages = availablePackages.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } - if (guid != Guid.Empty) + if (id != Guid.Empty) { - availablePackages = availablePackages.Where(x => Guid.Parse(x.Id) == guid); + availablePackages = availablePackages.Where(x => Guid.Parse(x.Id) == id); } if (specificVersion != null) @@ -260,11 +260,11 @@ namespace Emby.Server.Implementations.Updates public IEnumerable<InstallationInfo> GetCompatibleVersions( IEnumerable<PackageInfo> availablePackages, string? name = null, - Guid? guid = default, + Guid? id = default, Version? minVersion = null, Version? specificVersion = null) { - var package = FilterPackages(availablePackages, name, guid, specificVersion).FirstOrDefault(); + var package = FilterPackages(availablePackages, name, id, specificVersion).FirstOrDefault(); // Package not found in repository if (package == null) diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index dd9e0cc3f9..4c8a6e959a 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -41,14 +41,14 @@ namespace MediaBrowser.Common.Updates /// </summary> /// <param name="availablePackages">The available packages.</param> /// <param name="name">The name of the plugin.</param> - /// <param name="guid">The id of the plugin.</param> + /// <param name="id">The id of the plugin.</param> /// <param name="specificVersion">The version of the plugin.</param> /// <returns>All plugins matching the requirements.</returns> IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, string? name = null, #pragma warning disable CA1720 // Identifier contains type name - Guid? guid = default, + Guid? id = default, #pragma warning restore CA1720 // Identifier contains type name Version? specificVersion = null); @@ -57,7 +57,7 @@ namespace MediaBrowser.Common.Updates /// </summary> /// <param name="availablePackages">The available packages.</param> /// <param name="name">The name.</param> - /// <param name="guid">The guid of the plugin.</param> + /// <param name="id">The id of the plugin.</param> /// <param name="minVersion">The minimum required version of the plugin.</param> /// <param name="specificVersion">The specific version of the plugin to install.</param> /// <returns>All compatible versions ordered from newest to oldest.</returns> @@ -65,7 +65,7 @@ namespace MediaBrowser.Common.Updates IEnumerable<PackageInfo> availablePackages, string? name = null, #pragma warning disable CA1720 // Identifier contains type name - Guid? guid = default, + Guid? id = default, #pragma warning restore CA1720 // Identifier contains type name Version? minVersion = null, Version? specificVersion = null); From 4cc19be173baab9bf93a310db6790d9c33e8ad17 Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:14:38 +0000 Subject: [PATCH 0787/1930] removed compiler directives. --- MediaBrowser.Common/Updates/IInstallationManager.cs | 4 ---- MediaBrowser.Model/Updates/PackageInfo.cs | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 4c8a6e959a..0844c2d792 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -47,9 +47,7 @@ namespace MediaBrowser.Common.Updates IEnumerable<PackageInfo> FilterPackages( IEnumerable<PackageInfo> availablePackages, string? name = null, -#pragma warning disable CA1720 // Identifier contains type name Guid? id = default, -#pragma warning restore CA1720 // Identifier contains type name Version? specificVersion = null); /// <summary> @@ -64,9 +62,7 @@ namespace MediaBrowser.Common.Updates IEnumerable<InstallationInfo> GetCompatibleVersions( IEnumerable<PackageInfo> availablePackages, string? name = null, -#pragma warning disable CA1720 // Identifier contains type name Guid? id = default, -#pragma warning restore CA1720 // Identifier contains type name Version? minVersion = null, Version? specificVersion = null); diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 8f7d7ede6a..0902e04409 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -77,7 +77,7 @@ namespace MediaBrowser.Model.Updates #pragma warning restore CA2227 // Collection properties should be read only /// <summary> - /// Gets or sets the image url for the package. + /// Gets or sets the image path for the package. /// </summary> [JsonPropertyName("imagePath")] public string? ImagePath { get; set; } From 4757824a826b05b281a83945ef39d19fa04981e4 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:55:50 +0000 Subject: [PATCH 0788/1930] Update Emby.Server.Implementations/Updates/InstallationManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index fa62c08589..4c2424c15b 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -132,7 +132,7 @@ namespace Emby.Server.Implementations.Updates targetAbi = minimumVersion; } - // Only show plugins that fall between targetAbi. + // Only show plugins that are greater than or equal to targetAbi. if (_applicationHost.ApplicationVersion >= targetAbi) { continue; From 3708ca8dbb0eff2eaa6c39b22cc1a2fd6e197dff Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:56:03 +0000 Subject: [PATCH 0789/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 613e610d3f..6ed9623f99 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -29,7 +29,6 @@ namespace Emby.Server.Implementations.Plugins private readonly IApplicationHost _appHost; private readonly ServerConfiguration _config; private readonly IList<LocalPlugin> _plugins; - private readonly Version _nextVersion; private readonly Version _minimumVersion; /// <summary> From 09f219bbcee78569537bb417de27f842879f2233 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:56:15 +0000 Subject: [PATCH 0790/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 6ed9623f99..dc2eca4a1c 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -52,7 +52,6 @@ namespace Emby.Server.Implementations.Plugins _jsonOptions = JsonDefaults.GetOptions(); _config = config; _appHost = appHost; - _nextVersion = new Version(_appVersion.Major, _appVersion.Minor + 2, _appVersion.Build, _appVersion.Revision); _minimumVersion = new Version(0, 0, 0, 1); _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>(); } From 5c3ebb63e62948ce9d405f7cbb82d4579e568833 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:56:35 +0000 Subject: [PATCH 0791/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index dc2eca4a1c..be08d8515e 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -113,7 +113,7 @@ namespace Emby.Server.Implementations.Plugins /// </summary> public void CreatePlugins() { - var createdPlugins = _appHost.GetExports<IPlugin>(CreatePluginInstance) + _ = _appHost.GetExports<IPlugin>(CreatePluginInstance) .Where(i => i != null) .ToArray(); } From a293024efd5ebf8d04b53de0999da78a64a857e5 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:56:54 +0000 Subject: [PATCH 0792/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index be08d8515e..1fd87273f7 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -280,7 +280,7 @@ namespace Emby.Server.Implementations.Plugins throw new ArgumentNullException(nameof(assembly)); } - var plugin = _plugins.Where(p => p.DllFiles.Contains(assembly.Location)).FirstOrDefault(); + var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location)); if (plugin == null) { // A plugin's assembly didn't cause this issue, so ignore it. From 9bf970e5c6d67a7e55c9faceda042e45ad06b532 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 21:59:14 +0000 Subject: [PATCH 0793/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Cody Robibero <cody@robibe.ro> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 1fd87273f7..d7292f21ba 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -629,11 +629,7 @@ namespace Emby.Server.Implementations.Plugins continue; } - if (manifest.Status != PluginStatus.Deleted) - { - manifest.Status = PluginStatus.Deleted; - SaveManifest(manifest, entry.Path); - } + ChangePluginState(entry, PluginStatus.Deleted); } } } From d34428f2f779dcd033f6cd060dc773515d2fbc6a Mon Sep 17 00:00:00 2001 From: Greenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 22:17:46 +0000 Subject: [PATCH 0794/1930] removed exception --- .../Plugins/PluginManager.cs | 134 ++++++++---------- 1 file changed, 59 insertions(+), 75 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index d7292f21ba..32646d1bf2 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.Plugins // Now load the assemblies.. foreach (var plugin in _plugins) { - CheckIfStillSuperceded(plugin); + UpdatePluginSuperceedStatus(plugin); if (plugin.IsEnabledAndSupported == false) { @@ -134,7 +134,7 @@ namespace Emby.Server.Implementations.Plugins continue; } - CheckIfStillSuperceded(plugin); + UpdatePluginSuperceedStatus(plugin); if (!plugin.IsEnabledAndSupported) { continue; @@ -172,7 +172,7 @@ namespace Emby.Server.Implementations.Plugins // Load the plugin. var plugin = LoadManifest(folder); // Make sure we haven't already loaded this. - if (plugin == null || _plugins.Any(p => p.Manifest.Equals(plugin.Manifest))) + if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest))) { return; } @@ -435,7 +435,7 @@ namespace Emby.Server.Implementations.Plugins } } - private void CheckIfStillSuperceded(LocalPlugin plugin) + private void UpdatePluginSuperceedStatus(LocalPlugin plugin) { if (plugin.Manifest.Status != PluginStatus.Superceded) { @@ -464,7 +464,6 @@ namespace Emby.Server.Implementations.Plugins { Directory.Delete(plugin.Path, true); _logger.LogDebug("Deleted {Path}", plugin.Path); - _plugins.Remove(plugin); } #pragma warning disable CA1031 // Do not catch general exception types catch @@ -476,79 +475,69 @@ namespace Emby.Server.Implementations.Plugins return _plugins.Remove(plugin); } - private LocalPlugin? LoadManifest(string dir) + private LocalPlugin LoadManifest(string dir) { - try + Version? version; + PluginManifest? manifest = null; + var metafile = Path.Combine(dir, "meta.json"); + if (File.Exists(metafile)) { - Version? version; - PluginManifest? manifest = null; - var metafile = Path.Combine(dir, "meta.json"); - if (File.Exists(metafile)) + try { - try - { - var data = File.ReadAllText(metafile, Encoding.UTF8); - manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions); - } + var data = File.ReadAllText(metafile, Encoding.UTF8); + manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions); + } #pragma warning disable CA1031 // Do not catch general exception types - catch (Exception ex) + catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types - { - _logger.LogError(ex, "Error deserializing {Path}.", dir); - } - } - - if (manifest != null) { - if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) - { - targetAbi = _minimumVersion; - } - - if (!Version.TryParse(manifest.Version, out version)) - { - manifest.Version = _minimumVersion.ToString(); - } - - return new LocalPlugin(dir, _appVersion >= targetAbi, manifest); + _logger.LogError(ex, "Error deserializing {Path}.", dir); } - - // No metafile, so lets see if the folder is versioned. - // TODO: Phase this support out in future versions. - metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; - int versionIndex = dir.LastIndexOf('_'); - if (versionIndex != -1) - { - // Get the version number from the filename if possible. - metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex]; - version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion; - } - else - { - // Un-versioned folder - Add it under the path name and version it suitable for this instance. - version = _appVersion; - } - - // Auto-create a plugin manifest, so we can disable it, if it fails to load. - manifest = new PluginManifest - { - Status = PluginStatus.Restart, - Name = metafile, - AutoUpdate = false, - Id = metafile.GetMD5(), - TargetAbi = _appVersion.ToString(), - Version = version.ToString() - }; - - return new LocalPlugin(dir, true, manifest); } -#pragma warning disable CA1031 // Do not catch general exception types - catch (Exception ex) -#pragma warning restore CA1031 // Do not catch general exception types + + if (manifest != null) { - _logger.LogError(ex, "Something went wrong!"); - return null; + if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) + { + targetAbi = _minimumVersion; + } + + if (!Version.TryParse(manifest.Version, out version)) + { + manifest.Version = _minimumVersion.ToString(); + } + + return new LocalPlugin(dir, _appVersion >= targetAbi, manifest); } + + // No metafile, so lets see if the folder is versioned. + // TODO: Phase this support out in future versions. + metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; + int versionIndex = dir.LastIndexOf('_'); + if (versionIndex != -1) + { + // Get the version number from the filename if possible. + metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex]; + version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion; + } + else + { + // Un-versioned folder - Add it under the path name and version it suitable for this instance. + version = _appVersion; + } + + // Auto-create a plugin manifest, so we can disable it, if it fails to load. + manifest = new PluginManifest + { + Status = PluginStatus.Restart, + Name = metafile, + AutoUpdate = false, + Id = metafile.GetMD5(), + TargetAbi = _appVersion.ToString(), + Version = version.ToString() + }; + + return new LocalPlugin(dir, true, manifest); } /// <summary> @@ -566,14 +555,9 @@ namespace Emby.Server.Implementations.Plugins } var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly); - LocalPlugin? entry; foreach (var dir in directories) { - entry = LoadManifest(dir); - if (entry != null) - { - versions.Add(entry); - } + versions.Add(LoadManifest(dir)); } string lastName = string.Empty; @@ -582,7 +566,7 @@ namespace Emby.Server.Implementations.Plugins // The first item will be the latest version. for (int x = versions.Count - 1; x >= 0; x--) { - entry = versions[x]; + var entry = versions[x]; if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase)) { entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories)); From f06d52c4756fa2b61744fb11d7cf105b349a1885 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 23:29:21 +0000 Subject: [PATCH 0795/1930] Disable API if dlna is disabled. --- Emby.Dlna/Main/DlnaEntryPoint.cs | 6 +++ .../Controllers/DlnaServerController.cs | 39 +++++++++++++++---- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index fb4454a343..175a1ad2b1 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -126,6 +126,11 @@ namespace Emby.Dlna.Main public static DlnaEntryPoint Current { get; private set; } + /// <summary> + /// Gets a value indicating whether the dlna server is enabled. + /// </summary> + public static bool Enabled { get; private set; } + public IContentDirectory ContentDirectory { get; private set; } public IConnectionManager ConnectionManager { get; private set; } @@ -152,6 +157,7 @@ namespace Emby.Dlna.Main private void ReloadComponents() { var options = _config.GetDlnaConfiguration(); + Enabled = options.EnableServer; StartSsdpHandler(); diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 4fd9c2fbf6..8555cbfa6b 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -45,14 +45,20 @@ namespace Jellyfin.Api.Controllers [HttpGet("{serverId}/description")] [HttpGet("{serverId}/description.xml", Name = "GetDescriptionXml_2")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult GetDescriptionXml([FromRoute, Required] string serverId) { - var url = GetAbsoluteUri(); - var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase)); - var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers, serverId, serverAddress); - return Ok(xml); + if (DlnaEntryPoint.Enabled) + { + var url = GetAbsoluteUri(); + var serverAddress = url.Substring(0, url.IndexOf("/dlna/", StringComparison.OrdinalIgnoreCase)); + var xml = _dlnaManager.GetServerDescriptionXml(Request.Headers, serverId, serverAddress); + return Ok(xml); + } + + return NotFound(); } /// <summary> @@ -65,12 +71,18 @@ namespace Jellyfin.Api.Controllers [HttpGet("{serverId}/ContentDirectory/ContentDirectory", Name = "GetContentDirectory_2")] [HttpGet("{serverId}/ContentDirectory/ContentDirectory.xml", Name = "GetContentDirectory_3")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] public ActionResult GetContentDirectory([FromRoute, Required] string serverId) { - return Ok(_contentDirectory.GetServiceXml()); + if (DlnaEntryPoint.Enabled) + { + return Ok(_contentDirectory.GetServiceXml()); + } + + return NotFound(); } /// <summary> @@ -83,12 +95,18 @@ namespace Jellyfin.Api.Controllers [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar.xml", Name = "GetMediaReceiverRegistrar_3")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] public ActionResult GetMediaReceiverRegistrar([FromRoute, Required] string serverId) { - return Ok(_mediaReceiverRegistrar.GetServiceXml()); + if (DlnaEntryPoint.Enabled) + { + return Ok(_mediaReceiverRegistrar.GetServiceXml()); + } + + return NotFound(); } /// <summary> @@ -101,12 +119,18 @@ namespace Jellyfin.Api.Controllers [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager.xml", Name = "GetConnectionManager_3")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] public ActionResult GetConnectionManager([FromRoute, Required] string serverId) { - return Ok(_connectionManager.GetServiceXml()); + if (DlnaEntryPoint.Enabled) + { + return Ok(_connectionManager.GetServiceXml()); + } + + return NotFound(); } /// <summary> @@ -147,6 +171,7 @@ namespace Jellyfin.Api.Controllers /// <returns>Control response.</returns> [HttpPost("{serverId}/MediaReceiverRegistrar/Control")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId) From bae8f0c4ec4a123db573579d09bf9051e84d3911 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 23:52:19 +0000 Subject: [PATCH 0796/1930] corrected. --- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 25 ++++++-------------- 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index e4e766472c..24a6dbeacc 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -15,6 +15,8 @@ namespace MediaBrowser.Common.Plugins public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration where TConfigurationType : BasePluginConfiguration { + private readonly string _dataFolderPath; + /// <summary> /// The configuration sync lock. /// </summary> @@ -47,14 +49,14 @@ namespace MediaBrowser.Common.Plugins var assemblyName = assembly.GetName(); var assemblyFilePath = assembly.Location; - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - if (!Directory.Exists(dataFolderPath) && Version != null) + _dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + if (!Directory.Exists(_dataFolderPath) && Version != null) { // Try again with the version number appended to the folder name. - dataFolderPath = dataFolderPath + "_" + Version.ToString(); + _dataFolderPath = _dataFolderPath + "_" + Version.ToString(); } - assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); + assemblyPlugin.SetAttributes(assemblyFilePath, _dataFolderPath, assemblyName.Version); var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); if (idAttributes.Length > 0) @@ -137,20 +139,7 @@ namespace MediaBrowser.Common.Plugins /// Gets the full path to the configuration file. /// </summary> /// <value>The configuration file path.</value> - public string ConfigurationFilePath - { - get - { - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(AssemblyFilePath)); - if (!Directory.Exists(dataFolderPath) && Version != null) - { - // Try again with the version number appended to the folder name. - return dataFolderPath + "_" + Version.ToString(); - } - - return dataFolderPath; - } - } + public string ConfigurationFilePath => Path.Combine(_dataFolderPath, ConfigurationFileName); /// <summary> /// Gets the plugin configuration. From 46c7499e2b6e5897caeb562d4c0eba89aed843f2 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 23:55:23 +0000 Subject: [PATCH 0797/1930] reverted change --- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index 24a6dbeacc..ea05a722bc 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -15,8 +15,6 @@ namespace MediaBrowser.Common.Plugins public abstract class BasePlugin<TConfigurationType> : BasePlugin, IHasPluginConfiguration where TConfigurationType : BasePluginConfiguration { - private readonly string _dataFolderPath; - /// <summary> /// The configuration sync lock. /// </summary> @@ -49,14 +47,14 @@ namespace MediaBrowser.Common.Plugins var assemblyName = assembly.GetName(); var assemblyFilePath = assembly.Location; - _dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - if (!Directory.Exists(_dataFolderPath) && Version != null) + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + if (!Directory.Exists(dataFolderPath) && Version != null) { // Try again with the version number appended to the folder name. - _dataFolderPath = _dataFolderPath + "_" + Version.ToString(); + dataFolderPath = dataFolderPath + "_" + Version.ToString(); } - assemblyPlugin.SetAttributes(assemblyFilePath, _dataFolderPath, assemblyName.Version); + assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); if (idAttributes.Length > 0) @@ -139,7 +137,7 @@ namespace MediaBrowser.Common.Plugins /// Gets the full path to the configuration file. /// </summary> /// <value>The configuration file path.</value> - public string ConfigurationFilePath => Path.Combine(_dataFolderPath, ConfigurationFileName); + public string ConfigurationFilePath => Path.Combine(ApplicationPaths.PluginConfigurationsPath, ConfigurationFileName); /// <summary> /// Gets the plugin configuration. From c98144c60d25b2ccb6f6ad3e2e2b1b04f88067ab Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 18 Dec 2020 23:59:21 +0000 Subject: [PATCH 0798/1930] Updated docs. --- Jellyfin.Api/Controllers/DlnaServerController.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 8555cbfa6b..914add9f12 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -41,6 +41,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Description xml returned.</response> + /// <response code="404">Not found.</response> /// <returns>An <see cref="OkResult"/> containing the description xml.</returns> [HttpGet("{serverId}/description")] [HttpGet("{serverId}/description.xml", Name = "GetDescriptionXml_2")] @@ -66,6 +67,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna content directory returned.</response> + /// <response code="404">Not found.</response> /// <returns>An <see cref="OkResult"/> containing the dlna content directory xml.</returns> [HttpGet("{serverId}/ContentDirectory")] [HttpGet("{serverId}/ContentDirectory/ContentDirectory", Name = "GetContentDirectory_2")] @@ -90,6 +92,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> + /// <response code="404">Not found.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/MediaReceiverRegistrar")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")] @@ -114,6 +117,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> + /// <response code="404">Not found.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/ConnectionManager")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")] @@ -168,6 +172,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/MediaReceiverRegistrar/Control")] [ProducesResponseType(StatusCodes.Status200OK)] From 3d0b9f9ea14a4ffae2daffb454162fe05d626b14 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 19 Dec 2020 09:34:04 +0000 Subject: [PATCH 0799/1930] Did the other API, --- .../Controllers/DlnaServerController.cs | 67 ++++++++++++++++--- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 914add9f12..42658bb8c7 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -145,11 +145,17 @@ namespace Jellyfin.Api.Controllers /// <returns>Control response.</returns> [HttpPost("{serverId}/ContentDirectory/Control")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessContentDirectoryControlRequest([FromRoute, Required] string serverId) { - return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false); + if (DlnaEntryPoint.Enabled) + { + return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false); + } + + return NotFound(); } /// <summary> @@ -160,11 +166,17 @@ namespace Jellyfin.Api.Controllers /// <returns>Control response.</returns> [HttpPost("{serverId}/ConnectionManager/Control")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessConnectionManagerControlRequest([FromRoute, Required] string serverId) { - return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false); + if (DlnaEntryPoint.Enabled) + { + return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false); + } + + return NotFound(); } /// <summary> @@ -181,7 +193,12 @@ namespace Jellyfin.Api.Controllers [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId) { - return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false); + if (DlnaEntryPoint.Enabled) + { + return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false); + } + + return NotFound(); } /// <summary> @@ -195,11 +212,17 @@ namespace Jellyfin.Api.Controllers [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessMediaReceiverRegistrarEventRequest(string serverId) { - return ProcessEventRequest(_mediaReceiverRegistrar); + if (DlnaEntryPoint.Enabled) + { + return ProcessEventRequest(_mediaReceiverRegistrar); + } + + return NotFound(); } /// <summary> @@ -207,17 +230,24 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ContentDirectory/Events")] [HttpUnsubscribe("{serverId}/ContentDirectory/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessContentDirectoryEventRequest(string serverId) { - return ProcessEventRequest(_contentDirectory); + if (DlnaEntryPoint.Enabled) + { + return ProcessEventRequest(_contentDirectory); + } + + return NotFound(); } /// <summary> @@ -225,17 +255,24 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ConnectionManager/Events")] [HttpUnsubscribe("{serverId}/ConnectionManager/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessConnectionManagerEventRequest(string serverId) { - return ProcessEventRequest(_connectionManager); + if (DlnaEntryPoint.Enabled) + { + return ProcessEventRequest(_connectionManager); + } + + return NotFound(); } /// <summary> @@ -243,14 +280,21 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <param name="fileName">The icon filename.</param> + /// <response code="404">Not found.</response> /// <returns>Icon stream.</returns> [HttpGet("{serverId}/icons/{fileName}")] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] public ActionResult GetIconId([FromRoute, Required] string serverId, [FromRoute, Required] string fileName) { - return GetIconInternal(fileName); + if (DlnaEntryPoint.Enabled) + { + return GetIconInternal(fileName); + } + + return NotFound(); } /// <summary> @@ -258,11 +302,18 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="fileName">The icon filename.</param> /// <returns>Icon stream.</returns> + /// <response code="404">Not found.</response> [HttpGet("icons/{fileName}")] + [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesImageFile] public ActionResult GetIcon([FromRoute, Required] string fileName) { - return GetIconInternal(fileName); + if (DlnaEntryPoint.Enabled) + { + return GetIconInternal(fileName); + } + + return NotFound(); } private ActionResult GetIconInternal(string fileName) From 94707121186f1b71c21a0977bef7c8ab746932df Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sat, 19 Dec 2020 17:38:46 +0000 Subject: [PATCH 0800/1930] Added xml docs --- Jellyfin.Api/Controllers/DlnaServerController.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index 42658bb8c7..a3c82ed847 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -142,6 +142,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ContentDirectory/Control")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -163,6 +164,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ConnectionManager/Control")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -206,6 +208,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> + /// <response code="404">Not found.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")] [HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")] From 4539164d3892701d6d358c558df5359b282a3568 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 19 Dec 2020 10:55:07 -0700 Subject: [PATCH 0801/1930] Add request parameters to OpenLiveStreamDto --- .../Controllers/MediaInfoController.cs | 28 +++++----- .../Models/MediaInfoDtos/OpenLiveStreamDto.cs | 55 +++++++++++++++++++ 2 files changed, 69 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index 2a1da31c9e..baa2e06361 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -259,24 +259,24 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? subtitleStreamIndex, [FromQuery] int? maxAudioChannels, [FromQuery] Guid? itemId, - [FromBody] OpenLiveStreamDto openLiveStreamDto, - [FromQuery] bool enableDirectPlay = true, - [FromQuery] bool enableDirectStream = true) + [FromBody] OpenLiveStreamDto? openLiveStreamDto, + [FromQuery] bool? enableDirectPlay, + [FromQuery] bool? enableDirectStream) { var request = new LiveStreamRequest { - OpenToken = openToken, - UserId = userId ?? Guid.Empty, - PlaySessionId = playSessionId, - MaxStreamingBitrate = maxStreamingBitrate, - StartTimeTicks = startTimeTicks, - AudioStreamIndex = audioStreamIndex, - SubtitleStreamIndex = subtitleStreamIndex, - MaxAudioChannels = maxAudioChannels, - ItemId = itemId ?? Guid.Empty, + OpenToken = openToken ?? openLiveStreamDto?.OpenToken, + UserId = userId ?? openLiveStreamDto?.UserId ?? Guid.Empty, + PlaySessionId = playSessionId ?? openLiveStreamDto?.PlaySessionId, + MaxStreamingBitrate = maxStreamingBitrate ?? openLiveStreamDto?.MaxStreamingBitrate, + StartTimeTicks = startTimeTicks ?? openLiveStreamDto?.StartTimeTicks, + AudioStreamIndex = audioStreamIndex ?? openLiveStreamDto?.AudioStreamIndex, + SubtitleStreamIndex = subtitleStreamIndex ?? openLiveStreamDto?.SubtitleStreamIndex, + MaxAudioChannels = maxAudioChannels ?? openLiveStreamDto?.MaxAudioChannels, + ItemId = itemId ?? openLiveStreamDto?.ItemId ?? Guid.Empty, DeviceProfile = openLiveStreamDto?.DeviceProfile, - EnableDirectPlay = enableDirectPlay, - EnableDirectStream = enableDirectStream, + EnableDirectPlay = enableDirectPlay ?? openLiveStreamDto?.EnableDirectPlay ?? true, + EnableDirectStream = enableDirectStream ?? openLiveStreamDto?.EnableDirectStream ?? true, DirectPlayProtocols = openLiveStreamDto?.DirectPlayProtocols ?? new[] { MediaProtocol.Http } }; return await _mediaInfoHelper.OpenMediaSource(Request, request).ConfigureAwait(false); diff --git a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs index b0b3de8553..7045423261 100644 --- a/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs +++ b/Jellyfin.Api/Models/MediaInfoDtos/OpenLiveStreamDto.cs @@ -10,6 +10,61 @@ namespace Jellyfin.Api.Models.MediaInfoDtos /// </summary> public class OpenLiveStreamDto { + /// <summary> + /// Gets or sets the open token. + /// </summary> + public string? OpenToken { get; set; } + + /// <summary> + /// Gets or sets the user id. + /// </summary> + public Guid? UserId { get; set; } + + /// <summary> + /// Gets or sets the play session id. + /// </summary> + public string? PlaySessionId { get; set; } + + /// <summary> + /// Gets or sets the max streaming bitrate. + /// </summary> + public int? MaxStreamingBitrate { get; set; } + + /// <summary> + /// Gets or sets the start time in ticks. + /// </summary> + public long? StartTimeTicks { get; set; } + + /// <summary> + /// Gets or sets the audio stream index. + /// </summary> + public int? AudioStreamIndex { get; set; } + + /// <summary> + /// Gets or sets the subtitle stream index. + /// </summary> + public int? SubtitleStreamIndex { get; set; } + + /// <summary> + /// Gets or sets the max audio channels. + /// </summary> + public int? MaxAudioChannels { get; set; } + + /// <summary> + /// Gets or sets the item id. + /// </summary> + public Guid? ItemId { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable direct play. + /// </summary> + public bool? EnableDirectPlay { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enale direct stream. + /// </summary> + public bool? EnableDirectStream { get; set; } + /// <summary> /// Gets or sets the device profile. /// </summary> From 841df64e9f4399304337d9303b5c2a5b015d996a Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sat, 19 Dec 2020 15:56:08 -0500 Subject: [PATCH 0802/1930] Add static Linux builds for arm and musl --- deployment/Dockerfile.linux.amd64-musl | 31 ++++++++++++++++++++++++++ deployment/Dockerfile.linux.arm64 | 31 ++++++++++++++++++++++++++ deployment/Dockerfile.linux.armhf | 31 ++++++++++++++++++++++++++ deployment/build.linux.amd64-musl | 31 ++++++++++++++++++++++++++ deployment/build.linux.arm64 | 31 ++++++++++++++++++++++++++ deployment/build.linux.armhf | 31 ++++++++++++++++++++++++++ 6 files changed, 186 insertions(+) create mode 100644 deployment/Dockerfile.linux.amd64-musl create mode 100644 deployment/Dockerfile.linux.arm64 create mode 100644 deployment/Dockerfile.linux.armhf create mode 100755 deployment/build.linux.amd64-musl create mode 100755 deployment/build.linux.arm64 create mode 100755 deployment/build.linux.armhf diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl new file mode 100644 index 0000000000..08b4ffa528 --- /dev/null +++ b/deployment/Dockerfile.linux.amd64-musl @@ -0,0 +1,31 @@ +FROM debian:10 +# Docker build arguments +ARG SOURCE_DIR=/jellyfin +ARG ARTIFACT_DIR=/dist +ARG SDK_VERSION=5.0 +# Docker run environment +ENV SOURCE_DIR=/jellyfin +ENV ARTIFACT_DIR=/dist +ENV DEB_BUILD_OPTIONS=noddebs +ENV ARCH=amd64 +ENV IS_DOCKER=YES + +# Prepare Debian build environment +RUN apt-get update \ + && apt-get install -y apt-transport-https debhelper gnupg wget devscripts mmv libc6-dev libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0 + +# Install dotnet repository +# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ + && mkdir -p dotnet-sdk \ + && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ + && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet + +# Link to docker-build script +RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.amd64-musl /build.sh + +VOLUME ${SOURCE_DIR}/ + +VOLUME ${ARTIFACT_DIR}/ + +ENTRYPOINT ["/build.sh"] diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 new file mode 100644 index 0000000000..b8499c9172 --- /dev/null +++ b/deployment/Dockerfile.linux.arm64 @@ -0,0 +1,31 @@ +FROM debian:10 +# Docker build arguments +ARG SOURCE_DIR=/jellyfin +ARG ARTIFACT_DIR=/dist +ARG SDK_VERSION=5.0 +# Docker run environment +ENV SOURCE_DIR=/jellyfin +ENV ARTIFACT_DIR=/dist +ENV DEB_BUILD_OPTIONS=noddebs +ENV ARCH=arm64 +ENV IS_DOCKER=YES + +# Prepare Debian build environment +RUN apt-get update \ + && apt-get install -y apt-transport-https debhelper gnupg wget devscripts mmv libc6-dev libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0 + +# Install dotnet repository +# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ + && mkdir -p dotnet-sdk \ + && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ + && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet + +# Link to docker-build script +RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.arm64 /build.sh + +VOLUME ${SOURCE_DIR}/ + +VOLUME ${ARTIFACT_DIR}/ + +ENTRYPOINT ["/build.sh"] diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf new file mode 100644 index 0000000000..80c4d14693 --- /dev/null +++ b/deployment/Dockerfile.linux.armhf @@ -0,0 +1,31 @@ +FROM debian:10 +# Docker build arguments +ARG SOURCE_DIR=/jellyfin +ARG ARTIFACT_DIR=/dist +ARG SDK_VERSION=5.0 +# Docker run environment +ENV SOURCE_DIR=/jellyfin +ENV ARTIFACT_DIR=/dist +ENV DEB_BUILD_OPTIONS=noddebs +ENV ARCH=armhf +ENV IS_DOCKER=YES + +# Prepare Debian build environment +RUN apt-get update \ + && apt-get install -y apt-transport-https debhelper gnupg wget devscripts mmv libc6-dev libcurl4-openssl-dev libfontconfig1-dev libfreetype6-dev libssl-dev libssl1.1 liblttng-ust0 + +# Install dotnet repository +# https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current +RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ + && mkdir -p dotnet-sdk \ + && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ + && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet + +# Link to docker-build script +RUN ln -sf ${SOURCE_DIR}/deployment/build.linux.armhf /build.sh + +VOLUME ${SOURCE_DIR}/ + +VOLUME ${ARTIFACT_DIR}/ + +ENTRYPOINT ["/build.sh"] diff --git a/deployment/build.linux.amd64-musl b/deployment/build.linux.amd64-musl new file mode 100755 index 0000000000..72444c05e7 --- /dev/null +++ b/deployment/build.linux.amd64-musl @@ -0,0 +1,31 @@ +#!/bin/bash + +#= Generic Linux amd64-musl .tar.gz + +set -o errexit +set -o xtrace + +# Move to source directory +pushd ${SOURCE_DIR} + +# Get version +if [[ ${IS_UNSTABLE} == 'yes' ]]; then + version="${BUILD_ID}" +else + version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )" +fi + +# Build archives +dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-musl-x64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true" +tar -czf jellyfin-server_${version}_linux-amd64-musl.tar.gz -C dist jellyfin-server_${version} +rm -rf dist/jellyfin-server_${version} + +# Move the artifacts out +mkdir -p ${ARTIFACT_DIR}/ +mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/ + +if [[ ${IS_DOCKER} == YES ]]; then + chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR} +fi + +popd diff --git a/deployment/build.linux.arm64 b/deployment/build.linux.arm64 new file mode 100755 index 0000000000..e362607a76 --- /dev/null +++ b/deployment/build.linux.arm64 @@ -0,0 +1,31 @@ +#!/bin/bash + +#= Generic Linux arm64 .tar.gz + +set -o errexit +set -o xtrace + +# Move to source directory +pushd ${SOURCE_DIR} + +# Get version +if [[ ${IS_UNSTABLE} == 'yes' ]]; then + version="${BUILD_ID}" +else + version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )" +fi + +# Build archives +dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-arm64 --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true" +tar -czf jellyfin-server_${version}_linux-arm64.tar.gz -C dist jellyfin-server_${version} +rm -rf dist/jellyfin-server_${version} + +# Move the artifacts out +mkdir -p ${ARTIFACT_DIR}/ +mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/ + +if [[ ${IS_DOCKER} == YES ]]; then + chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR} +fi + +popd diff --git a/deployment/build.linux.armhf b/deployment/build.linux.armhf new file mode 100755 index 0000000000..c0d0607fc7 --- /dev/null +++ b/deployment/build.linux.armhf @@ -0,0 +1,31 @@ +#!/bin/bash + +#= Generic Linux armhf .tar.gz + +set -o errexit +set -o xtrace + +# Move to source directory +pushd ${SOURCE_DIR} + +# Get version +if [[ ${IS_UNSTABLE} == 'yes' ]]; then + version="${BUILD_ID}" +else + version="$( grep "version:" ./build.yaml | sed -E 's/version: "([0-9\.]+.*)"/\1/' )" +fi + +# Build archives +dotnet publish Jellyfin.Server --configuration Release --self-contained --runtime linux-arm --output dist/jellyfin-server_${version}/ "-p:DebugSymbols=false;DebugType=none;UseAppHost=true" +tar -czf jellyfin-server_${version}_linux-armhf.tar.gz -C dist jellyfin-server_${version} +rm -rf dist/jellyfin-server_${version} + +# Move the artifacts out +mkdir -p ${ARTIFACT_DIR}/ +mv jellyfin[-_]*.tar.gz ${ARTIFACT_DIR}/ + +if [[ ${IS_DOCKER} == YES ]]; then + chown -Rc $(stat -c %u:%g ${ARTIFACT_DIR}) ${ARTIFACT_DIR} +fi + +popd From 704d627f3a14b879a6e2fae363474a308079c8bb Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" <joshua@boniface.me> Date: Sat, 19 Dec 2020 15:57:08 -0500 Subject: [PATCH 0803/1930] Add Azure pipeline configs for new arches --- .ci/azure-pipelines-package.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 47477ba602..6063851163 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -22,6 +22,12 @@ jobs: BuildConfiguration: ubuntu.armhf Linux.amd64: BuildConfiguration: linux.amd64 + Linux.amd64-musl: + BuildConfiguration: linux.amd64-musl + Linux.arm64: + BuildConfiguration: linux.arm64 + Linux.armhf: + BuildConfiguration: linux.armhf Windows.amd64: BuildConfiguration: windows.amd64 MacOS: From b8ef0823fac3984296562f5cc31e7f740fc28ff2 Mon Sep 17 00:00:00 2001 From: WWWesten <wwwesten@gmail.com> Date: Sat, 19 Dec 2020 19:20:24 +0000 Subject: [PATCH 0804/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- Emby.Server.Implementations/Localization/Core/kk.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index 91c1fb15bc..a092614fd0 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -91,5 +91,6 @@ "UserStoppedPlayingItemWithValues": "{0} - {1} oınatýyn {2} toqtatty", "ValueHasBeenAddedToLibrary": "{0} (tasyǵyshhanaǵa ústelindi)", "ValueSpecialEpisodeName": "Arnaıy - {0}", - "VersionNumber": "Nusqasy {0}" + "VersionNumber": "Nusqasy {0}", + "Default": "Ádepki" } From 1d50c2ad63fd0e312d1b0190d5caaff9444df76c Mon Sep 17 00:00:00 2001 From: WWWesten <wwwesten@gmail.com> Date: Sun, 20 Dec 2020 06:00:44 +0000 Subject: [PATCH 0805/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- .../Localization/Core/kk.json | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index a092614fd0..47c0879be4 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -92,5 +92,21 @@ "ValueHasBeenAddedToLibrary": "{0} (tasyǵyshhanaǵa ústelindi)", "ValueSpecialEpisodeName": "Arnaıy - {0}", "VersionNumber": "Nusqasy {0}", - "Default": "Ádepki" + "Default": "Ádepki", + "TaskDownloadMissingSubtitles": "Joq sýbtıtrlerdi júktep alý", + "TaskRefreshChannels": "Arnalardy jańartý", + "TaskCleanTranscode": "Qaıta kodtaý katalogyn tazalaý", + "TaskUpdatePlugins": "Plagınderdi jańartý", + "TaskRefreshPeople": "Adamdardy jańartý", + "TaskCleanLogs": "Jurnal katalogyn tazalaý", + "TaskRefreshLibrary": "Tasyǵyshhanany skanerleý", + "TaskRefreshChapterImages": "Sahna keskinderin shyǵaryp alý", + "TaskCleanCache": "Kesh katalogyn tazalaý", + "TaskCleanActivityLog": "Áreket jurnalyn tazalaý", + "TasksChannelsCategory": "Internet-arnalar", + "TasksApplicationCategory": "Qoldanba", + "TasksLibraryCategory": "Tasyǵyshhana", + "TasksMaintenanceCategory": "Qyzmet kórsetý", + "Undefined": "Anyqtalmady", + "Forced": "Májbúrli" } From cc5d0af4c18cc2632f1a77a53d3bdef0be3d903b Mon Sep 17 00:00:00 2001 From: WWWesten <wwwesten@gmail.com> Date: Sun, 20 Dec 2020 06:12:52 +0000 Subject: [PATCH 0806/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index ca6172fce0..03d30247a7 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -96,7 +96,7 @@ "TaskRefreshChannels": "Обновление каналов", "TaskCleanTranscode": "Очистка каталога перекодировки", "TaskUpdatePlugins": "Обновление плагинов", - "TaskRefreshPeople": "Обновление метаданных людей", + "TaskRefreshPeople": "Подновить людей", "TaskCleanLogs": "Очистка каталога журналов", "TaskRefreshLibrary": "Сканирование медиатеки", "TaskRefreshChapterImages": "Извлечение изображений сцен", @@ -109,7 +109,7 @@ "TaskRefreshChannelsDescription": "Обновляются данные интернет-каналов.", "TaskCleanTranscodeDescription": "Удаляются файлы перекодировки старше одного дня.", "TaskUpdatePluginsDescription": "Загружаются и устанавливаются обновления для плагинов, у которых включено автоматическое обновление.", - "TaskRefreshPeopleDescription": "Обновляются метаданные актеров и режиссёров в медиатеке.", + "TaskRefreshPeopleDescription": "Обновляются метаданные для актёров и режиссёров в медиатеке.", "TaskCleanLogsDescription": "Удаляются файлы журнала, возраст которых превышает {0} дн(я/ей).", "TaskRefreshLibraryDescription": "Сканируется медиатека на новые файлы и обновляются метаданные.", "TaskRefreshChapterImagesDescription": "Создаются эскизы для видео, которые содержат сцены.", From f4d1e33010d1b3577fbec19ad9c8b70950ce33dd Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Sun, 20 Dec 2020 15:35:10 +0100 Subject: [PATCH 0807/1930] Fix similar items endpoint for movies and TV --- Jellyfin.Api/Controllers/LibraryController.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index c1538a4316..0b90eeea7a 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -732,9 +732,6 @@ namespace Jellyfin.Api.Controllers } else { - // For non series and movie types these columns are typically null - isSeries = null; - isMovie = null; includeItemTypes.Add(item.GetType().Name); } @@ -742,8 +739,6 @@ namespace Jellyfin.Api.Controllers { Limit = limit, IncludeItemTypes = includeItemTypes.ToArray(), - IsMovie = isMovie, - IsSeries = isSeries, SimilarTo = item, DtoOptions = dtoOptions, EnableTotalRecordCount = !isMovie ?? true, From eba403158e1769a3a5e7e49e0e96f0af2a96d14e Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Sun, 20 Dec 2020 17:00:27 +0100 Subject: [PATCH 0808/1930] Re-add IsMovie --- Jellyfin.Api/Controllers/LibraryController.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 0b90eeea7a..deb7052aa3 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -732,6 +732,9 @@ namespace Jellyfin.Api.Controllers } else { + // For non series and movie types these columns are typically null + isSeries = null; + isMovie = null; includeItemTypes.Add(item.GetType().Name); } @@ -739,6 +742,7 @@ namespace Jellyfin.Api.Controllers { Limit = limit, IncludeItemTypes = includeItemTypes.ToArray(), + IsMovie = isMovie, SimilarTo = item, DtoOptions = dtoOptions, EnableTotalRecordCount = !isMovie ?? true, From 53e280b80fe0e0e5ffdcf636246aa4afdc9467a0 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 20 Dec 2020 16:29:28 +0000 Subject: [PATCH 0809/1930] json name override. --- MediaBrowser.Common/Plugins/PluginManifest.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 9c45e5d950..f938214293 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -13,68 +13,80 @@ namespace MediaBrowser.Common.Plugins /// <summary> /// Gets or sets the category of the plugin. /// </summary> + [JsonPropertyName("category")] public string Category { get; set; } = string.Empty; /// <summary> /// Gets or sets the changelog information. /// </summary> + [JsonPropertyName("changelog")] public string Changelog { get; set; } = string.Empty; /// <summary> /// Gets or sets the description of the plugin. /// </summary> + [JsonPropertyName("description")] public string Description { get; set; } = string.Empty; /// <summary> /// Gets or sets the Global Unique Identifier for the plugin. /// </summary> - [JsonPropertyName("Guid")] + [JsonPropertyName("guid")] public Guid Id { get; set; } /// <summary> /// Gets or sets the Name of the plugin. /// </summary> + [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; /// <summary> /// Gets or sets an overview of the plugin. /// </summary> + [JsonPropertyName("overview")] public string Overview { get; set; } = string.Empty; /// <summary> /// Gets or sets the owner of the plugin. /// </summary> + [JsonPropertyName("owner")] public string Owner { get; set; } = string.Empty; /// <summary> /// Gets or sets the compatibility version for the plugin. /// </summary> + [JsonPropertyName("targetAbi")] public string TargetAbi { get; set; } = string.Empty; /// <summary> /// Gets or sets the timestamp of the plugin. /// </summary> + [JsonPropertyName("timestamp")] public DateTime Timestamp { get; set; } /// <summary> /// Gets or sets the Version number of the plugin. /// </summary> + [JsonPropertyName("version")] public string Version { get; set; } = string.Empty; /// <summary> /// Gets or sets a value indicating the operational status of this plugin. /// </summary> + [JsonPropertyName("status")] public PluginStatus Status { get; set; } /// <summary> /// Gets or sets a value indicating whether this plugin should automatically update. /// </summary> + [JsonPropertyName("autoUpdate")] public bool AutoUpdate { get; set; } = true; /// <summary> /// Gets or sets a value indicating whether this plugin has an image. /// Image must be located in the local plugin folder. /// </summary> + [JsonPropertyName("imagePath")] public string? ImagePath { get; set; } } } From 7a667619819bec314fdb6d0b4fd0c3290566297e Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 20 Dec 2020 19:30:48 +0000 Subject: [PATCH 0810/1930] write json files indented. --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 32646d1bf2..2497cddd9f 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -50,6 +50,7 @@ namespace Emby.Server.Implementations.Plugins _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions.WriteIndented = true; _config = config; _appHost = appHost; _minimumVersion = new Version(0, 0, 0, 1); From a682fc4516eea7076114c7f24f47401117d3e423 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 20 Dec 2020 12:59:44 -0700 Subject: [PATCH 0811/1930] Return dashboardTheme when requesting DisplayPreferences --- Jellyfin.Api/Controllers/DisplayPreferencesController.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs index f7bb968f0b..87b4577b62 100644 --- a/Jellyfin.Api/Controllers/DisplayPreferencesController.cs +++ b/Jellyfin.Api/Controllers/DisplayPreferencesController.cs @@ -85,6 +85,7 @@ namespace Jellyfin.Api.Controllers dto.CustomPrefs["skipBackLength"] = displayPreferences.SkipBackwardLength.ToString(CultureInfo.InvariantCulture); dto.CustomPrefs["enableNextVideoInfoOverlay"] = displayPreferences.EnableNextVideoInfoOverlay.ToString(CultureInfo.InvariantCulture); dto.CustomPrefs["tvhome"] = displayPreferences.TvHome; + dto.CustomPrefs["dashboardTheme"] = displayPreferences.DashboardTheme; // Load all custom display preferences var customDisplayPreferences = _displayPreferencesManager.ListCustomItemDisplayPreferences(displayPreferences.UserId, itemId, displayPreferences.Client); From 13de66320126b23f4bb585e5cea3946fa010ce52 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Sun, 20 Dec 2020 22:21:11 +0100 Subject: [PATCH 0812/1930] Fix similar endpoint for TV --- Jellyfin.Api/Controllers/LibraryController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index deb7052aa3..28d359ac3a 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -742,7 +742,6 @@ namespace Jellyfin.Api.Controllers { Limit = limit, IncludeItemTypes = includeItemTypes.ToArray(), - IsMovie = isMovie, SimilarTo = item, DtoOptions = dtoOptions, EnableTotalRecordCount = !isMovie ?? true, From 3df97d54418058d933d7a260fb201a2b1fd5ed40 Mon Sep 17 00:00:00 2001 From: Page Asgardius <hackerman@disroot.org> Date: Mon, 21 Dec 2020 00:36:24 +0000 Subject: [PATCH 0813/1930] Translated using Weblate (Spanish (Latin America)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es_419/ --- Emby.Server.Implementations/Localization/Core/es_419.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es_419.json b/Emby.Server.Implementations/Localization/Core/es_419.json index dcd30694f0..03c6d5f5d3 100644 --- a/Emby.Server.Implementations/Localization/Core/es_419.json +++ b/Emby.Server.Implementations/Localization/Core/es_419.json @@ -112,5 +112,9 @@ "CameraImageUploadedFrom": "Una nueva imagen de cámara ha sido subida desde {0}", "AuthenticationSucceededWithUserName": "{0} autenticado con éxito", "Application": "Aplicación", - "AppDeviceValues": "App: {0}, Dispositivo: {1}" + "AppDeviceValues": "App: {0}, Dispositivo: {1}", + "TaskCleanActivityLogDescription": "Elimina las entradas del registro de actividad anteriores al periodo configurado.", + "TaskCleanActivityLog": "Limpiar Registro de Actividades", + "Undefined": "Sin definir", + "Forced": "Forzado" } From e778fda843c7ea1a746ea93472e661ce5438dfdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Predrag=20Ljubenovi=C4=87?= <predragljubenovic@gmail.com> Date: Sun, 20 Dec 2020 20:15:53 +0000 Subject: [PATCH 0814/1930] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- .../Localization/Core/sr.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index 2984ed972e..d785bcb907 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -66,7 +66,7 @@ "Inherit": "Наследи", "HomeVideos": "Кућни видео", "HeaderRecordingGroups": "Групе снимања", - "HeaderNextUp": "Следеће горе", + "HeaderNextUp": "Следи", "HeaderLiveTV": "ТВ уживо", "HeaderFavoriteSongs": "Омиљене песме", "HeaderFavoriteShows": "Омиљене серије", @@ -79,17 +79,17 @@ "Folders": "Фасцикле", "Favorites": "Омиљено", "FailedLoginAttemptWithUserName": "Неуспела пријава са {0}", - "DeviceOnlineWithName": "{0} се повезао", + "DeviceOnlineWithName": "{0} је повезан", "DeviceOfflineWithName": "{0} је прекинуо везу", "Collections": "Колекције", "ChapterNameValue": "Поглавље {0}", "Channels": "Канали", - "CameraImageUploadedFrom": "Нова фотографија је послата са {0}", + "CameraImageUploadedFrom": "Нова фотографија је учитана са {0}", "Books": "Књиге", "AuthenticationSucceededWithUserName": "{0} успешно проверено", - "Artists": "Извођач", + "Artists": "Извођачи", "Application": "Апликација", - "AppDeviceValues": "Апл: {0}, уређај: {1}", + "AppDeviceValues": "Апликација: {0}, Уређај: {1}", "Albums": "Албуми", "TaskDownloadMissingSubtitlesDescription": "Претражује интернет за недостајуће титлове на основу конфигурације метаподатака.", "TaskDownloadMissingSubtitles": "Преузмите недостајуће титлове", @@ -104,7 +104,7 @@ "TaskCleanLogsDescription": "Брише логове старије од {0} дана.", "TaskCleanLogs": "Очистите директоријум логова", "TaskRefreshLibraryDescription": "Скенира вашу медијску библиотеку за нове датотеке и освежава метаподатке.", - "TaskRefreshLibrary": "Скенирај Библиотеку Медија", + "TaskRefreshLibrary": "Скенирај библиотеку медија", "TaskRefreshChapterImagesDescription": "Ствара сличице за видео записе који имају поглавља.", "TaskRefreshChapterImages": "Издвоји слике из поглавља", "TaskCleanCacheDescription": "Брише Кеш фајлове који више нису потребни систему.", From 3633996a53385d78601df33286b47415475ae3bb Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Mon, 21 Dec 2020 09:01:59 +0000 Subject: [PATCH 0815/1930] New json converter implemented. --- .../Plugins/PluginManager.cs | 2 ++ .../Json/Converters/JsonGuidDashConverter.cs | 26 +++++++++++++++++++ MediaBrowser.Common/Plugins/PluginManifest.cs | 2 ++ 3 files changed, 30 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 2497cddd9f..b46c199950 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -9,6 +9,7 @@ using System.Text.Json; using MediaBrowser.Common; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Plugins; @@ -50,6 +51,7 @@ namespace Emby.Server.Implementations.Plugins _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions.Converters.Add(new JsonGuidDashConverter()); _jsonOptions.WriteIndented = true; _config = config; _appHost = appHost; diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs new file mode 100644 index 0000000000..75bab58751 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a GUID object or value to/from JSON. + /// </summary> + public class JsonGuidDashConverter : JsonConverter<Guid> + { + /// <inheritdoc /> + public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var guidStr = reader.GetString(); + return guidStr == null ? Guid.Empty : new Guid(guidStr); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } + } +} diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index f938214293..956a91f851 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.Text.Json.Serialization; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins @@ -32,6 +33,7 @@ namespace MediaBrowser.Common.Plugins /// Gets or sets the Global Unique Identifier for the plugin. /// </summary> [JsonPropertyName("guid")] + [JsonConverter(typeof(JsonGuidDashConverter))] public Guid Id { get; set; } /// <summary> From fd488cd3ff707bfc584d0e03e22a8eba49d0256c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Dec 2020 12:00:39 +0000 Subject: [PATCH 0816/1930] Bump AutoFixture from 4.14.0 to 4.15.0 Bumps [AutoFixture](https://github.com/AutoFixture/AutoFixture) from 4.14.0 to 4.15.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.14.0...v4.15.0) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index b5e8e521ca..559289f1e9 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -13,7 +13,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="AutoFixture" Version="4.14.0" /> + <PackageReference Include="AutoFixture" Version="4.15.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.1" /> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index bcd12deaf7..b7a006070f 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -14,7 +14,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="AutoFixture" Version="4.14.0" /> + <PackageReference Include="AutoFixture" Version="4.15.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="Moq" Version="4.15.2" /> From 242b5a45ab198ba4ddcfa7cc9adb1c2217b455c7 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 21 Dec 2020 08:12:32 -0700 Subject: [PATCH 0817/1930] Add JsonDateTimeConverter --- .../Json/Converters/JsonDateTimeConverter.cs | 34 +++++++++++++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 1 + 2 files changed, 35 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs b/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs new file mode 100644 index 0000000000..698b161c99 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs @@ -0,0 +1,34 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Legacy DateTime converter. + /// Milliseconds aren't output if zero by default. + /// </summary> + public class JsonDateTimeConverter : JsonConverter<DateTime> + { + /// <inheritdoc /> + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.GetDateTime(); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + if (value.Ticks % 10_000_000 == 0) + { + // Remaining ticks value will be 0, manually format. + writer.WriteStringValue(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffZ", CultureInfo.InvariantCulture)); + } + else + { + writer.WriteStringValue(value); + } + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index b76edd2bc7..128cc9d5d0 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -44,6 +44,7 @@ namespace MediaBrowser.Common.Json options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new JsonNullableStructConverterFactory()); options.Converters.Add(new JsonBoolNumberConverter()); + options.Converters.Add(new JsonDateTimeConverter()); return options; } From d3b6a24f78d7a70fc61fe0d479be4b5d3d57bd3f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 21 Dec 2020 08:41:13 -0700 Subject: [PATCH 0818/1930] Add JsonDateTimeConverter --- MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs b/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs index 698b161c99..73e3a0493d 100644 --- a/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonDateTimeConverter.cs @@ -20,7 +20,7 @@ namespace MediaBrowser.Common.Json.Converters /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { - if (value.Ticks % 10_000_000 == 0) + if (value.Millisecond == 0) { // Remaining ticks value will be 0, manually format. writer.WriteStringValue(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffZ", CultureInfo.InvariantCulture)); From 3a6501abe0d2ea4b7b8f19bfffd95467fce555b8 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 21 Dec 2020 17:28:06 -0700 Subject: [PATCH 0819/1930] Fix another key collision in MigrateDisplayPreferencesDatabase --- .../Routines/MigrateDisplayPreferencesDb.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index dd005b7f47..f4040748d7 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -8,7 +8,6 @@ using System.Text.Json.Serialization; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using Jellyfin.Server.Implementations; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; @@ -81,7 +80,8 @@ namespace Jellyfin.Server.Migrations.Routines { "unstable", ChromecastVersion.Unstable } }; - var customDisplayPrefs = new HashSet<string>(); + var displayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var customDisplayPrefs = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var dbFilePath = Path.Combine(_paths.DataPath, DbFilename); using (var connection = SQLite3.Open(dbFilePath, ConnectionFlags.ReadOnly, null)) { @@ -98,6 +98,15 @@ namespace Jellyfin.Server.Migrations.Routines var itemId = new Guid(result[1].ToBlob()); var dtoUserId = new Guid(result[1].ToBlob()); + var client = result[2].ToString(); + var displayPreferencesKey = $"{dtoUserId}|{itemId}|{client}"; + if (displayPrefs.Contains(displayPreferencesKey)) + { + // Duplicate display preference. + continue; + } + + displayPrefs.Add(displayPreferencesKey); var existingUser = _userManager.GetUserById(dtoUserId); if (existingUser == null) { @@ -110,7 +119,7 @@ namespace Jellyfin.Server.Migrations.Routines : ChromecastVersion.Stable; dto.CustomPrefs.Remove("chromecastVersion"); - var displayPreferences = new DisplayPreferences(dtoUserId, itemId, result[2].ToString()) + var displayPreferences = new DisplayPreferences(dtoUserId, itemId, client) { IndexBy = Enum.TryParse<IndexingKind>(dto.IndexBy, true, out var indexBy) ? indexBy : (IndexingKind?)null, ShowBackdrop = dto.ShowBackdrop, From 621e6d28cda49fac580cf8c9c672b5fdfd3f743b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 22 Dec 2020 14:07:01 +0000 Subject: [PATCH 0820/1930] Fallback to default guid --- .../Plugins/PluginManager.cs | 12 +++++- .../Json/Converters/JsonGuidDashConverter.cs | 26 ------------ MediaBrowser.Common/Plugins/PluginManifest.cs | 40 ++++++++++++++----- 3 files changed, 40 insertions(+), 38 deletions(-) delete mode 100644 MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index b46c199950..33faa5e9d8 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -51,8 +51,18 @@ namespace Emby.Server.Implementations.Plugins _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); _jsonOptions = JsonDefaults.GetOptions(); - _jsonOptions.Converters.Add(new JsonGuidDashConverter()); _jsonOptions.WriteIndented = true; + + // We need to use the default GUID converter, so we need to remove any custom ones. + for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--) + { + if (_jsonOptions.Converters[a] is JsonGuidConverter convertor) + { + _jsonOptions.Converters.Remove(convertor); + break; + } + } + _config = config; _appHost = appHost; _minimumVersion = new Version(0, 0, 0, 1); diff --git a/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs b/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs deleted file mode 100644 index 75bab58751..0000000000 --- a/MediaBrowser.Common/Json/Converters/JsonGuidDashConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Globalization; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace MediaBrowser.Common.Json.Converters -{ - /// <summary> - /// Converts a GUID object or value to/from JSON. - /// </summary> - public class JsonGuidDashConverter : JsonConverter<Guid> - { - /// <inheritdoc /> - public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var guidStr = reader.GetString(); - return guidStr == null ? Guid.Empty : new Guid(guidStr); - } - - /// <inheritdoc /> - public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } - } -} diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 956a91f851..334c8d9082 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -1,7 +1,7 @@ #nullable enable + using System; using System.Text.Json.Serialization; -using MediaBrowser.Common.Json.Converters; using MediaBrowser.Model.Plugins; namespace MediaBrowser.Common.Plugins @@ -11,54 +11,71 @@ namespace MediaBrowser.Common.Plugins /// </summary> public class PluginManifest { + /// <summary> + /// Initializes a new instance of the <see cref="PluginManifest"/> class. + /// </summary> + public PluginManifest() + { + Category = string.Empty; + Changelog = string.Empty; + Description = string.Empty; + Status = PluginStatus.Active; + Id = Guid.Empty; + Name = string.Empty; + Owner = string.Empty; + Overview = string.Empty; + TargetAbi = string.Empty; + Version = string.Empty; + AutoUpdate = true; + } + /// <summary> /// Gets or sets the category of the plugin. /// </summary> [JsonPropertyName("category")] - public string Category { get; set; } = string.Empty; + public string Category { get; set; } /// <summary> /// Gets or sets the changelog information. /// </summary> [JsonPropertyName("changelog")] - public string Changelog { get; set; } = string.Empty; + public string Changelog { get; set; } /// <summary> /// Gets or sets the description of the plugin. /// </summary> [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; + public string Description { get; set; } /// <summary> /// Gets or sets the Global Unique Identifier for the plugin. /// </summary> [JsonPropertyName("guid")] - [JsonConverter(typeof(JsonGuidDashConverter))] public Guid Id { get; set; } /// <summary> /// Gets or sets the Name of the plugin. /// </summary> [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + public string Name { get; set; } /// <summary> /// Gets or sets an overview of the plugin. /// </summary> [JsonPropertyName("overview")] - public string Overview { get; set; } = string.Empty; + public string Overview { get; set; } /// <summary> /// Gets or sets the owner of the plugin. /// </summary> [JsonPropertyName("owner")] - public string Owner { get; set; } = string.Empty; + public string Owner { get; set; } /// <summary> /// Gets or sets the compatibility version for the plugin. /// </summary> [JsonPropertyName("targetAbi")] - public string TargetAbi { get; set; } = string.Empty; + public string TargetAbi { get; set; } /// <summary> /// Gets or sets the timestamp of the plugin. @@ -70,7 +87,7 @@ namespace MediaBrowser.Common.Plugins /// Gets or sets the Version number of the plugin. /// </summary> [JsonPropertyName("version")] - public string Version { get; set; } = string.Empty; + public string Version { get; set; } /// <summary> /// Gets or sets a value indicating the operational status of this plugin. @@ -82,9 +99,10 @@ namespace MediaBrowser.Common.Plugins /// Gets or sets a value indicating whether this plugin should automatically update. /// </summary> [JsonPropertyName("autoUpdate")] - public bool AutoUpdate { get; set; } = true; + public bool AutoUpdate { get; set; } /// <summary> + /// Gets or sets the ImagePath /// Gets or sets a value indicating whether this plugin has an image. /// Image must be located in the local plugin folder. /// </summary> From 1f2ecd0775f291457e780733339bb5009ebb8408 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 22 Dec 2020 15:01:26 +0000 Subject: [PATCH 0821/1930] Fix for DI. --- Emby.Server.Implementations/Plugins/PluginManager.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 33faa5e9d8..fbb092a7c6 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -140,7 +140,7 @@ namespace Emby.Server.Implementations.Plugins { foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>()) { - var plugin = GetPluginByType(pluginServiceRegistrator.Assembly.GetType()); + var plugin = GetPluginByAssembly(pluginServiceRegistrator.Assembly); if (plugin == null) { _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName); @@ -350,14 +350,14 @@ namespace Emby.Server.Implementations.Plugins } /// <summary> - /// Finds the plugin record using the type. + /// Finds the plugin record using the assembly. /// </summary> - /// <param name="type">The <see cref="Type"/> being sought.</param> + /// <param name="assembly">The <see cref="Assembly"/> being sought.</param> /// <returns>The matching record, or null if not found.</returns> - private LocalPlugin? GetPluginByType(Type type) + private LocalPlugin? GetPluginByAssembly(Assembly assembly) { // Find which plugin it is by the path. - return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(type.Assembly.Location), StringComparison.Ordinal)); + return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(assembly.Location), StringComparison.Ordinal)); } /// <summary> @@ -368,7 +368,7 @@ namespace Emby.Server.Implementations.Plugins private IPlugin? CreatePluginInstance(Type type) { // Find the record for this plugin. - var plugin = GetPluginByType(type); + var plugin = GetPluginByAssembly(type.Assembly); if (plugin?.Manifest.Status < PluginStatus.Active) { return null; From bf24929d271406bb6ae50eb4aaa784fdf9511b94 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 22 Dec 2020 15:23:55 +0000 Subject: [PATCH 0822/1930] Changed to 503. --- .../Controllers/DlnaServerController.cs | 75 ++++++++++--------- 1 file changed, 41 insertions(+), 34 deletions(-) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index a3c82ed847..df7504b777 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -41,12 +41,12 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Description xml returned.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>An <see cref="OkResult"/> containing the description xml.</returns> [HttpGet("{serverId}/description")] [HttpGet("{serverId}/description.xml", Name = "GetDescriptionXml_2")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult GetDescriptionXml([FromRoute, Required] string serverId) @@ -59,7 +59,7 @@ namespace Jellyfin.Api.Controllers return Ok(xml); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -67,13 +67,13 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna content directory returned.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>An <see cref="OkResult"/> containing the dlna content directory xml.</returns> [HttpGet("{serverId}/ContentDirectory")] [HttpGet("{serverId}/ContentDirectory/ContentDirectory", Name = "GetContentDirectory_2")] [HttpGet("{serverId}/ContentDirectory/ContentDirectory.xml", Name = "GetContentDirectory_3")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] @@ -84,7 +84,7 @@ namespace Jellyfin.Api.Controllers return Ok(_contentDirectory.GetServiceXml()); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -92,13 +92,13 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/MediaReceiverRegistrar")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar.xml", Name = "GetMediaReceiverRegistrar_3")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] @@ -109,7 +109,7 @@ namespace Jellyfin.Api.Controllers return Ok(_mediaReceiverRegistrar.GetServiceXml()); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -117,13 +117,13 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/ConnectionManager")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager.xml", Name = "GetConnectionManager_3")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] @@ -134,7 +134,7 @@ namespace Jellyfin.Api.Controllers return Ok(_connectionManager.GetServiceXml()); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -142,11 +142,11 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ContentDirectory/Control")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessContentDirectoryControlRequest([FromRoute, Required] string serverId) @@ -156,7 +156,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -164,11 +164,11 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ConnectionManager/Control")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessConnectionManagerControlRequest([FromRoute, Required] string serverId) @@ -178,7 +178,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -186,11 +186,11 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/MediaReceiverRegistrar/Control")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public async Task<ActionResult<ControlResponse>> ProcessMediaReceiverRegistrarControlRequest([FromRoute, Required] string serverId) @@ -200,7 +200,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -208,14 +208,14 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")] [HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessMediaReceiverRegistrarEventRequest(string serverId) @@ -225,7 +225,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_mediaReceiverRegistrar); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -233,14 +233,14 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ContentDirectory/Events")] [HttpUnsubscribe("{serverId}/ContentDirectory/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessContentDirectoryEventRequest(string serverId) @@ -250,7 +250,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_contentDirectory); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -258,14 +258,14 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="404">Not found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ConnectionManager/Events")] [HttpUnsubscribe("{serverId}/ConnectionManager/Events")] [ApiExplorerSettings(IgnoreApi = true)] // Ignore in openapi docs [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [Produces(MediaTypeNames.Text.Xml)] [ProducesFile(MediaTypeNames.Text.Xml)] public ActionResult<EventSubscriptionResponse> ProcessConnectionManagerEventRequest(string serverId) @@ -275,7 +275,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_connectionManager); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -283,12 +283,15 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <param name="fileName">The icon filename.</param> - /// <response code="404">Not found.</response> + /// <response code="200">Request processed.</response> + /// <response code="404">Not Found.</response> + /// <response code="503">Service Unavailable.</response> /// <returns>Icon stream.</returns> [HttpGet("{serverId}/icons/{fileName}")] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [ProducesImageFile] public ActionResult GetIconId([FromRoute, Required] string serverId, [FromRoute, Required] string fileName) { @@ -297,7 +300,7 @@ namespace Jellyfin.Api.Controllers return GetIconInternal(fileName); } - return NotFound(); + return StatusCode(503); } /// <summary> @@ -305,9 +308,13 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="fileName">The icon filename.</param> /// <returns>Icon stream.</returns> - /// <response code="404">Not found.</response> + /// <response code="200">Request processed.</response> + /// <response code="404">Not Found.</response> + /// <response code="503">Service Unavailable.</response> [HttpGet("icons/{fileName}")] + [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status503ServiceUnavailable)] [ProducesImageFile] public ActionResult GetIcon([FromRoute, Required] string fileName) { @@ -316,7 +323,7 @@ namespace Jellyfin.Api.Controllers return GetIconInternal(fileName); } - return NotFound(); + return StatusCode(503); } private ActionResult GetIconInternal(string fileName) From bc9462981eb7a3624d82547ea71024442c085ebd Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 22 Dec 2020 15:33:25 +0000 Subject: [PATCH 0823/1930] changed to constants --- .../Controllers/DlnaServerController.cs | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Jellyfin.Api/Controllers/DlnaServerController.cs b/Jellyfin.Api/Controllers/DlnaServerController.cs index df7504b777..694d16ad97 100644 --- a/Jellyfin.Api/Controllers/DlnaServerController.cs +++ b/Jellyfin.Api/Controllers/DlnaServerController.cs @@ -41,7 +41,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Description xml returned.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>An <see cref="OkResult"/> containing the description xml.</returns> [HttpGet("{serverId}/description")] [HttpGet("{serverId}/description.xml", Name = "GetDescriptionXml_2")] @@ -59,7 +59,7 @@ namespace Jellyfin.Api.Controllers return Ok(xml); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -67,7 +67,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna content directory returned.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>An <see cref="OkResult"/> containing the dlna content directory xml.</returns> [HttpGet("{serverId}/ContentDirectory")] [HttpGet("{serverId}/ContentDirectory/ContentDirectory", Name = "GetContentDirectory_2")] @@ -84,7 +84,7 @@ namespace Jellyfin.Api.Controllers return Ok(_contentDirectory.GetServiceXml()); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -92,7 +92,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/MediaReceiverRegistrar")] [HttpGet("{serverId}/MediaReceiverRegistrar/MediaReceiverRegistrar", Name = "GetMediaReceiverRegistrar_2")] @@ -109,7 +109,7 @@ namespace Jellyfin.Api.Controllers return Ok(_mediaReceiverRegistrar.GetServiceXml()); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -117,7 +117,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Dlna media receiver registrar xml returned.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Dlna media receiver registrar xml.</returns> [HttpGet("{serverId}/ConnectionManager")] [HttpGet("{serverId}/ConnectionManager/ConnectionManager", Name = "GetConnectionManager_2")] @@ -134,7 +134,7 @@ namespace Jellyfin.Api.Controllers return Ok(_connectionManager.GetServiceXml()); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -142,7 +142,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ContentDirectory/Control")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -156,7 +156,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _contentDirectory).ConfigureAwait(false); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -164,7 +164,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/ConnectionManager/Control")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -178,7 +178,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _connectionManager).ConfigureAwait(false); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -186,7 +186,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Control response.</returns> [HttpPost("{serverId}/MediaReceiverRegistrar/Control")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -200,7 +200,7 @@ namespace Jellyfin.Api.Controllers return await ProcessControlRequestInternalAsync(serverId, Request.Body, _mediaReceiverRegistrar).ConfigureAwait(false); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -208,7 +208,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/MediaReceiverRegistrar/Events")] [HttpUnsubscribe("{serverId}/MediaReceiverRegistrar/Events")] @@ -225,7 +225,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_mediaReceiverRegistrar); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -233,7 +233,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ContentDirectory/Events")] [HttpUnsubscribe("{serverId}/ContentDirectory/Events")] @@ -250,7 +250,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_contentDirectory); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -258,7 +258,7 @@ namespace Jellyfin.Api.Controllers /// </summary> /// <param name="serverId">Server UUID.</param> /// <response code="200">Request processed.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Event subscription response.</returns> [HttpSubscribe("{serverId}/ConnectionManager/Events")] [HttpUnsubscribe("{serverId}/ConnectionManager/Events")] @@ -275,7 +275,7 @@ namespace Jellyfin.Api.Controllers return ProcessEventRequest(_connectionManager); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -285,7 +285,7 @@ namespace Jellyfin.Api.Controllers /// <param name="fileName">The icon filename.</param> /// <response code="200">Request processed.</response> /// <response code="404">Not Found.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> /// <returns>Icon stream.</returns> [HttpGet("{serverId}/icons/{fileName}")] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "serverId", Justification = "Required for DLNA")] @@ -300,7 +300,7 @@ namespace Jellyfin.Api.Controllers return GetIconInternal(fileName); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } /// <summary> @@ -310,7 +310,7 @@ namespace Jellyfin.Api.Controllers /// <returns>Icon stream.</returns> /// <response code="200">Request processed.</response> /// <response code="404">Not Found.</response> - /// <response code="503">Service Unavailable.</response> + /// <response code="503">DLNA is disabled.</response> [HttpGet("icons/{fileName}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] @@ -323,7 +323,7 @@ namespace Jellyfin.Api.Controllers return GetIconInternal(fileName); } - return StatusCode(503); + return StatusCode(StatusCodes.Status503ServiceUnavailable); } private ActionResult GetIconInternal(string fileName) From 1dac2226c4d12c5ccb9bed83c8b6cceab8dbff09 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 22 Dec 2020 08:57:51 -0700 Subject: [PATCH 0824/1930] Remove unused deps --- Emby.Dlna/Emby.Dlna.csproj | 4 +--- .../Emby.Server.Implementations.csproj | 8 -------- Jellyfin.Api/Jellyfin.Api.csproj | 2 -- MediaBrowser.Common/MediaBrowser.Common.csproj | 2 +- .../MediaBrowser.MediaEncoding.csproj | 2 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 1 - MediaBrowser.Providers/MediaBrowser.Providers.csproj | 1 - 7 files changed, 3 insertions(+), 17 deletions(-) diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index bd30cc1e11..8b057a0950 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -78,9 +78,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> - <PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.6" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> </ItemGroup> </Project> diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 9e9452f32c..7c9a5fbe19 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -23,14 +23,6 @@ <ItemGroup> <PackageReference Include="Jellyfin.XmlTv" Version="10.6.2" /> - <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" /> - <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> - <PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" /> - <PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index b4f2817f71..f01f50cea7 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,9 +15,7 @@ </PropertyGroup> <ItemGroup> - <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.1" /> - <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> <PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="5.6.3" /> diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index be5e7f5b45..320e60dc66 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -14,6 +14,7 @@ </PropertyGroup> <ItemGroup> + <FrameworkReference Include="Microsoft.AspNetCore.App"/> <ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" /> </ItemGroup> @@ -21,7 +22,6 @@ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> - <PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.8" /> </ItemGroup> <ItemGroup> diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 7bb2a7d03f..f8af499e4c 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -24,7 +24,7 @@ <ItemGroup> <PackageReference Include="BDInfo" Version="0.7.6.1" /> - <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.6" /> + <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> <PackageReference Include="System.Text.Encoding.CodePages" Version="5.0.0" /> <PackageReference Include="UTF.Unknown" Version="2.3.0" /> </ItemGroup> diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index b86187f9be..334fe82097 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -33,7 +33,6 @@ <ItemGroup> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" /> - <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" /> <PackageReference Include="System.Globalization" Version="4.3.0" /> <PackageReference Include="System.Text.Json" Version="5.0.0" /> diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index accdea36e4..fc8eb8c4e4 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -22,7 +22,6 @@ <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" /> <PackageReference Include="PlaylistsNET" Version="1.1.3" /> <PackageReference Include="TMDbLib" Version="1.7.3-alpha" /> - <PackageReference Include="TvDbSharper" Version="3.2.2" /> </ItemGroup> <PropertyGroup> From e113a5059794b84090ff3dfb37f52b28ce7651f0 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Tue, 22 Dec 2020 16:14:06 +0000 Subject: [PATCH 0825/1930] Possible null reference fix. --- Jellyfin.Api/Controllers/SystemController.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 7784e8a119..d79bea9855 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; +using System.Net; using System.Net.Mime; using System.Threading; using System.Threading.Tasks; @@ -66,7 +67,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<SystemInfo> GetSystemInfo() { - return _appHost.GetSystemInfo(Request.HttpContext.Connection.RemoteIpAddress); + return _appHost.GetSystemInfo(Request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback); } /// <summary> @@ -78,7 +79,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult<PublicSystemInfo> GetPublicSystemInfo() { - return _appHost.GetPublicSystemInfo(Request.HttpContext.Connection.RemoteIpAddress); + return _appHost.GetPublicSystemInfo(Request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback); } /// <summary> From c0c0eaec0586a1dda3d69c0131f00ba1d5966025 Mon Sep 17 00:00:00 2001 From: Ryan Petris <ryan@petris.net> Date: Tue, 22 Dec 2020 20:37:07 -0700 Subject: [PATCH 0826/1930] new List(int) does not pre-allocate indicies like Arrays, it merely sets the initial capacity. --- .../LiveTv/Listings/SchedulesDirect.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 90e6cc9668..b19ccadd8f 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -784,18 +784,17 @@ namespace Emby.Server.Implementations.LiveTv.Listings var allStations = root.stations ?? new List<ScheduleDirect.Station>(); var map = root.map; - int len = map.Count; - var array = new List<ChannelInfo>(len); - for (int i = 0; i < len; i++) + var list = new List<ChannelInfo>(map.Count); + foreach (var channel in map) { - var channelNumber = GetChannelNumber(map[i]); + var channelNumber = GetChannelNumber(channel); - var station = allStations.Find(item => string.Equals(item.stationID, map[i].stationID, StringComparison.OrdinalIgnoreCase)); + var station = allStations.Find(item => string.Equals(item.stationID, channel.stationID, StringComparison.OrdinalIgnoreCase)); if (station == null) { station = new ScheduleDirect.Station { - stationID = map[i].stationID + stationID = channel.stationID }; } @@ -812,10 +811,10 @@ namespace Emby.Server.Implementations.LiveTv.Listings channelInfo.ImageUrl = station.logo.URL; } - array[i] = channelInfo; + list.Add(channelInfo); } - return array; + return list; } private static string NormalizeName(string value) From 66d98cb8e406d1dddebd339b0aab20b93df4bf7b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:24:30 +0000 Subject: [PATCH 0827/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index b91ba6b6ca..f73cd1ea4f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -462,7 +462,7 @@ namespace Emby.Server.Implementations { // Convert to list so this isn't executed for each iteration var parts = GetExportTypes<T>() - .Select(i => defaultFunc(i)) + .Select(defaultFunc) .Where(i => i != null) .Cast<T>() .ToList(); From 4ba4eefeeb145d03c1599c12a1ef61b4f87f67fb Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:26:02 +0000 Subject: [PATCH 0828/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index fbb092a7c6..2609f6fca6 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -232,9 +232,9 @@ namespace Emby.Server.Implementations.Plugins var plugins = _plugins.Where(p => p.Id.Equals(id)); plugin = plugins.FirstOrDefault(p => p.Instance != null); - if (plugin == null) + if (plugin == null && plugins.Length > 0) { - plugin = plugins.OrderByDescending(p => p.Version).FirstOrDefault(); + plugin = plugins.OrderByDescending(p => p.Version)[0]; } } else From 63c290f87893d234e8a1db3ce2260feaab5e2304 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:26:20 +0000 Subject: [PATCH 0829/1930] Update Emby.Server.Implementations/Updates/InstallationManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 4c2424c15b..76d3481b40 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -395,7 +395,7 @@ namespace Emby.Server.Implementations.Updates if (plugin.Instance?.CanUninstall == false) { - _logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name); + _logger.LogWarning("Attempt to delete non removable plugin {PluginName}, ignoring request", plugin.Name); return; } From 8e04e6c837e628fe80fab486adea33ae3b33aae5 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:27:27 +0000 Subject: [PATCH 0830/1930] Update Emby.Server.Implementations/Updates/InstallationManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 76d3481b40..abcb4313f3 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -589,7 +589,7 @@ namespace Emby.Server.Implementations.Updates await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); // Do plugin-specific processing - _logger.LogInformation(plugin == null ? "New plugin installed: {0} {1}" : "Plugin updated: {0} {1}", package.Name, package.Version); + _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version); return plugin != null; } From 9a97933499d4171e6ff7d2d860845c1cc54ef7d8 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:29:21 +0000 Subject: [PATCH 0831/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Claus Vium <cvium@users.noreply.github.com> --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 2609f6fca6..dac3100af8 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -229,7 +229,7 @@ namespace Emby.Server.Implementations.Plugins if (version == null) { // If no version is given, return the current instance. - var plugins = _plugins.Where(p => p.Id.Equals(id)); + var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList(); plugin = plugins.FirstOrDefault(p => p.Instance != null); if (plugin == null && plugins.Length > 0) From e8df9551ef392785c0fb7269b9e187cd199390d8 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:31:11 +0000 Subject: [PATCH 0832/1930] Update PluginManager.cs Changed a to i --- Emby.Server.Implementations/Plugins/PluginManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index dac3100af8..629975abb1 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -81,9 +81,9 @@ namespace Emby.Server.Implementations.Plugins public IEnumerable<Assembly> LoadAssemblies() { // Attempt to remove any deleted plugins and change any successors to be active. - for (int a = _plugins.Count - 1; a >= 0; a--) + for (int i = _plugins.Count - 1; i >= 0; i--) { - var plugin = _plugins[a]; + var plugin = _plugins[i]; if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin)) { UpdateSuccessors(plugin); From d98f42a6aa80b4d9f5f9ffecc17f87bd2510442a Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 10:36:34 +0000 Subject: [PATCH 0833/1930] Update PackageInfo.cs uncommented attribute. --- MediaBrowser.Model/Updates/PackageInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 0902e04409..2b6e940d15 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Model.Updates /// Gets or sets a long description of the plugin containing features or helpful explanations. /// </summary> /// <value>The description.</value> - /// [JsonPropertyName("description")] + [JsonPropertyName("description")] public string Description { get; set; } /// <summary> From e09d3ba9efa7505a14d57d344707fe7ce71119b2 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:06:29 +0100 Subject: [PATCH 0834/1930] Remove custom Json serializer from Providers --- .../Plugins/AudioDb/AlbumImageProvider.cs | 10 +++++---- .../Plugins/AudioDb/AlbumProvider.cs | 9 ++++---- .../Plugins/AudioDb/ArtistImageProvider.cs | 10 +++++---- .../Plugins/AudioDb/ArtistProvider.cs | 9 ++++---- .../Plugins/Omdb/OmdbEpisodeProvider.cs | 8 ++----- .../Plugins/Omdb/OmdbImageProvider.cs | 9 +++----- .../Plugins/Omdb/OmdbItemProvider.cs | 14 ++++++------- .../Plugins/Omdb/OmdbProvider.cs | 21 ++++++++++--------- 8 files changed, 44 insertions(+), 46 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index 293087da7a..605b93788b 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -1,9 +1,12 @@ #pragma warning disable CS1591 using System.Collections.Generic; +using System.IO; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -19,13 +22,11 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _json; - public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory, IJsonSerializer json) + public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { _config = config; _httpClientFactory = httpClientFactory; - _json = json; } /// <inheritdoc /> @@ -56,7 +57,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbAlbumProvider.GetAlbumInfoPath(_config.ApplicationPaths, id); - var obj = _json.DeserializeFromFile<AudioDbAlbumProvider.RootObject>(path); + var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + var obj = JsonSerializer.Deserialize<AudioDbAlbumProvider.RootObject>(jsonString, JsonDefaults.GetOptions()); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 97bba10baa..32ef135475 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -6,10 +6,12 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.Audio; @@ -27,16 +29,14 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _json; public static AudioDbAlbumProvider Current; - public AudioDbAlbumProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory, IJsonSerializer json) + public AudioDbAlbumProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory) { _config = config; _fileSystem = fileSystem; _httpClientFactory = httpClientFactory; - _json = json; Current = this; } @@ -64,7 +64,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetAlbumInfoPath(_config.ApplicationPaths, id); - var obj = _json.DeserializeFromFile<RootObject>(path); + var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + var obj = JsonSerializer.Deserialize<RootObject>(jsonString, JsonDefaults.GetOptions()); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index d250acfa84..f0b8e00f3f 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -1,9 +1,12 @@ #pragma warning disable CS1591 using System.Collections.Generic; +using System.IO; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -19,12 +22,10 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _json; - public AudioDbArtistImageProvider(IServerConfigurationManager config, IJsonSerializer json, IHttpClientFactory httpClientFactory) + public AudioDbArtistImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { _config = config; - _json = json; _httpClientFactory = httpClientFactory; } @@ -58,7 +59,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbArtistProvider.GetArtistInfoPath(_config.ApplicationPaths, id); - var obj = _json.DeserializeFromFile<AudioDbArtistProvider.RootObject>(path); + var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + var obj = JsonSerializer.Deserialize<AudioDbArtistProvider.RootObject>(jsonString, JsonDefaults.GetOptions()); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index a2a03e1f9a..2476c86715 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -5,10 +5,12 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.Audio; @@ -29,14 +31,12 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _json; - public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory, IJsonSerializer json) + public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory) { _config = config; _fileSystem = fileSystem; _httpClientFactory = httpClientFactory; - _json = json; Current = this; } @@ -65,7 +65,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetArtistInfoPath(_config.ApplicationPaths, id); - var obj = _json.DeserializeFromFile<RootObject>(path); + var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + var obj = JsonSerializer.Deserialize<RootObject>(jsonString, JsonDefaults.GetOptions()); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs index bfc840ea59..24ef80a35d 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbEpisodeProvider.cs @@ -12,13 +12,11 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.Omdb { public class OmdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder { - private readonly IJsonSerializer _jsonSerializer; private readonly IHttpClientFactory _httpClientFactory; private readonly OmdbItemProvider _itemProvider; private readonly IFileSystem _fileSystem; @@ -26,19 +24,17 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IApplicationHost _appHost; public OmdbEpisodeProvider( - IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClientFactory httpClientFactory, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { - _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _fileSystem = fileSystem; _configurationManager = configurationManager; _appHost = appHost; - _itemProvider = new OmdbItemProvider(jsonSerializer, _appHost, httpClientFactory, libraryManager, fileSystem, configurationManager); + _itemProvider = new OmdbItemProvider(_appHost, httpClientFactory, libraryManager, fileSystem, configurationManager); } // After TheTvDb @@ -69,7 +65,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb { if (info.IndexNumber.HasValue && info.ParentIndexNumber.HasValue) { - result.HasMetadata = await new OmdbProvider(_jsonSerializer, _httpClientFactory, _fileSystem, _appHost, _configurationManager) + result.HasMetadata = await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager) .FetchEpisodeData(result, info.IndexNumber.Value, info.ParentIndexNumber.Value, info.GetProviderId(MetadataProvider.Imdb), seriesImdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); } } diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs index 8f4240dc11..df67aff31c 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbImageProvider.cs @@ -1,8 +1,8 @@ #pragma warning disable CS1591 using System.Collections.Generic; -using System.Net.Http; using System.Globalization; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; @@ -15,21 +15,18 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.Omdb { public class OmdbImageProvider : IRemoteImageProvider, IHasOrder { private readonly IHttpClientFactory _httpClientFactory; - private readonly IJsonSerializer _jsonSerializer; private readonly IFileSystem _fileSystem; private readonly IServerConfigurationManager _configurationManager; private readonly IApplicationHost _appHost; - public OmdbImageProvider(IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager) + public OmdbImageProvider(IApplicationHost appHost, IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { - _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _fileSystem = fileSystem; _configurationManager = configurationManager; @@ -56,7 +53,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var list = new List<RemoteImageInfo>(); - var provider = new OmdbProvider(_jsonSerializer, _httpClientFactory, _fileSystem, _appHost, _configurationManager); + var provider = new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager); if (!string.IsNullOrWhiteSpace(imdbId)) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 43d8af75f0..7e9ef974e2 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -6,9 +6,11 @@ using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -19,14 +21,12 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.Omdb { public class OmdbItemProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IRemoteMetadataProvider<Movie, MovieInfo>, IRemoteMetadataProvider<Trailer, TrailerInfo>, IHasOrder { - private readonly IJsonSerializer _jsonSerializer; private readonly IHttpClientFactory _httpClientFactory; private readonly ILibraryManager _libraryManager; private readonly IFileSystem _fileSystem; @@ -34,14 +34,12 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IApplicationHost _appHost; public OmdbItemProvider( - IJsonSerializer jsonSerializer, IApplicationHost appHost, IHttpClientFactory httpClientFactory, ILibraryManager libraryManager, IFileSystem fileSystem, IServerConfigurationManager configurationManager) { - _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _libraryManager = libraryManager; _fileSystem = fileSystem; @@ -138,7 +136,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb if (isSearch) { - var searchResultList = await _jsonSerializer.DeserializeFromStreamAsync<SearchResultList>(stream).ConfigureAwait(false); + var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (searchResultList != null && searchResultList.Search != null) { resultList.AddRange(searchResultList.Search); @@ -146,7 +144,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } else { - var result = await _jsonSerializer.DeserializeFromStreamAsync<SearchResult>(stream).ConfigureAwait(false); + var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase)) { resultList.Add(result); @@ -221,7 +219,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb result.Item.SetProviderId(MetadataProvider.Imdb, imdbId); result.HasMetadata = true; - await new OmdbProvider(_jsonSerializer, _httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); + await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); } return result; @@ -253,7 +251,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb result.Item.SetProviderId(MetadataProvider.Imdb, imdbId); result.HasMetadata = true; - await new OmdbProvider(_jsonSerializer, _httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); + await new OmdbProvider(_httpClientFactory, _fileSystem, _appHost, _configurationManager).Fetch(result, imdbId, info.MetadataLanguage, info.MetadataCountryCode, cancellationToken).ConfigureAwait(false); } return result; diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index e6c6050720..e73085460d 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -7,31 +7,30 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.Omdb { public class OmdbProvider { - private readonly IJsonSerializer _jsonSerializer; private readonly IFileSystem _fileSystem; private readonly IServerConfigurationManager _configurationManager; private readonly IHttpClientFactory _httpClientFactory; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IApplicationHost _appHost; - public OmdbProvider(IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager) + public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager) { - _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _fileSystem = fileSystem; _configurationManager = configurationManager; @@ -220,7 +219,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - var result = _jsonSerializer.DeserializeFromString<RootObject>(resultString); + var result = JsonSerializer.Deserialize<RootObject>(resultString, JsonDefaults.GetOptions()); return result; } @@ -239,7 +238,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - var result = _jsonSerializer.DeserializeFromString<SeasonRootObject>(resultString); + var result = JsonSerializer.Deserialize<SeasonRootObject>(resultString, JsonDefaults.GetOptions()); return result; } @@ -299,9 +298,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<RootObject>(stream).ConfigureAwait(false); + var rootObject = await JsonSerializer.DeserializeAsync<RootObject>(stream, cancellationToken: cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(rootObject, path); + await using FileStream jsonFileStream = File.Create(path); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); return path; } @@ -337,9 +337,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var rootObject = await _jsonSerializer.DeserializeFromStreamAsync<SeasonRootObject>(stream).ConfigureAwait(false); + var rootObject = await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, cancellationToken: cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(rootObject, path); + await using FileStream jsonFileStream = File.Create(path); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); return path; } From bc0976ceac32b5f7e0ef234ec01a0b17477b9086 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:12:06 +0100 Subject: [PATCH 0835/1930] Remove custom Json serializer from Dlna --- Emby.Dlna/DlnaManager.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index fedd20b68a..df69dd5162 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -7,12 +7,14 @@ using System.IO; using System.Linq; using System.Reflection; using System.Text; +using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using Emby.Dlna.Profiles; using Emby.Dlna.Server; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Controller; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Drawing; @@ -32,7 +34,6 @@ namespace Emby.Dlna private readonly IXmlSerializer _xmlSerializer; private readonly IFileSystem _fileSystem; private readonly ILogger<DlnaManager> _logger; - private readonly IJsonSerializer _jsonSerializer; private readonly IServerApplicationHost _appHost; private static readonly Assembly _assembly = typeof(DlnaManager).Assembly; @@ -43,14 +44,12 @@ namespace Emby.Dlna IFileSystem fileSystem, IApplicationPaths appPaths, ILoggerFactory loggerFactory, - IJsonSerializer jsonSerializer, IServerApplicationHost appHost) { _xmlSerializer = xmlSerializer; _fileSystem = fileSystem; _appPaths = appPaths; _logger = loggerFactory.CreateLogger<DlnaManager>(); - _jsonSerializer = jsonSerializer; _appHost = appHost; } @@ -495,9 +494,9 @@ namespace Emby.Dlna return profile; } - var json = _jsonSerializer.SerializeToString(profile); + var json = JsonSerializer.Serialize(profile, JsonDefaults.GetOptions()); - return _jsonSerializer.DeserializeFromString<DeviceProfile>(json); + return JsonSerializer.Deserialize<DeviceProfile>(json, options: JsonDefaults.GetOptions()); } public string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress) From 196388d607a856050221d1b55192360dd3ea8be5 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:12:40 +0100 Subject: [PATCH 0836/1930] Remove custom Json serializer from Emby.Server.Implementations --- .../ApplicationHost.cs | 14 +++----- .../Channels/ChannelManager.cs | 32 +++++++++-------- .../Library/LiveStreamHelper.cs | 13 +++---- .../Library/MediaSourceManager.cs | 18 +++++----- .../LiveTv/EmbyTV/EmbyTV.cs | 12 +++---- .../LiveTv/EmbyTV/EncodedRecorder.cs | 8 ++--- .../LiveTv/EmbyTV/ItemDataProvider.cs | 12 +++---- .../LiveTv/EmbyTV/SeriesTimerManager.cs | 4 +-- .../LiveTv/EmbyTV/TimerManager.cs | 5 ++- .../LiveTv/Listings/SchedulesDirect.cs | 24 ++++++------- .../Localization/LocalizationManager.cs | 14 ++++---- .../ScheduledTasks/ScheduledTaskWorker.cs | 35 ++++++++++--------- .../ScheduledTasks/TaskManager.cs | 7 ++-- 13 files changed, 95 insertions(+), 103 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 50ef71a46d..fcc156e9c5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -7,11 +7,9 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net; -using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; -using System.Text; using System.Threading; using System.Threading.Tasks; using Emby.Dlna; @@ -50,6 +48,7 @@ using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -101,6 +100,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Prometheus.DotNetRuntime; +using JsonSerializer = System.Text.Json.JsonSerializer; using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager; @@ -118,7 +118,6 @@ namespace Emby.Server.Implementations private readonly IFileSystem _fileSystemManager; private readonly IXmlSerializer _xmlSerializer; - private readonly IJsonSerializer _jsonSerializer; private readonly IStartupOptions _startupOptions; private IMediaEncoder _mediaEncoder; @@ -257,7 +256,6 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); ServiceCollection = serviceCollection; @@ -528,8 +526,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths); - ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>(); - ServiceCollection.AddSingleton(_fileSystemManager); ServiceCollection.AddSingleton<TmdbClientManager>(); @@ -754,7 +750,6 @@ namespace Emby.Server.Implementations UserView.CollectionManager = Resolve<ICollectionManager>(); BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>(); CollectionFolder.XmlSerializer = _xmlSerializer; - CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>(); CollectionFolder.ApplicationHost = this; } @@ -967,7 +962,7 @@ namespace Emby.Server.Implementations { return true; } - + throw new FileNotFoundException( string.Format( CultureInfo.InvariantCulture, @@ -1051,7 +1046,8 @@ namespace Emby.Server.Implementations var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { - var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile); + var jsonString = File.ReadAllText(metafile); + var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, JsonDefaults.GetOptions()); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 57684a4298..0966c252ba 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Progress; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; @@ -21,10 +22,10 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Episode = MediaBrowser.Controller.Entities.TV.Episode; +using JsonSerializer = System.Text.Json.JsonSerializer; using Movie = MediaBrowser.Controller.Entities.Movies.Movie; using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum; using Season = MediaBrowser.Controller.Entities.TV.Season; @@ -44,7 +45,6 @@ namespace Emby.Server.Implementations.Channels private readonly ILogger<ChannelManager> _logger; private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; - private readonly IJsonSerializer _jsonSerializer; private readonly IProviderManager _providerManager; private readonly IMemoryCache _memoryCache; private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1); @@ -70,7 +70,6 @@ namespace Emby.Server.Implementations.Channels IServerConfigurationManager config, IFileSystem fileSystem, IUserDataManager userDataManager, - IJsonSerializer jsonSerializer, IProviderManager providerManager, IMemoryCache memoryCache) { @@ -81,7 +80,6 @@ namespace Emby.Server.Implementations.Channels _config = config; _fileSystem = fileSystem; _userDataManager = userDataManager; - _jsonSerializer = jsonSerializer; _providerManager = providerManager; _memoryCache = memoryCache; } @@ -343,7 +341,8 @@ namespace Emby.Server.Implementations.Channels try { - return _jsonSerializer.DeserializeFromFile<List<MediaSourceInfo>>(path) ?? new List<MediaSourceInfo>(); + var jsonString = File.ReadAllText(path); + return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, JsonDefaults.GetOptions()) ?? new List<MediaSourceInfo>(); } catch { @@ -351,7 +350,7 @@ namespace Emby.Server.Implementations.Channels } } - private void SaveMediaSources(BaseItem item, List<MediaSourceInfo> mediaSources) + private async Task SaveMediaSources(BaseItem item, List<MediaSourceInfo> mediaSources) { var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json"); @@ -369,8 +368,8 @@ namespace Emby.Server.Implementations.Channels } Directory.CreateDirectory(Path.GetDirectoryName(path)); - - _jsonSerializer.SerializeToFile(mediaSources, path); + await using FileStream createStream = File.Create(path); + await JsonSerializer.SerializeAsync(createStream, mediaSources, JsonDefaults.GetOptions()).ConfigureAwait(false); } /// <inheritdoc /> @@ -812,7 +811,8 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - var cachedResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath); + var jsonString = await File.ReadAllTextAsync(cachePath, cancellationToken); + var cachedResult = JsonSerializer.Deserialize<ChannelItemResult>(jsonString); if (cachedResult != null) { return null; @@ -834,7 +834,8 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - var cachedResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath); + var jsonString = await File.ReadAllTextAsync(cachePath, cancellationToken); + var cachedResult = JsonSerializer.Deserialize<ChannelItemResult>(jsonString); if (cachedResult != null) { return null; @@ -865,7 +866,7 @@ namespace Emby.Server.Implementations.Channels throw new InvalidOperationException("Channel returned a null result from GetChannelItems"); } - CacheResponse(result, cachePath); + await CacheResponse(result, cachePath); return result; } @@ -875,13 +876,14 @@ namespace Emby.Server.Implementations.Channels } } - private void CacheResponse(object result, string path) + private async Task CacheResponse(object result, string path) { try { Directory.CreateDirectory(Path.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(result, path); + await using FileStream createStream = File.Create(path); + await JsonSerializer.SerializeAsync(createStream, result, JsonDefaults.GetOptions()).ConfigureAwait(false); } catch (Exception ex) { @@ -1176,11 +1178,11 @@ namespace Emby.Server.Implementations.Channels { if (enableMediaProbe && !info.IsLiveStream && item.HasPathProtocol) { - SaveMediaSources(item, new List<MediaSourceInfo>()); + await SaveMediaSources(item, new List<MediaSourceInfo>()); } else { - SaveMediaSources(item, info.MediaSources); + await SaveMediaSources(item, info.MediaSources); } } diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index 041619d1e5..ad7988fb15 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -5,16 +5,17 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library @@ -23,14 +24,12 @@ namespace Emby.Server.Implementations.Library { private readonly IMediaEncoder _mediaEncoder; private readonly ILogger _logger; - private readonly IJsonSerializer _json; private readonly IApplicationPaths _appPaths; - public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IJsonSerializer json, IApplicationPaths appPaths) + public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IApplicationPaths appPaths) { _mediaEncoder = mediaEncoder; _logger = logger; - _json = json; _appPaths = appPaths; } @@ -47,7 +46,8 @@ namespace Emby.Server.Implementations.Library { try { - mediaInfo = _json.DeserializeFromFile<MediaInfo>(cacheFilePath); + var jsonString = await File.ReadAllTextAsync(cacheFilePath, cancellationToken).ConfigureAwait(false); + JsonSerializer.Deserialize<MediaInfo>(jsonString, JsonDefaults.GetOptions()); // _logger.LogDebug("Found cached media info"); } @@ -83,7 +83,8 @@ namespace Emby.Server.Implementations.Library if (cacheFilePath != null) { Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); - _json.SerializeToFile(mediaInfo, cacheFilePath); + await using FileStream createStream = File.Create(cacheFilePath); + await JsonSerializer.SerializeAsync(createStream, mediaInfo, cancellationToken: cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Saved media info to {0}", cacheFilePath); } diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 928f5f88e4..264390dd33 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -6,12 +6,14 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; @@ -23,7 +25,6 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Library @@ -36,7 +37,6 @@ namespace Emby.Server.Implementations.Library private readonly IItemRepository _itemRepo; private readonly IUserManager _userManager; private readonly ILibraryManager _libraryManager; - private readonly IJsonSerializer _jsonSerializer; private readonly IFileSystem _fileSystem; private readonly ILogger<MediaSourceManager> _logger; private readonly IUserDataManager _userDataManager; @@ -56,7 +56,6 @@ namespace Emby.Server.Implementations.Library IUserManager userManager, ILibraryManager libraryManager, ILogger<MediaSourceManager> logger, - IJsonSerializer jsonSerializer, IFileSystem fileSystem, IUserDataManager userDataManager, IMediaEncoder mediaEncoder) @@ -65,7 +64,6 @@ namespace Emby.Server.Implementations.Library _userManager = userManager; _libraryManager = libraryManager; _logger = logger; - _jsonSerializer = jsonSerializer; _fileSystem = fileSystem; _userDataManager = userDataManager; _mediaEncoder = mediaEncoder; @@ -504,7 +502,7 @@ namespace Emby.Server.Implementations.Library // hack - these two values were taken from LiveTVMediaSourceProvider string cacheKey = request.OpenToken; - await new LiveStreamHelper(_mediaEncoder, _logger, _jsonSerializer, _appPaths) + await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) .AddMediaInfoWithProbe(mediaSource, isAudio, cacheKey, true, cancellationToken) .ConfigureAwait(false); } @@ -516,9 +514,9 @@ namespace Emby.Server.Implementations.Library } // TODO: @bond Fix - var json = _jsonSerializer.SerializeToString(mediaSource); + var json = JsonSerializer.Serialize(mediaSource, JsonDefaults.GetOptions()); _logger.LogInformation("Live stream opened: " + json); - var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json); + var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, JsonDefaults.GetOptions()); if (!request.UserId.Equals(Guid.Empty)) { @@ -643,7 +641,8 @@ namespace Emby.Server.Implementations.Library { try { - mediaInfo = _jsonSerializer.DeserializeFromFile<MediaInfo>(cacheFilePath); + var json = await File.ReadAllTextAsync(cacheFilePath, cancellationToken).ConfigureAwait(false); + mediaInfo = JsonSerializer.Deserialize<MediaInfo>(json, JsonDefaults.GetOptions()); // _logger.LogDebug("Found cached media info"); } @@ -679,7 +678,8 @@ namespace Emby.Server.Implementations.Library if (cacheFilePath != null) { Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); - _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath); + await using FileStream createStream = File.Create(cacheFilePath); + await JsonSerializer.SerializeAsync(createStream, mediaInfo, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Saved media info to {0}", cacheFilePath); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 0dc045ee6f..2c0de661df 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -36,7 +36,6 @@ using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Providers; using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV @@ -51,7 +50,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly ILogger<EmbyTV> _logger; private readonly IHttpClientFactory _httpClientFactory; private readonly IServerConfigurationManager _config; - private readonly IJsonSerializer _jsonSerializer; private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider; private readonly TimerManager _timerProvider; @@ -81,7 +79,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV IStreamHelper streamHelper, IMediaSourceManager mediaSourceManager, ILogger<EmbyTV> logger, - IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory, IServerConfigurationManager config, ILiveTvManager liveTvManager, @@ -103,12 +100,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _providerManager = providerManager; _mediaEncoder = mediaEncoder; _liveTvManager = (LiveTvManager)liveTvManager; - _jsonSerializer = jsonSerializer; _mediaSourceManager = mediaSourceManager; _streamHelper = streamHelper; - _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json")); - _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json")); + _seriesTimerProvider = new SeriesTimerManager(_logger, Path.Combine(DataPath, "seriestimers.json")); + _timerProvider = new TimerManager(_logger, Path.Combine(DataPath, "timers.json")); _timerProvider.TimerFired += OnTimerProviderTimerFired; _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated; @@ -1052,7 +1048,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV IgnoreIndex = true }; - await new LiveStreamHelper(_mediaEncoder, _logger, _jsonSerializer, _config.CommonApplicationPaths) + await new LiveStreamHelper(_mediaEncoder, _logger, _config.CommonApplicationPaths) .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false); return new List<MediaSourceInfo> @@ -1635,7 +1631,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http)) { - return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, _config); + return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _config); } return new DirectRecorder(_logger, _httpClientFactory, _streamHelper); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index e6ee9819eb..9609f28816 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -6,16 +6,17 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Json; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV @@ -25,7 +26,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly ILogger _logger; private readonly IMediaEncoder _mediaEncoder; private readonly IServerApplicationPaths _appPaths; - private readonly IJsonSerializer _json; private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>(); private readonly IServerConfigurationManager _serverConfigurationManager; @@ -38,13 +38,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV ILogger logger, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, - IJsonSerializer json, IServerConfigurationManager serverConfigurationManager) { _logger = logger; _mediaEncoder = mediaEncoder; _appPaths = appPaths; - _json = json; _serverConfigurationManager = serverConfigurationManager; } @@ -95,7 +93,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); - var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); + var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(mediaSource, JsonDefaults.GetOptions()) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); _process = new Process diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index fc543dc551..5256a0ee72 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -4,7 +4,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using MediaBrowser.Model.Serialization; +using System.Text.Json; +using MediaBrowser.Common.Json; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV @@ -12,18 +13,15 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public class ItemDataProvider<T> where T : class { - private readonly IJsonSerializer _jsonSerializer; private readonly string _dataPath; private readonly object _fileDataLock = new object(); private T[] _items; public ItemDataProvider( - IJsonSerializer jsonSerializer, ILogger logger, string dataPath, Func<T, T, bool> equalityComparer) { - _jsonSerializer = jsonSerializer; Logger = logger; _dataPath = dataPath; EqualityComparer = equalityComparer; @@ -46,7 +44,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - _items = _jsonSerializer.DeserializeFromFile<T[]>(_dataPath); + var json = File.ReadAllText(_dataPath); + _items = JsonSerializer.Deserialize<T[]>(json, JsonDefaults.GetOptions()); return; } catch (Exception ex) @@ -61,7 +60,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void SaveList() { Directory.CreateDirectory(Path.GetDirectoryName(_dataPath)); - _jsonSerializer.SerializeToFile(_items, _dataPath); + using FileStream stream = File.OpenWrite(_dataPath); + JsonSerializer.SerializeAsync(stream, _items, JsonDefaults.GetOptions()); } public IReadOnlyList<T> GetAll() diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index 194e4606de..da707fec63 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -9,8 +9,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { public class SeriesTimerManager : ItemDataProvider<SeriesTimerInfo> { - public SeriesTimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath) - : base(jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)) + public SeriesTimerManager(ILogger logger, string dataPath) + : base(logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)) { } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index dd479b7d1b..1efa90e256 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -8,7 +8,6 @@ using System.Threading; using Jellyfin.Data.Events; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV @@ -17,8 +16,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { private readonly ConcurrentDictionary<string, Timer> _timers = new ConcurrentDictionary<string, Timer>(StringComparer.OrdinalIgnoreCase); - public TimerManager(IJsonSerializer jsonSerializer, ILogger logger, string dataPath) - : base(jsonSerializer, logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)) + public TimerManager(ILogger logger, string dataPath) + : base(logger, dataPath, (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)) { } diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 90e6cc9668..198d196c23 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -9,16 +9,17 @@ using System.Net; using System.Net.Http; using System.Net.Mime; using System.Text; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Cryptography; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.Listings @@ -28,7 +29,6 @@ namespace Emby.Server.Implementations.LiveTv.Listings private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; private readonly ILogger<SchedulesDirect> _logger; - private readonly IJsonSerializer _jsonSerializer; private readonly IHttpClientFactory _httpClientFactory; private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1); private readonly IApplicationHost _appHost; @@ -39,13 +39,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings public SchedulesDirect( ILogger<SchedulesDirect> logger, - IJsonSerializer jsonSerializer, IHttpClientFactory httpClientFactory, IApplicationHost appHost, ICryptoProvider cryptoProvider) { _logger = logger; - _jsonSerializer = jsonSerializer; _httpClientFactory = httpClientFactory; _appHost = appHost; _cryptoProvider = cryptoProvider; @@ -104,7 +102,9 @@ namespace Emby.Server.Implementations.LiveTv.Listings } }; - var requestString = _jsonSerializer.SerializeToString(requestList); + var jsonOptions = JsonDefaults.GetOptions(); + + var requestString = JsonSerializer.Serialize(requestList, jsonOptions); _logger.LogDebug("Request string for schedules is: {RequestString}", requestString); using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); @@ -112,7 +112,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings options.Headers.TryAddWithoutValidation("token", token); using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false); await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(responseStream).ConfigureAwait(false); + var dailySchedules = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Day>>(responseStream, jsonOptions).ConfigureAwait(false); _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); @@ -123,7 +123,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false); await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream).ConfigureAwait(false); + var programDetails = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream, jsonOptions).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); var programIdsWithImages = @@ -479,7 +479,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false); await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(response).ConfigureAwait(false); + return await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ShowImages>>(response, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); } catch (Exception ex) { @@ -508,7 +508,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false); await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(response).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Headends>>(response, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (root != null) { @@ -649,7 +649,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Token>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (string.Equals(root.message, "OK", StringComparison.Ordinal)) { _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); @@ -705,7 +705,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpResponse.EnsureSuccessStatusCode(); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var response = httpResponse.Content; - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(stream).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Lineups>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); } @@ -777,7 +777,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(stream).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Channel>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); _logger.LogInformation("Mapping Stations to Channel"); diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 30aaf3a058..11355872f3 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -5,7 +5,9 @@ using System.Globalization; using System.IO; using System.Linq; using System.Reflection; +using System.Text.Json; using System.Threading.Tasks; +using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; @@ -24,7 +26,6 @@ namespace Emby.Server.Implementations.Localization private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" }; private readonly IServerConfigurationManager _configurationManager; - private readonly IJsonSerializer _jsonSerializer; private readonly ILogger<LocalizationManager> _logger; private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings = @@ -43,11 +44,9 @@ namespace Emby.Server.Implementations.Localization /// <param name="logger">The logger.</param> public LocalizationManager( IServerConfigurationManager configurationManager, - IJsonSerializer jsonSerializer, ILogger<LocalizationManager> logger) { _configurationManager = configurationManager; - _jsonSerializer = jsonSerializer; _logger = logger; } @@ -179,8 +178,11 @@ namespace Emby.Server.Implementations.Localization /// <inheritdoc /> public IEnumerable<CountryInfo> GetCountries() - => _jsonSerializer.DeserializeFromStream<IEnumerable<CountryInfo>>( - _assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json")); + { + StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json")); + + return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), JsonDefaults.GetOptions()); + } /// <inheritdoc /> public IEnumerable<ParentalRating> GetParentalRatings() @@ -344,7 +346,7 @@ namespace Emby.Server.Implementations.Localization // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain if (stream != null) { - var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream).ConfigureAwait(false); + var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); foreach (var key in dict.Keys) { diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 3a9e284583..4ac4443cd6 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -4,13 +4,14 @@ using System; using System.Globalization; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Events; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Json; using MediaBrowser.Common.Progress; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; @@ -21,11 +22,6 @@ namespace Emby.Server.Implementations.ScheduledTasks /// </summary> public class ScheduledTaskWorker : IScheduledTaskWorker { - /// <summary> - /// Gets or sets the json serializer. - /// </summary> - /// <value>The json serializer.</value> - private readonly IJsonSerializer _jsonSerializer; /// <summary> /// Gets or sets the application paths. @@ -88,7 +84,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// or /// logger. /// </exception> - public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger) + public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger) { if (scheduledTask == null) { @@ -105,11 +101,6 @@ namespace Emby.Server.Implementations.ScheduledTasks throw new ArgumentNullException(nameof(taskManager)); } - if (jsonSerializer == null) - { - throw new ArgumentNullException(nameof(jsonSerializer)); - } - if (logger == null) { throw new ArgumentNullException(nameof(logger)); @@ -118,7 +109,6 @@ namespace Emby.Server.Implementations.ScheduledTasks ScheduledTask = scheduledTask; _applicationPaths = applicationPaths; _taskManager = taskManager; - _jsonSerializer = jsonSerializer; _logger = logger; InitTriggerEvents(); @@ -150,7 +140,15 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - _lastExecutionResult = _jsonSerializer.DeserializeFromFile<TaskResult>(path); + var jsonString = File.ReadAllText(path); + if (!string.IsNullOrWhiteSpace(jsonString)) + { + _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, JsonDefaults.GetOptions()); + } + else + { + _logger.LogDebug("Scheduled Task history file {path} is empty. Skipping deserialization.", path); + } } catch (Exception ex) { @@ -174,7 +172,8 @@ namespace Emby.Server.Implementations.ScheduledTasks lock (_lastExecutionResultSyncLock) { - _jsonSerializer.SerializeToFile(value, path); + using FileStream createStream = File.OpenWrite(path); + JsonSerializer.SerializeAsync(createStream, value, JsonDefaults.GetOptions()); } } } @@ -537,7 +536,8 @@ namespace Emby.Server.Implementations.ScheduledTasks TaskTriggerInfo[] list = null; if (File.Exists(path)) { - list = _jsonSerializer.DeserializeFromFile<TaskTriggerInfo[]>(path); + var jsonString = File.ReadAllText(path); + list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(jsonString, JsonDefaults.GetOptions()); } // Return defaults if file doesn't exist. @@ -573,7 +573,8 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(Path.GetDirectoryName(path)); - _jsonSerializer.SerializeToFile(triggers, path); + using FileStream stream = File.OpenWrite(path); + JsonSerializer.SerializeAsync(stream, triggers, JsonDefaults.GetOptions()); } /// <summary> diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index cfbf03ddc0..197a5ed5ef 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Threading.Tasks; using Jellyfin.Data.Events; using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; @@ -19,6 +18,7 @@ namespace Emby.Server.Implementations.ScheduledTasks public class TaskManager : ITaskManager { public event EventHandler<GenericEventArgs<IScheduledTaskWorker>> TaskExecuting; + public event EventHandler<TaskCompletionEventArgs> TaskCompleted; /// <summary> @@ -33,7 +33,6 @@ namespace Emby.Server.Implementations.ScheduledTasks private readonly ConcurrentQueue<Tuple<Type, TaskOptions>> _taskQueue = new ConcurrentQueue<Tuple<Type, TaskOptions>>(); - private readonly IJsonSerializer _jsonSerializer; private readonly IApplicationPaths _applicationPaths; private readonly ILogger<TaskManager> _logger; @@ -45,11 +44,9 @@ namespace Emby.Server.Implementations.ScheduledTasks /// <param name="logger">The logger.</param> public TaskManager( IApplicationPaths applicationPaths, - IJsonSerializer jsonSerializer, ILogger<TaskManager> logger) { _applicationPaths = applicationPaths; - _jsonSerializer = jsonSerializer; _logger = logger; ScheduledTasks = Array.Empty<IScheduledTaskWorker>(); @@ -196,7 +193,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// <param name="tasks">The tasks.</param> public void AddTasks(IEnumerable<IScheduledTask> tasks) { - var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _jsonSerializer, _logger)); + var list = tasks.Select(t => new ScheduledTaskWorker(t, _applicationPaths, this, _logger)); ScheduledTasks = ScheduledTasks.Concat(list).ToArray(); } From e9902e9d35978b0f0d56b35612fa092daf6145c8 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:13:28 +0100 Subject: [PATCH 0837/1930] Remove custom Json serializer --- .../Serialization/JsonSerializer.cs | 281 ------------------ .../Serialization/IJsonSerializer.cs | 102 ------- 2 files changed, 383 deletions(-) delete mode 100644 Emby.Server.Implementations/Serialization/JsonSerializer.cs delete mode 100644 MediaBrowser.Model/Serialization/IJsonSerializer.cs diff --git a/Emby.Server.Implementations/Serialization/JsonSerializer.cs b/Emby.Server.Implementations/Serialization/JsonSerializer.cs deleted file mode 100644 index 5ec3a735a6..0000000000 --- a/Emby.Server.Implementations/Serialization/JsonSerializer.cs +++ /dev/null @@ -1,281 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Globalization; -using System.IO; -using System.Threading.Tasks; -using MediaBrowser.Model.Serialization; - -namespace Emby.Server.Implementations.Serialization -{ - /// <summary> - /// Provides a wrapper around third party json serialization. - /// </summary> - public class JsonSerializer : IJsonSerializer - { - /// <summary> - /// Initializes a new instance of the <see cref="JsonSerializer" /> class. - /// </summary> - public JsonSerializer() - { - ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601; - ServiceStack.Text.JsConfig.ExcludeTypeInfo = true; - ServiceStack.Text.JsConfig.IncludeNullValues = false; - ServiceStack.Text.JsConfig.AlwaysUseUtc = true; - ServiceStack.Text.JsConfig.AssumeUtc = true; - - ServiceStack.Text.JsConfig<Guid>.SerializeFn = SerializeGuid; - } - - /// <summary> - /// Serializes to stream. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="stream">The stream.</param> - /// <exception cref="ArgumentNullException">obj</exception> - public void SerializeToStream(object obj, Stream stream) - { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - ServiceStack.Text.JsonSerializer.SerializeToStream(obj, obj.GetType(), stream); - } - - /// <summary> - /// Serializes to stream. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="stream">The stream.</param> - /// <exception cref="ArgumentNullException">obj</exception> - public void SerializeToStream<T>(T obj, Stream stream) - { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - ServiceStack.Text.JsonSerializer.SerializeToStream<T>(obj, stream); - } - - /// <summary> - /// Serializes to file. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="file">The file.</param> - /// <exception cref="ArgumentNullException">obj</exception> - public void SerializeToFile(object obj, string file) - { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - - if (string.IsNullOrEmpty(file)) - { - throw new ArgumentNullException(nameof(file)); - } - - using (var stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) - { - SerializeToStream(obj, stream); - } - } - - private static Stream OpenFile(string path) - { - return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072); - } - - /// <summary> - /// Deserializes from file. - /// </summary> - /// <param name="type">The type.</param> - /// <param name="file">The file.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">type</exception> - public object DeserializeFromFile(Type type, string file) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (string.IsNullOrEmpty(file)) - { - throw new ArgumentNullException(nameof(file)); - } - - using (var stream = OpenFile(file)) - { - return DeserializeFromStream(stream, type); - } - } - - /// <summary> - /// Deserializes from file. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="file">The file.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">file</exception> - public T DeserializeFromFile<T>(string file) - where T : class - { - if (string.IsNullOrEmpty(file)) - { - throw new ArgumentNullException(nameof(file)); - } - - using (var stream = OpenFile(file)) - { - return DeserializeFromStream<T>(stream); - } - } - - /// <summary> - /// Deserializes from stream. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="stream">The stream.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">stream</exception> - public T DeserializeFromStream<T>(Stream stream) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - return ServiceStack.Text.JsonSerializer.DeserializeFromStream<T>(stream); - } - - public Task<T> DeserializeFromStreamAsync<T>(Stream stream) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - return ServiceStack.Text.JsonSerializer.DeserializeFromStreamAsync<T>(stream); - } - - /// <summary> - /// Deserializes from string. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="text">The text.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">text</exception> - public T DeserializeFromString<T>(string text) - { - if (string.IsNullOrEmpty(text)) - { - throw new ArgumentNullException(nameof(text)); - } - - return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(text); - } - - /// <summary> - /// Deserializes from stream. - /// </summary> - /// <param name="stream">The stream.</param> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">stream</exception> - public object DeserializeFromStream(Stream stream, Type type) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - return ServiceStack.Text.JsonSerializer.DeserializeFromStream(type, stream); - } - - public async Task<object> DeserializeFromStreamAsync(Stream stream, Type type) - { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - using (var reader = new StreamReader(stream)) - { - var json = await reader.ReadToEndAsync().ConfigureAwait(false); - - return ServiceStack.Text.JsonSerializer.DeserializeFromString(json, type); - } - } - - private static string SerializeGuid(Guid guid) - { - if (guid.Equals(Guid.Empty)) - { - return null; - } - - return guid.ToString("N", CultureInfo.InvariantCulture); - } - - /// <summary> - /// Deserializes from string. - /// </summary> - /// <param name="json">The json.</param> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">json</exception> - public object DeserializeFromString(string json, Type type) - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentNullException(nameof(json)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - return ServiceStack.Text.JsonSerializer.DeserializeFromString(json, type); - } - - /// <summary> - /// Serializes to string. - /// </summary> - /// <param name="obj">The obj.</param> - /// <returns>System.String.</returns> - /// <exception cref="ArgumentNullException">obj</exception> - public string SerializeToString(object obj) - { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - - return ServiceStack.Text.JsonSerializer.SerializeToString(obj, obj.GetType()); - } - } -} diff --git a/MediaBrowser.Model/Serialization/IJsonSerializer.cs b/MediaBrowser.Model/Serialization/IJsonSerializer.cs deleted file mode 100644 index 09b6ff9b5a..0000000000 --- a/MediaBrowser.Model/Serialization/IJsonSerializer.cs +++ /dev/null @@ -1,102 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; -using System.IO; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Serialization -{ - public interface IJsonSerializer - { - /// <summary> - /// Serializes to stream. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="stream">The stream.</param> - /// <exception cref="ArgumentNullException">obj</exception> - void SerializeToStream(object obj, Stream stream); - - /// <summary> - /// Serializes to stream. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="stream">The stream.</param> - /// <exception cref="ArgumentNullException">obj</exception> - void SerializeToStream<T>(T obj, Stream stream); - - /// <summary> - /// Serializes to file. - /// </summary> - /// <param name="obj">The obj.</param> - /// <param name="file">The file.</param> - /// <exception cref="ArgumentNullException">obj</exception> - void SerializeToFile(object obj, string file); - - /// <summary> - /// Deserializes from file. - /// </summary> - /// <param name="type">The type.</param> - /// <param name="file">The file.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">type</exception> - object DeserializeFromFile(Type type, string file); - - /// <summary> - /// Deserializes from file. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="file">The file.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">file</exception> - T DeserializeFromFile<T>(string file) - where T : class; - - /// <summary> - /// Deserializes from stream. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="stream">The stream.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">stream</exception> - T DeserializeFromStream<T>(Stream stream); - - /// <summary> - /// Deserializes from string. - /// </summary> - /// <typeparam name="T"></typeparam> - /// <param name="text">The text.</param> - /// <returns>``0.</returns> - /// <exception cref="ArgumentNullException">text</exception> - T DeserializeFromString<T>(string text); - - /// <summary> - /// Deserializes from stream. - /// </summary> - /// <param name="stream">The stream.</param> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">stream</exception> - object DeserializeFromStream(Stream stream, Type type); - - /// <summary> - /// Deserializes from string. - /// </summary> - /// <param name="json">The json.</param> - /// <param name="type">The type.</param> - /// <returns>System.Object.</returns> - /// <exception cref="ArgumentNullException">json</exception> - object DeserializeFromString(string json, Type type); - - /// <summary> - /// Serializes to string. - /// </summary> - /// <param name="obj">The obj.</param> - /// <returns>System.String.</returns> - /// <exception cref="ArgumentNullException">obj</exception> - string SerializeToString(object obj); - - Task<object> DeserializeFromStreamAsync(Stream stream, Type type); - Task<T> DeserializeFromStreamAsync<T>(Stream stream); - } -} From b9dbdc7e542af6e84de75e5548f4185646383d6d Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:24:14 +0100 Subject: [PATCH 0838/1930] Remove custom Json serializer from MediaBrowser.Controller --- MediaBrowser.Controller/Entities/CollectionFolder.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index d25545a2fc..b960278b85 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -4,9 +4,11 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Json; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -26,8 +28,6 @@ namespace MediaBrowser.Controller.Entities { public static IXmlSerializer XmlSerializer { get; set; } - public static IJsonSerializer JsonSerializer { get; set; } - public static IServerApplicationHost ApplicationHost { get; set; } public CollectionFolder() @@ -122,7 +122,8 @@ namespace MediaBrowser.Controller.Entities { LibraryOptions[path] = options; - var clone = JsonSerializer.DeserializeFromString<LibraryOptions>(JsonSerializer.SerializeToString(options)); + var jsonOptions = JsonDefaults.GetOptions(); + var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.Serialize(options, jsonOptions), jsonOptions); foreach (var mediaPath in clone.PathInfos) { if (!string.IsNullOrEmpty(mediaPath.Path)) From 62fcc84bf4ba3affeb7ab853cfb6880417fd1a9e Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:35:49 +0100 Subject: [PATCH 0839/1930] Remove nuget reference --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 9e9452f32c..1416ffa261 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -37,7 +37,6 @@ <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" /> <PackageReference Include="Mono.Nat" Version="3.0.1" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.1" /> - <PackageReference Include="ServiceStack.Text.Core" Version="5.10.2" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="2.1.0" /> <PackageReference Include="DotNet.Glob" Version="3.1.0" /> From 276b219fbdaaf14e16bc9e3435d1d9c571ed1cf8 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 13:43:42 +0100 Subject: [PATCH 0840/1930] Add missing options --- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index e73085460d..374b154e1e 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -298,10 +298,11 @@ namespace MediaBrowser.Providers.Plugins.Omdb using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var rootObject = await JsonSerializer.DeserializeAsync<RootObject>(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + var jsonOptions = JsonDefaults.GetOptions(); + var rootObject = await JsonSerializer.DeserializeAsync<RootObject>(stream, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.Create(path); - await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); return path; } @@ -337,10 +338,11 @@ namespace MediaBrowser.Providers.Plugins.Omdb using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var rootObject = await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + var jsonOptions = JsonDefaults.GetOptions(); + var rootObject = await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.Create(path); - await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); return path; } From e2d338412fea5489aadb0e75af96cb36e4f13317 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 14:45:05 +0100 Subject: [PATCH 0841/1930] Fix OMDb "N/A" --- .../Plugins/Omdb/OmdbProvider.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 374b154e1e..bbedffbc7d 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -296,10 +296,8 @@ namespace MediaBrowser.Providers.Plugins.Omdb "i={0}&plot=short&tomatoes=true&r=json", imdbParam)); - using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var jsonOptions = JsonDefaults.GetOptions(); - var rootObject = await JsonSerializer.DeserializeAsync<RootObject>(stream, jsonOptions, cancellationToken).ConfigureAwait(false); + var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.Create(path); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); @@ -336,10 +334,8 @@ namespace MediaBrowser.Providers.Plugins.Omdb imdbParam, seasonId)); - using var response = await GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var jsonOptions = JsonDefaults.GetOptions(); - var rootObject = await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, jsonOptions, cancellationToken).ConfigureAwait(false); + var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.Create(path); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); @@ -347,6 +343,16 @@ namespace MediaBrowser.Providers.Plugins.Omdb return path; } + public static async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, JsonSerializerOptions jsonOptions, CancellationToken cancellationToken) + { + using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); + var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + // OMDb is sending "N/A" for no empty number fields + content = content.Replace("\"N/A\"", "\"0\"", StringComparison.InvariantCulture); + return JsonSerializer.Deserialize<T>(content, jsonOptions); + } + public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken) { return httpClient.GetAsync(url, cancellationToken); From f38970cbd32c845d1740828450aac8de16fec788 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 15:03:14 +0100 Subject: [PATCH 0842/1930] Remove xml docs --- Emby.Server.Implementations/Channels/ChannelManager.cs | 1 - Emby.Server.Implementations/Localization/LocalizationManager.cs | 1 - .../ScheduledTasks/ScheduledTaskWorker.cs | 1 - Emby.Server.Implementations/ScheduledTasks/TaskManager.cs | 1 - 4 files changed, 4 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 0966c252ba..4e4fbf82c6 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -59,7 +59,6 @@ namespace Emby.Server.Implementations.Channels /// <param name="config">The server configuration manager.</param> /// <param name="fileSystem">The filesystem.</param> /// <param name="userDataManager">The user data manager.</param> - /// <param name="jsonSerializer">The JSON serializer.</param> /// <param name="providerManager">The provider manager.</param> /// <param name="memoryCache">The memory cache.</param> public ChannelManager( diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 11355872f3..2d6fb252d2 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -40,7 +40,6 @@ namespace Emby.Server.Implementations.Localization /// Initializes a new instance of the <see cref="LocalizationManager" /> class. /// </summary> /// <param name="configurationManager">The configuration manager.</param> - /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> public LocalizationManager( IServerConfigurationManager configurationManager, diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 4ac4443cd6..eee7aeea30 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -71,7 +71,6 @@ namespace Emby.Server.Implementations.ScheduledTasks /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> - /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="ArgumentNullException"> /// scheduledTask diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index 197a5ed5ef..af316e1083 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -40,7 +40,6 @@ namespace Emby.Server.Implementations.ScheduledTasks /// Initializes a new instance of the <see cref="TaskManager" /> class. /// </summary> /// <param name="applicationPaths">The application paths.</param> - /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> public TaskManager( IApplicationPaths applicationPaths, From af8acf7128c66b369cd8cad0aaebc4c3dd963c41 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 23 Dec 2020 09:01:24 -0700 Subject: [PATCH 0843/1930] Initialize JsonSerializerOptions statically --- MediaBrowser.Common/Json/JsonDefaults.cs | 78 ++++++++++++++---------- 1 file changed, 46 insertions(+), 32 deletions(-) diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 128cc9d5d0..1ec2a87c53 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -19,56 +19,70 @@ namespace MediaBrowser.Common.Json /// </summary> public const string CamelCaseMediaType = "application/json; profile=\"CamelCase\""; + /// <summary> + /// When changing these options, update + /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs + /// -> AddJellyfinApi + /// -> AddJsonOptions. + /// </summary> + private static readonly JsonSerializerOptions _jsonSerializerOptions = new () + { + ReadCommentHandling = JsonCommentHandling.Disallow, + WriteIndented = false, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + NumberHandling = JsonNumberHandling.AllowReadingFromString, + Converters = + { + new JsonGuidConverter(), + new JsonVersionConverter(), + new JsonStringEnumConverter(), + new JsonNullableStructConverterFactory(), + new JsonBoolNumberConverter(), + new JsonDateTimeConverter() + } + }; + + private static readonly JsonSerializerOptions _pascalCaseJsonSerializerOptions = new (_jsonSerializerOptions) + { + PropertyNamingPolicy = null + }; + + private static readonly JsonSerializerOptions _camelCaseJsonSerializerOptions = new (_jsonSerializerOptions) + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + /// <summary> /// Gets the default <see cref="JsonSerializerOptions" /> options. /// </summary> /// <remarks> - /// When changing these options, update - /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs - /// -> AddJellyfinApi - /// -> AddJsonOptions. + /// The return value must not be modified. + /// If the defaults must be modified the author must use the copy constructor. /// </remarks> /// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns> public static JsonSerializerOptions GetOptions() - { - var options = new JsonSerializerOptions - { - ReadCommentHandling = JsonCommentHandling.Disallow, - WriteIndented = false, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - NumberHandling = JsonNumberHandling.AllowReadingFromString - }; - - options.Converters.Add(new JsonGuidConverter()); - options.Converters.Add(new JsonVersionConverter()); - options.Converters.Add(new JsonStringEnumConverter()); - options.Converters.Add(new JsonNullableStructConverterFactory()); - options.Converters.Add(new JsonBoolNumberConverter()); - options.Converters.Add(new JsonDateTimeConverter()); - - return options; - } + => _jsonSerializerOptions; /// <summary> /// Gets camelCase json options. /// </summary> + /// <remarks> + /// The return value must not be modified. + /// If the defaults must be modified the author must use the copy constructor. + /// </remarks> /// <returns>The camelCase <see cref="JsonSerializerOptions" /> options.</returns> public static JsonSerializerOptions GetCamelCaseOptions() - { - var options = GetOptions(); - options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; - return options; - } + => _camelCaseJsonSerializerOptions; /// <summary> /// Gets PascalCase json options. /// </summary> + /// <remarks> + /// The return value must not be modified. + /// If the defaults must be modified the author must use the copy constructor. + /// </remarks> /// <returns>The PascalCase <see cref="JsonSerializerOptions" /> options.</returns> public static JsonSerializerOptions GetPascalCaseOptions() - { - var options = GetOptions(); - options.PropertyNamingPolicy = null; - return options; - } + => _pascalCaseJsonSerializerOptions; } } From 62702fa3eb5070ce8c57dc4e39551bcc4e64fa74 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 16:28:50 +0000 Subject: [PATCH 0844/1930] Changes as requested --- .../ApplicationHost.cs | 2 +- .../Plugins/PluginManager.cs | 45 +++++++++++++------ Jellyfin.Api/Controllers/PluginsController.cs | 16 ++----- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 1 - MediaBrowser.Common/Plugins/BasePluginOfT.cs | 20 +++------ .../Plugins/IHasPluginConfiguration.cs | 6 --- MediaBrowser.Common/Plugins/IPluginManager.cs | 1 + MediaBrowser.Common/Plugins/PluginManifest.cs | 4 +- 8 files changed, 43 insertions(+), 52 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index f73cd1ea4f..b91ba6b6ca 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -462,7 +462,7 @@ namespace Emby.Server.Implementations { // Convert to list so this isn't executed for each iteration var parts = GetExportTypes<T>() - .Select(defaultFunc) + .Select(i => defaultFunc(i)) .Where(i => i != null) .Cast<T>() .ToList(); diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 629975abb1..c063597575 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Reflection; using System.Text; using System.Text.Json; +using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; @@ -86,7 +87,8 @@ namespace Emby.Server.Implementations.Plugins var plugin = _plugins[i]; if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin)) { - UpdateSuccessors(plugin); + // See if there is another version, and if so make that active. + ProcessAlternative(plugin); } } @@ -208,12 +210,19 @@ namespace Emby.Server.Implementations.Plugins if (DeletePlugin(plugin)) { + ProcessAlternative(plugin); return true; } _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path); // Unable to delete, so disable. - return ChangePluginState(plugin, PluginStatus.Deleted); + if (ChangePluginState(plugin, PluginStatus.Deleted)) + { + ProcessAlternative(plugin); + return true; + } + + return false; } /// <summary> @@ -232,9 +241,9 @@ namespace Emby.Server.Implementations.Plugins var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList(); plugin = plugins.FirstOrDefault(p => p.Instance != null); - if (plugin == null && plugins.Length > 0) + if (plugin == null) { - plugin = plugins.OrderByDescending(p => p.Version)[0]; + plugin = plugins.OrderByDescending(p => p.Version).FirstOrDefault(); } } else @@ -259,7 +268,8 @@ namespace Emby.Server.Implementations.Plugins if (ChangePluginState(plugin, PluginStatus.Active)) { - UpdateSuccessors(plugin); + // See if there is another version, and if so, supercede it. + ProcessAlternative(plugin); } } @@ -277,7 +287,8 @@ namespace Emby.Server.Implementations.Plugins // Update the manifest on disk if (ChangePluginState(plugin, PluginStatus.Disabled)) { - UpdateSuccessors(plugin); + // If there is another version, activate it. + ProcessAlternative(plugin); } } @@ -639,27 +650,33 @@ namespace Emby.Server.Implementations.Plugins /// Changes the status of the other versions of the plugin to "Superceded". /// </summary> /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param> - private void UpdateSuccessors(LocalPlugin plugin) + private void ProcessAlternative(LocalPlugin plugin) { - // This value is memory only - so that the web will show restart required. - plugin.Manifest.Status = PluginStatus.Restart; - // Detect whether there is another version of this plugin that needs disabling. - var predecessor = _plugins.OrderByDescending(p => p.Version) + var previousVersion = _plugins.OrderByDescending(p => p.Version) .FirstOrDefault( p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version); - if (predecessor == null) + if (previousVersion == null) { + // This value is memory only - so that the web will show restart required. + plugin.Manifest.Status = PluginStatus.Restart; return; } - if (predecessor.Manifest.Status == PluginStatus.Active && !ChangePluginState(predecessor, PluginStatus.Superceded)) + if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Superceded)) { - _logger.LogError("Unable to disable version {Version} of {Name}", predecessor.Version, predecessor.Name); + _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersion.Name); } + else if (plugin.Manifest.Status == PluginStatus.Superceded && !ChangePluginState(previousVersion, PluginStatus.Active)) + { + _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVersion.Name); + } + + // This value is memory only - so that the web will show restart required. + plugin.Manifest.Status = PluginStatus.Restart; } } } diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 365bb2248c..b73611c979 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -198,7 +198,7 @@ namespace Jellyfin.Api.Controllers /// <param name="pluginId">Plugin id.</param> /// <response code="204">Plugin uninstalled.</response> /// <response code="404">Plugin not found.</response> - /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the file could not be found.</returns> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpDelete("{pluginId}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] @@ -210,7 +210,7 @@ namespace Jellyfin.Api.Controllers var plugins = _pluginManager.Plugins.Where(p => p.Id.Equals(pluginId)); // Select the un-instanced one first. - var plugin = plugins.FirstOrDefault(p => p.Instance != null); + var plugin = plugins.FirstOrDefault(p => p.Instance == null); if (plugin == null) { // Then by the status. @@ -256,11 +256,7 @@ namespace Jellyfin.Api.Controllers /// <param name="pluginId">Plugin id.</param> /// <response code="204">Plugin configuration updated.</response> /// <response code="404">Plugin not found or plugin does not have configuration.</response> - /// <returns> - /// A <see cref="Task" /> that represents the asynchronous operation to update plugin configuration. - /// The task result contains an <see cref="NoContentResult"/> indicating success, or <see cref="NotFoundResult"/> - /// when plugin not found or plugin doesn't have configuration. - /// </returns> + /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpPost("{pluginId}/Configuration")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] @@ -321,11 +317,7 @@ namespace Jellyfin.Api.Controllers /// <param name="pluginId">Plugin id.</param> /// <response code="204">Plugin manifest returned.</response> /// <response code="404">Plugin not found.</response> - /// <returns> - /// A <see cref="Task" /> that represents the asynchronous operation to get the plugin's manifest. - /// The task result contains an <see cref="NoContentResult"/> indicating success, or <see cref="NotFoundResult"/> - /// when plugin not found. - /// </returns> + /// <returns>A <see cref="PluginManifest"/> on success, or a <see cref="NotFoundResult"/> if the plugin could not be found.</returns> [HttpPost("{pluginId}/Manifest")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index c15ed05d39..f56ef59765 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -23,7 +23,6 @@ namespace Jellyfin.Api.Models if (page.Plugin != null) { DisplayName = page.Plugin.Name; - // Don't use "N" because it needs to match Plugin.Id PluginId = page.Plugin.Id; } } diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index ea05a722bc..d5c7808512 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -25,8 +25,6 @@ namespace MediaBrowser.Common.Plugins /// </summary> private readonly object _configurationSaveLock = new object(); - private Action<string> _directoryCreateFn; - /// <summary> /// The configuration. /// </summary> @@ -65,11 +63,6 @@ namespace MediaBrowser.Common.Plugins assemblyPlugin.SetId(assemblyId); } } - - if (this is IHasPluginConfiguration hasPluginConfiguration) - { - hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s)); - } } /// <summary> @@ -145,13 +138,6 @@ namespace MediaBrowser.Common.Plugins /// <value>The configuration.</value> BasePluginConfiguration IHasPluginConfiguration.Configuration => Configuration; - /// <inheritdoc /> - public void SetStartupInfo(Action<string> directoryCreateFn) - { - // hack alert, until the .net core transition is complete - _directoryCreateFn = directoryCreateFn; - } - /// <summary> /// Saves the current configuration to the file system. /// </summary> @@ -160,7 +146,11 @@ namespace MediaBrowser.Common.Plugins { lock (_configurationSaveLock) { - _directoryCreateFn(Path.GetDirectoryName(ConfigurationFilePath)); + var folder = Path.GetDirectoryName(ConfigurationFilePath); + if (!Directory.Exists(folder)) + { + Directory.CreateDirectory(folder); + } XmlSerializer.SerializeToFile(config, ConfigurationFilePath); } diff --git a/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs index 42ad85dd37..af9272caae 100644 --- a/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs +++ b/MediaBrowser.Common/Plugins/IHasPluginConfiguration.cs @@ -23,11 +23,5 @@ namespace MediaBrowser.Common.Plugins /// </summary> /// <param name="configuration">The configuration.</param> void UpdateConfiguration(BasePluginConfiguration configuration); - - /// <summary> - /// Sets the startup directory creation function. - /// </summary> - /// <param name="directoryCreateFn">The directory function used to create the configuration folder.</param> - void SetStartupInfo(Action<string> directoryCreateFn); } } diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index 7f7381b033..3da34d8bb3 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common.Plugins diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 334c8d9082..4c724f6949 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -19,14 +19,12 @@ namespace MediaBrowser.Common.Plugins Category = string.Empty; Changelog = string.Empty; Description = string.Empty; - Status = PluginStatus.Active; Id = Guid.Empty; Name = string.Empty; Owner = string.Empty; Overview = string.Empty; TargetAbi = string.Empty; Version = string.Empty; - AutoUpdate = true; } /// <summary> @@ -99,7 +97,7 @@ namespace MediaBrowser.Common.Plugins /// Gets or sets a value indicating whether this plugin should automatically update. /// </summary> [JsonPropertyName("autoUpdate")] - public bool AutoUpdate { get; set; } + public bool AutoUpdate { get; set; } = true; // DO NOT MOVE THIS INTO THE CONSTRUCTOR. /// <summary> /// Gets or sets the ImagePath From dae6798a1821924d38fe8d8d387b4981ed03e164 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 17:25:41 +0000 Subject: [PATCH 0845/1930] Making it work --- Emby.Server.Implementations/ApplicationHost.cs | 2 -- MediaBrowser.Common/Json/JsonDefaults.cs | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index b91ba6b6ca..b88ccff199 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -118,7 +118,6 @@ namespace Emby.Server.Implementations private readonly IFileSystem _fileSystemManager; private readonly IXmlSerializer _xmlSerializer; - private readonly IJsonSerializer _jsonSerializer; private readonly IStartupOptions _startupOptions; private readonly IPluginManager _pluginManager; @@ -249,7 +248,6 @@ namespace Emby.Server.Implementations IServiceCollection serviceCollection) { _xmlSerializer = new MyXmlSerializer(); - _jsonSerializer = new JsonSerializer(); ServiceCollection = serviceCollection; diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 2b5f04cf82..67c3dfe546 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Common.Json WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, NumberHandling = JsonNumberHandling.AllowReadingFromString, - + PropertyNameCaseInsensitive = true, Converters = { new JsonGuidConverter(), From b61541b6f749a189a69011f0888496fd7fcd99a7 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 24 Dec 2020 01:32:23 +0800 Subject: [PATCH 0846/1930] fix some profiles for H264 AMF encoder --- .../MediaEncoding/EncodingHelper.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 73ede7c5a4..6667c1c3bc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1131,8 +1131,8 @@ namespace MediaBrowser.Controller.MediaEncoding profile = Regex.Replace(profile, @"\s+", string.Empty); // We only transcode to HEVC 8-bit for now, force Main Profile. - if (profile.Contains("main 10", StringComparison.OrdinalIgnoreCase) - || profile.Contains("main still", StringComparison.OrdinalIgnoreCase)) + if (profile.Contains("main10", StringComparison.OrdinalIgnoreCase) + || profile.Contains("mainstill", StringComparison.OrdinalIgnoreCase)) { profile = "main"; } @@ -1145,7 +1145,7 @@ namespace MediaBrowser.Controller.MediaEncoding // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) - && profile.Contains("high 10", StringComparison.OrdinalIgnoreCase)) + && profile.Contains("high10", StringComparison.OrdinalIgnoreCase)) { profile = "high"; } @@ -1177,9 +1177,21 @@ namespace MediaBrowser.Controller.MediaEncoding profile = "high"; } + if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + && profile.Contains("constrainedbaseline", StringComparison.OrdinalIgnoreCase)) + { + profile = "constrained_baseline"; + } + + if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) + && profile.Contains("constrainedhigh", StringComparison.OrdinalIgnoreCase)) + { + profile = "constrained_high"; + } + // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase) - && profile.Contains("main 10", StringComparison.OrdinalIgnoreCase)) + && profile.Contains("main10", StringComparison.OrdinalIgnoreCase)) { profile = "main"; } From 21f6d3943264b0f6a59f3312e9ec34a3b6269af2 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 23 Dec 2020 17:43:29 +0000 Subject: [PATCH 0847/1930] copy constructor --- Emby.Server.Implementations/Plugins/PluginManager.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index c063597575..51a75f6a39 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -51,8 +51,10 @@ namespace Emby.Server.Implementations.Plugins _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); - _jsonOptions = JsonDefaults.GetOptions(); - _jsonOptions.WriteIndented = true; + _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()) + { + WriteIndented = true + }; // We need to use the default GUID converter, so we need to remove any custom ones. for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--) From 2a574914eaca486f6216db400d9fdf88ad88636e Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 19:24:58 +0100 Subject: [PATCH 0848/1930] Use streams instead of strings --- Emby.Server.Implementations/ApplicationHost.cs | 5 +++-- .../Channels/ChannelManager.cs | 4 ++-- .../Library/LiveStreamHelper.cs | 4 ++-- .../Library/MediaSourceManager.cs | 4 ++-- .../LiveTv/EmbyTV/ItemDataProvider.cs | 4 ++-- .../ScheduledTasks/ScheduledTaskWorker.cs | 11 ++--------- .../Plugins/AudioDb/AlbumImageProvider.cs | 4 ++-- .../Plugins/AudioDb/AlbumProvider.cs | 4 ++-- .../Plugins/AudioDb/ArtistImageProvider.cs | 4 ++-- .../Plugins/AudioDb/ArtistProvider.cs | 4 ++-- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 6 +++--- 11 files changed, 24 insertions(+), 30 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index fcc156e9c5..99cd3b6cc1 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1038,6 +1038,7 @@ namespace Emby.Server.Implementations } var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); + var jsonOptions = JsonDefaults.GetOptions(); foreach (var dir in directories) { @@ -1046,8 +1047,8 @@ namespace Emby.Server.Implementations var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { - var jsonString = File.ReadAllText(metafile); - var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, JsonDefaults.GetOptions()); + using FileStream jsonStream = File.OpenRead(metafile); + var manifest = JsonSerializer.DeserializeAsync<PluginManifest>(jsonStream, jsonOptions).GetAwaiter().GetResult(); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 4e4fbf82c6..b462d7bdcd 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -340,8 +340,8 @@ namespace Emby.Server.Implementations.Channels try { - var jsonString = File.ReadAllText(path); - return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, JsonDefaults.GetOptions()) ?? new List<MediaSourceInfo>(); + using FileStream jsonStream = File.OpenRead(path); + return JsonSerializer.DeserializeAsync<List<MediaSourceInfo>>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); } catch { diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index ad7988fb15..3ceba0fe94 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -46,8 +46,8 @@ namespace Emby.Server.Implementations.Library { try { - var jsonString = await File.ReadAllTextAsync(cacheFilePath, cancellationToken).ConfigureAwait(false); - JsonSerializer.Deserialize<MediaInfo>(jsonString, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(cacheFilePath); + await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Found cached media info"); } diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 264390dd33..b3900e4aa1 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -641,8 +641,8 @@ namespace Emby.Server.Implementations.Library { try { - var json = await File.ReadAllTextAsync(cacheFilePath, cancellationToken).ConfigureAwait(false); - mediaInfo = JsonSerializer.Deserialize<MediaInfo>(json, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(cacheFilePath); + mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Found cached media info"); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 5256a0ee72..1b9abaa78e 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -44,8 +44,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var json = File.ReadAllText(_dataPath); - _items = JsonSerializer.Deserialize<T[]>(json, JsonDefaults.GetOptions()); + using FileStream jsonStream = File.OpenRead(_dataPath); + _items = JsonSerializer.DeserializeAsync<T[]>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); return; } catch (Exception ex) diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index eee7aeea30..a9f4599864 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -139,15 +139,8 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - var jsonString = File.ReadAllText(path); - if (!string.IsNullOrWhiteSpace(jsonString)) - { - _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, JsonDefaults.GetOptions()); - } - else - { - _logger.LogDebug("Scheduled Task history file {path} is empty. Skipping deserialization.", path); - } + using FileStream jsonStream = File.OpenRead(path); + _lastExecutionResult = JsonSerializer.DeserializeAsync<TaskResult>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); } catch (Exception ex) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index 605b93788b..a5aeba7d2d 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -57,8 +57,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbAlbumProvider.GetAlbumInfoPath(_config.ApplicationPaths, id); - var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); - var obj = JsonSerializer.Deserialize<AudioDbAlbumProvider.RootObject>(jsonString, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(path); + var obj = await JsonSerializer.DeserializeAsync<AudioDbAlbumProvider.RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 32ef135475..9a61abc1ac 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -64,8 +64,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetAlbumInfoPath(_config.ApplicationPaths, id); - var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); - var obj = JsonSerializer.Deserialize<RootObject>(jsonString, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(path); + var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index f0b8e00f3f..639bbe8595 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -59,8 +59,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbArtistProvider.GetArtistInfoPath(_config.ApplicationPaths, id); - var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); - var obj = JsonSerializer.Deserialize<AudioDbArtistProvider.RootObject>(jsonString, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(path); + var obj = await JsonSerializer.DeserializeAsync<AudioDbArtistProvider.RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 2476c86715..71efd194e3 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -65,8 +65,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetArtistInfoPath(_config.ApplicationPaths, id); - var jsonString = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); - var obj = JsonSerializer.Deserialize<RootObject>(jsonString, JsonDefaults.GetOptions()); + await using FileStream jsonStream = File.OpenRead(path); + var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index bbedffbc7d..fa75e4ec49 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -299,7 +299,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var jsonOptions = JsonDefaults.GetOptions(); var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); - await using FileStream jsonFileStream = File.Create(path); + await using FileStream jsonFileStream = File.OpenWrite(path); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); return path; @@ -337,7 +337,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var jsonOptions = JsonDefaults.GetOptions(); var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); - await using FileStream jsonFileStream = File.Create(path); + await using FileStream jsonFileStream = File.OpenWrite(path); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); return path; @@ -349,7 +349,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // OMDb is sending "N/A" for no empty number fields - content = content.Replace("\"N/A\"", "\"0\"", StringComparison.InvariantCulture); + content = content.Replace("\"N/A\"", "\"\"", StringComparison.InvariantCulture); return JsonSerializer.Deserialize<T>(content, jsonOptions); } From 79cf57ce16c969963a88ba26baa838bea7465a2c Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 23 Dec 2020 12:33:50 -0700 Subject: [PATCH 0849/1930] Remove SQLitePCLRaw.provider.sqlite3.netstandard11 --- Jellyfin.Server/Jellyfin.Server.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 97fb56ba1e..bc000fd458 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -52,7 +52,6 @@ <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" /> <PackageReference Include="Serilog.Sinks.Graylog" Version="2.2.2" /> <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="2.0.4" /> - <PackageReference Include="SQLitePCLRaw.provider.sqlite3.netstandard11" Version="1.1.14" /> </ItemGroup> <ItemGroup> From 570b4dc0d04d018a4e6aeeb161a17706da3bda21 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 23 Dec 2020 12:34:07 -0700 Subject: [PATCH 0850/1930] Explicity reference Newtonsoft.Json --- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index fc8eb8c4e4..071a149db9 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -19,6 +19,7 @@ <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" /> + <PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="OptimizedPriorityQueue" Version="5.0.0" /> <PackageReference Include="PlaylistsNET" Version="1.1.3" /> <PackageReference Include="TMDbLib" Version="1.7.3-alpha" /> From a714008b596b108a44020f61ca384b30263df984 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Wed, 23 Dec 2020 21:00:50 +0100 Subject: [PATCH 0851/1930] Add missing FileStreams --- .../Channels/ChannelManager.cs | 11 ++++++----- .../Library/LiveStreamHelper.cs | 6 +++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index b462d7bdcd..3663e5094b 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -341,7 +341,8 @@ namespace Emby.Server.Implementations.Channels try { using FileStream jsonStream = File.OpenRead(path); - return JsonSerializer.DeserializeAsync<List<MediaSourceInfo>>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); + return JsonSerializer.DeserializeAsync<List<MediaSourceInfo>>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult() + ?? new List<MediaSourceInfo>(); } catch { @@ -810,8 +811,8 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - var jsonString = await File.ReadAllTextAsync(cachePath, cancellationToken); - var cachedResult = JsonSerializer.Deserialize<ChannelItemResult>(jsonString); + await using FileStream jsonStream = File.OpenRead(cachePath); + var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (cachedResult != null) { return null; @@ -833,8 +834,8 @@ namespace Emby.Server.Implementations.Channels { if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { - var jsonString = await File.ReadAllTextAsync(cachePath, cancellationToken); - var cachedResult = JsonSerializer.Deserialize<ChannelItemResult>(jsonString); + await using FileStream jsonStream = File.OpenRead(cachePath); + var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); if (cachedResult != null) { return null; diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index 3ceba0fe94..80729a280c 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Library try { await using FileStream jsonStream = File.OpenRead(cacheFilePath); - await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Found cached media info"); } @@ -83,8 +83,8 @@ namespace Emby.Server.Implementations.Library if (cacheFilePath != null) { Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); - await using FileStream createStream = File.Create(cacheFilePath); - await JsonSerializer.SerializeAsync(createStream, mediaInfo, cancellationToken: cancellationToken).ConfigureAwait(false); + await using FileStream createStream = File.OpenWrite(cacheFilePath); + await JsonSerializer.SerializeAsync(createStream, mediaInfo, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Saved media info to {0}", cacheFilePath); } From 20993412f20dd2fa11d25994f32c645dcdc1aae6 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Thu, 24 Dec 2020 10:18:32 +0100 Subject: [PATCH 0852/1930] Add unstable nuget condition --- .ci/azure-pipelines-package.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 6063851163..0a63b329ba 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -210,6 +210,7 @@ jobs: - task: DotNetCoreCLI@2 displayName: 'Build Unstable Nuget packages' + condition: startsWith(variables['Build.SourceBranch'], 'refs/heads/master') inputs: command: 'custom' projects: | From e835dfb27d4a25e2057047692fd58af439b15acc Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Thu, 24 Dec 2020 10:31:51 +0100 Subject: [PATCH 0853/1930] Use sync string instead of file --- Emby.Server.Implementations/ApplicationHost.cs | 6 +++--- .../Channels/ChannelManager.cs | 5 +++-- .../LiveTv/EmbyTV/ItemDataProvider.cs | 4 ++-- .../ScheduledTasks/ScheduledTaskWorker.cs | 11 +++++++++-- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 99cd3b6cc1..6e360ed852 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -10,6 +10,7 @@ using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Emby.Dlna; @@ -100,7 +101,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Prometheus.DotNetRuntime; -using JsonSerializer = System.Text.Json.JsonSerializer; using OperatingSystem = MediaBrowser.Common.System.OperatingSystem; using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager; @@ -1047,8 +1047,8 @@ namespace Emby.Server.Implementations var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { - using FileStream jsonStream = File.OpenRead(metafile); - var manifest = JsonSerializer.DeserializeAsync<PluginManifest>(jsonStream, jsonOptions).GetAwaiter().GetResult(); + var jsonString = File.ReadAllText(metafile); + var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, jsonOptions); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 3663e5094b..f06ad4436b 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -340,8 +340,8 @@ namespace Emby.Server.Implementations.Channels try { - using FileStream jsonStream = File.OpenRead(path); - return JsonSerializer.DeserializeAsync<List<MediaSourceInfo>>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult() + var jsonString = File.ReadAllText(path); + return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, JsonDefaults.GetOptions()) ?? new List<MediaSourceInfo>(); } catch @@ -368,6 +368,7 @@ namespace Emby.Server.Implementations.Channels } Directory.CreateDirectory(Path.GetDirectoryName(path)); + await using FileStream createStream = File.Create(path); await JsonSerializer.SerializeAsync(createStream, mediaSources, JsonDefaults.GetOptions()).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 1b9abaa78e..bbe9b50dd5 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -44,8 +44,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - using FileStream jsonStream = File.OpenRead(_dataPath); - _items = JsonSerializer.DeserializeAsync<T[]>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); + var jsonString = File.ReadAllText(_dataPath); + _items = JsonSerializer.Deserialize<T[]>(jsonString, JsonDefaults.GetOptions()); return; } catch (Exception ex) diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index a9f4599864..eee7aeea30 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -139,8 +139,15 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - using FileStream jsonStream = File.OpenRead(path); - _lastExecutionResult = JsonSerializer.DeserializeAsync<TaskResult>(jsonStream, JsonDefaults.GetOptions()).GetAwaiter().GetResult(); + var jsonString = File.ReadAllText(path); + if (!string.IsNullOrWhiteSpace(jsonString)) + { + _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, JsonDefaults.GetOptions()); + } + else + { + _logger.LogDebug("Scheduled Task history file {path} is empty. Skipping deserialization.", path); + } } catch (Exception ex) { From 043d04544850bb82972bb7817510984c2ddea75a Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Thu, 24 Dec 2020 11:15:12 +0100 Subject: [PATCH 0854/1930] Put json serializer options in private field --- Emby.Dlna/DlnaManager.cs | 5 +++-- .../ApplicationHost.cs | 4 ++-- .../Channels/ChannelManager.cs | 13 +++++++------ .../Library/LiveStreamHelper.cs | 5 +++-- .../Library/MediaSourceManager.cs | 9 +++++---- .../LiveTv/EmbyTV/EncodedRecorder.cs | 4 ++-- .../LiveTv/EmbyTV/ItemDataProvider.cs | 5 +++-- .../LiveTv/Listings/SchedulesDirect.cs | 19 +++++++++---------- .../Localization/LocalizationManager.cs | 6 ++++-- .../ScheduledTasks/ScheduledTaskWorker.cs | 13 +++++++++---- .../Entities/CollectionFolder.cs | 4 ++-- .../Plugins/AudioDb/AlbumImageProvider.cs | 3 ++- .../Plugins/AudioDb/AlbumProvider.cs | 3 ++- .../Plugins/AudioDb/ArtistImageProvider.cs | 3 ++- .../Plugins/AudioDb/ArtistProvider.cs | 3 ++- .../Plugins/Omdb/OmdbItemProvider.cs | 5 +++-- .../Plugins/Omdb/OmdbProvider.cs | 19 +++++++++---------- 17 files changed, 69 insertions(+), 54 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index df69dd5162..21ba1c7552 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -36,6 +36,7 @@ namespace Emby.Dlna private readonly ILogger<DlnaManager> _logger; private readonly IServerApplicationHost _appHost; private static readonly Assembly _assembly = typeof(DlnaManager).Assembly; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); private readonly Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>> _profiles = new Dictionary<string, Tuple<InternalProfileInfo, DeviceProfile>>(StringComparer.Ordinal); @@ -494,9 +495,9 @@ namespace Emby.Dlna return profile; } - var json = JsonSerializer.Serialize(profile, JsonDefaults.GetOptions()); + var json = JsonSerializer.Serialize(profile, _jsonOptions); - return JsonSerializer.Deserialize<DeviceProfile>(json, options: JsonDefaults.GetOptions()); + return JsonSerializer.Deserialize<DeviceProfile>(json, _jsonOptions); } public string GetServerDescriptionXml(IHeaderDictionary headers, string serverUuId, string serverAddress) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 6e360ed852..115d94b316 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -123,6 +123,7 @@ namespace Emby.Server.Implementations private IMediaEncoder _mediaEncoder; private ISessionManager _sessionManager; private string[] _urlPrefixes; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); /// <summary> /// Gets a value indicating whether this instance can self restart. @@ -1038,7 +1039,6 @@ namespace Emby.Server.Implementations } var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); - var jsonOptions = JsonDefaults.GetOptions(); foreach (var dir in directories) { @@ -1048,7 +1048,7 @@ namespace Emby.Server.Implementations if (File.Exists(metafile)) { var jsonString = File.ReadAllText(metafile); - var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, jsonOptions); + var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, _jsonOptions); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) { diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index f06ad4436b..cf6a87ecfd 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Entities; @@ -25,7 +26,6 @@ using MediaBrowser.Model.Querying; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Episode = MediaBrowser.Controller.Entities.TV.Episode; -using JsonSerializer = System.Text.Json.JsonSerializer; using Movie = MediaBrowser.Controller.Entities.Movies.Movie; using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum; using Season = MediaBrowser.Controller.Entities.TV.Season; @@ -48,6 +48,7 @@ namespace Emby.Server.Implementations.Channels private readonly IProviderManager _providerManager; private readonly IMemoryCache _memoryCache; private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); /// <summary> /// Initializes a new instance of the <see cref="ChannelManager"/> class. @@ -341,7 +342,7 @@ namespace Emby.Server.Implementations.Channels try { var jsonString = File.ReadAllText(path); - return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, JsonDefaults.GetOptions()) + return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, _jsonOptions) ?? new List<MediaSourceInfo>(); } catch @@ -370,7 +371,7 @@ namespace Emby.Server.Implementations.Channels Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream createStream = File.Create(path); - await JsonSerializer.SerializeAsync(createStream, mediaSources, JsonDefaults.GetOptions()).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(createStream, mediaSources, _jsonOptions).ConfigureAwait(false); } /// <inheritdoc /> @@ -813,7 +814,7 @@ namespace Emby.Server.Implementations.Channels if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { await using FileStream jsonStream = File.OpenRead(cachePath); - var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (cachedResult != null) { return null; @@ -836,7 +837,7 @@ namespace Emby.Server.Implementations.Channels if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow) { await using FileStream jsonStream = File.OpenRead(cachePath); - var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (cachedResult != null) { return null; @@ -884,7 +885,7 @@ namespace Emby.Server.Implementations.Channels Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream createStream = File.Create(path); - await JsonSerializer.SerializeAsync(createStream, result, JsonDefaults.GetOptions()).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(createStream, result, _jsonOptions).ConfigureAwait(false); } catch (Exception ex) { diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index 80729a280c..2070df31e4 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -25,6 +25,7 @@ namespace Emby.Server.Implementations.Library private readonly IMediaEncoder _mediaEncoder; private readonly ILogger _logger; private readonly IApplicationPaths _appPaths; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IApplicationPaths appPaths) { @@ -47,7 +48,7 @@ namespace Emby.Server.Implementations.Library try { await using FileStream jsonStream = File.OpenRead(cacheFilePath); - mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Found cached media info"); } @@ -84,7 +85,7 @@ namespace Emby.Server.Implementations.Library { Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); await using FileStream createStream = File.OpenWrite(cacheFilePath); - await JsonSerializer.SerializeAsync(createStream, mediaInfo, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Saved media info to {0}", cacheFilePath); } diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index b3900e4aa1..660ec106bd 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -46,6 +46,7 @@ namespace Emby.Server.Implementations.Library private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase); private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); private IMediaSourceProvider[] _providers; @@ -514,9 +515,9 @@ namespace Emby.Server.Implementations.Library } // TODO: @bond Fix - var json = JsonSerializer.Serialize(mediaSource, JsonDefaults.GetOptions()); + var json = JsonSerializer.Serialize(mediaSource, _jsonOptions); _logger.LogInformation("Live stream opened: " + json); - var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, JsonDefaults.GetOptions()); + var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions); if (!request.UserId.Equals(Guid.Empty)) { @@ -642,7 +643,7 @@ namespace Emby.Server.Implementations.Library try { await using FileStream jsonStream = File.OpenRead(cacheFilePath); - mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Found cached media info"); } @@ -679,7 +680,7 @@ namespace Emby.Server.Implementations.Library { Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); await using FileStream createStream = File.Create(cacheFilePath); - await JsonSerializer.SerializeAsync(createStream, mediaInfo, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false); // _logger.LogDebug("Saved media info to {0}", cacheFilePath); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 9609f28816..a70a72b74f 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly IServerApplicationPaths _appPaths; private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>(); private readonly IServerConfigurationManager _serverConfigurationManager; - + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); private bool _hasExited; private Stream _logFileStream; private string _targetPath; @@ -93,7 +93,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); - var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(mediaSource, JsonDefaults.GetOptions()) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); + var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(mediaSource, _jsonOptions) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); _process = new Process diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index bbe9b50dd5..f16d96a592 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -15,6 +15,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { private readonly string _dataPath; private readonly object _fileDataLock = new object(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); private T[] _items; public ItemDataProvider( @@ -45,7 +46,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { var jsonString = File.ReadAllText(_dataPath); - _items = JsonSerializer.Deserialize<T[]>(jsonString, JsonDefaults.GetOptions()); + _items = JsonSerializer.Deserialize<T[]>(jsonString, _jsonOptions); return; } catch (Exception ex) @@ -61,7 +62,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { Directory.CreateDirectory(Path.GetDirectoryName(_dataPath)); using FileStream stream = File.OpenWrite(_dataPath); - JsonSerializer.SerializeAsync(stream, _items, JsonDefaults.GetOptions()); + JsonSerializer.SerializeAsync(stream, _items, _jsonOptions); } public IReadOnlyList<T> GetAll() diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 198d196c23..2b8ccfb628 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -36,6 +36,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>(); private DateTime _lastErrorResponse; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public SchedulesDirect( ILogger<SchedulesDirect> logger, @@ -102,9 +103,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings } }; - var jsonOptions = JsonDefaults.GetOptions(); - - var requestString = JsonSerializer.Serialize(requestList, jsonOptions); + var requestString = JsonSerializer.Serialize(requestList, _jsonOptions); _logger.LogDebug("Request string for schedules is: {RequestString}", requestString); using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); @@ -112,7 +111,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings options.Headers.TryAddWithoutValidation("token", token); using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false); await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var dailySchedules = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Day>>(responseStream, jsonOptions).ConfigureAwait(false); + var dailySchedules = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Day>>(responseStream, _jsonOptions).ConfigureAwait(false); _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); @@ -123,7 +122,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false); await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var programDetails = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream, jsonOptions).ConfigureAwait(false); + var programDetails = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream, _jsonOptions).ConfigureAwait(false); var programDict = programDetails.ToDictionary(p => p.programID, y => y); var programIdsWithImages = @@ -479,7 +478,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings { using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false); await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - return await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ShowImages>>(response, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + return await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ShowImages>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { @@ -508,7 +507,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false); await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Headends>>(response, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Headends>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false); if (root != null) { @@ -649,7 +648,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Token>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Token>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (string.Equals(root.message, "OK", StringComparison.Ordinal)) { _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token); @@ -705,7 +704,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings httpResponse.EnsureSuccessStatusCode(); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var response = httpResponse.Content; - var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Lineups>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Lineups>(stream, _jsonOptions).ConfigureAwait(false); return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase)); } @@ -777,7 +776,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false); await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Channel>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); + var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Channel>(stream, _jsonOptions).ConfigureAwait(false); _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count); _logger.LogInformation("Mapping Stations to Channel"); diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 2d6fb252d2..3f9e221066 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -36,6 +36,8 @@ namespace Emby.Server.Implementations.Localization private List<CultureDto> _cultures; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + /// <summary> /// Initializes a new instance of the <see cref="LocalizationManager" /> class. /// </summary> @@ -180,7 +182,7 @@ namespace Emby.Server.Implementations.Localization { StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json")); - return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), JsonDefaults.GetOptions()); + return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions); } /// <inheritdoc /> @@ -345,7 +347,7 @@ namespace Emby.Server.Implementations.Localization // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain if (stream != null) { - var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); + var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false); foreach (var key in dict.Keys) { diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index eee7aeea30..3dca05bf98 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -65,6 +65,11 @@ namespace Emby.Server.Implementations.ScheduledTasks /// </summary> private string _id; + /// <summary> + /// The options for the json Serializer. + /// </summary> + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + /// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> @@ -142,7 +147,7 @@ namespace Emby.Server.Implementations.ScheduledTasks var jsonString = File.ReadAllText(path); if (!string.IsNullOrWhiteSpace(jsonString)) { - _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, JsonDefaults.GetOptions()); + _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, _jsonOptions); } else { @@ -172,7 +177,7 @@ namespace Emby.Server.Implementations.ScheduledTasks lock (_lastExecutionResultSyncLock) { using FileStream createStream = File.OpenWrite(path); - JsonSerializer.SerializeAsync(createStream, value, JsonDefaults.GetOptions()); + JsonSerializer.SerializeAsync(createStream, value, _jsonOptions); } } } @@ -536,7 +541,7 @@ namespace Emby.Server.Implementations.ScheduledTasks if (File.Exists(path)) { var jsonString = File.ReadAllText(path); - list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(jsonString, JsonDefaults.GetOptions()); + list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(jsonString, _jsonOptions); } // Return defaults if file doesn't exist. @@ -573,7 +578,7 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(Path.GetDirectoryName(path)); using FileStream stream = File.OpenWrite(path); - JsonSerializer.SerializeAsync(stream, triggers, JsonDefaults.GetOptions()); + JsonSerializer.SerializeAsync(stream, triggers, _jsonOptions); } /// <summary> diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index b960278b85..c3b6af76ea 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -26,6 +26,7 @@ namespace MediaBrowser.Controller.Entities /// </summary> public class CollectionFolder : Folder, ICollectionFolder { + private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public static IXmlSerializer XmlSerializer { get; set; } public static IServerApplicationHost ApplicationHost { get; set; } @@ -122,8 +123,7 @@ namespace MediaBrowser.Controller.Entities { LibraryOptions[path] = options; - var jsonOptions = JsonDefaults.GetOptions(); - var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.Serialize(options, jsonOptions), jsonOptions); + var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.Serialize(options, _jsonOptions), _jsonOptions); foreach (var mediaPath in clone.PathInfos) { if (!string.IsNullOrEmpty(mediaPath.Path)) diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index a5aeba7d2d..cd9e477432 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -22,6 +22,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { @@ -58,7 +59,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbAlbumProvider.GetAlbumInfoPath(_config.ApplicationPaths, id); await using FileStream jsonStream = File.OpenRead(path); - var obj = await JsonSerializer.DeserializeAsync<AudioDbAlbumProvider.RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var obj = await JsonSerializer.DeserializeAsync<AudioDbAlbumProvider.RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 9a61abc1ac..f463a3566b 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -29,6 +29,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public static AudioDbAlbumProvider Current; @@ -65,7 +66,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetAlbumInfoPath(_config.ApplicationPaths, id); await using FileStream jsonStream = File.OpenRead(path); - var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (obj != null && obj.album != null && obj.album.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index 639bbe8595..36700d1917 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -22,6 +22,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public AudioDbArtistImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { @@ -60,7 +61,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = AudioDbArtistProvider.GetArtistInfoPath(_config.ApplicationPaths, id); await using FileStream jsonStream = File.OpenRead(path); - var obj = await JsonSerializer.DeserializeAsync<AudioDbArtistProvider.RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var obj = await JsonSerializer.DeserializeAsync<AudioDbArtistProvider.RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 71efd194e3..7a15adb8e8 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -31,6 +31,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory) { @@ -66,7 +67,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb var path = GetArtistInfoPath(_config.ApplicationPaths, id); await using FileStream jsonStream = File.OpenRead(path); - var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var obj = await JsonSerializer.DeserializeAsync<RootObject>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (obj != null && obj.artists != null && obj.artists.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 7e9ef974e2..3ef404b535 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -32,6 +32,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IFileSystem _fileSystem; private readonly IServerConfigurationManager _configurationManager; private readonly IApplicationHost _appHost; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public OmdbItemProvider( IApplicationHost appHost, @@ -136,7 +137,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb if (isSearch) { - var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (searchResultList != null && searchResultList.Search != null) { resultList.AddRange(searchResultList.Search); @@ -144,7 +145,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } else { - var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false); + var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase)) { resultList.Add(result); diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index fa75e4ec49..3c21629990 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -28,6 +28,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IHttpClientFactory _httpClientFactory; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IApplicationHost _appHost; + private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager) { @@ -219,7 +220,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - var result = JsonSerializer.Deserialize<RootObject>(resultString, JsonDefaults.GetOptions()); + var result = JsonSerializer.Deserialize<RootObject>(resultString, _jsonOptions); return result; } @@ -238,7 +239,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb } } - var result = JsonSerializer.Deserialize<SeasonRootObject>(resultString, JsonDefaults.GetOptions()); + var result = JsonSerializer.Deserialize<SeasonRootObject>(resultString, _jsonOptions); return result; } @@ -296,11 +297,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb "i={0}&plot=short&tomatoes=true&r=json", imdbParam)); - var jsonOptions = JsonDefaults.GetOptions(); - var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); + var rootObject = await GetDeserializedOmdbResponse<RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.OpenWrite(path); - await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); return path; } @@ -334,23 +334,22 @@ namespace MediaBrowser.Providers.Plugins.Omdb imdbParam, seasonId)); - var jsonOptions = JsonDefaults.GetOptions(); - var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, jsonOptions, cancellationToken).ConfigureAwait(false); + var rootObject = await GetDeserializedOmdbResponse<SeasonRootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(path)); await using FileStream jsonFileStream = File.OpenWrite(path); - await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, jsonOptions, cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); return path; } - public static async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, JsonSerializerOptions jsonOptions, CancellationToken cancellationToken) + public static async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken) { using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // OMDb is sending "N/A" for no empty number fields content = content.Replace("\"N/A\"", "\"\"", StringComparison.InvariantCulture); - return JsonSerializer.Deserialize<T>(content, jsonOptions); + return JsonSerializer.Deserialize<T>(content, _jsonOptions); } public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken) From bc6ec08322a6d9111849dd4661bdda3746347835 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 24 Dec 2020 19:41:02 +0800 Subject: [PATCH 0855/1930] avoid transcoding to 3ch audio for HLS streaming --- .../MediaEncoding/EncodingHelper.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 6667c1c3bc..17201551a0 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1722,6 +1722,16 @@ namespace MediaBrowser.Controller.MediaEncoding : transcoderChannelLimit.Value; } + // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout). + // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices + if (isTranscodingAudio + && resultChannels.HasValue + && resultChannels.Value > 2 + && resultChannels.Value < 6) + { + resultChannels = 2; + } + return resultChannels; } From ae1187042af7bc9a144d184a31017b6bd32eefcd Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Thu, 24 Dec 2020 20:06:55 +0800 Subject: [PATCH 0856/1930] also avoid 7ch transcoding --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 17201551a0..29978a56c6 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1726,8 +1726,7 @@ namespace MediaBrowser.Controller.MediaEncoding // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices if (isTranscodingAudio && resultChannels.HasValue - && resultChannels.Value > 2 - && resultChannels.Value < 6) + && (resultChannels.Value > 2 && resultChannels.Value < 6 || resultChannels.Value == 7)) { resultChannels = 2; } From c8a95e0926c3152af91ba07fd74d23a2ee76baf9 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 24 Dec 2020 10:05:06 -0700 Subject: [PATCH 0857/1930] Fix null reference when logging --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 59c9810009..431cf0bafa 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1033,9 +1033,9 @@ namespace MediaBrowser.Model.Dlna { _logger.LogInformation( "Profile: {0}, No video direct play profiles found for {1} with codec {2}", - profile.Name ?? "Unknown Profile", - mediaSource.Path ?? "Unknown path", - videoStream.Codec ?? "Unknown codec"); + profile?.Name ?? "Unknown Profile", + mediaSource?.Path ?? "Unknown path", + videoStream?.Codec ?? "Unknown codec"); return (null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles)); } From 6ddbe8420f6bc61b2561c20def326fa1b4291c5e Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 24 Dec 2020 08:10:30 -0700 Subject: [PATCH 0858/1930] Add tests for special Omdb json --- .../JsonOmdbNotAvailableConverterFactory.cs | 36 +++++++++++++++++ .../JsonOmdbNotAvailableStringConverter.cs | 33 +++++++++++++++ .../JsonOmdbNotAvailableStructConverter.cs | 35 ++++++++++++++++ .../Plugins/Omdb/OmdbProvider.cs | 40 +++++++++++++++++-- .../Jellyfin.Common.Tests.csproj | 1 + .../Json/JsonOmdbConverterTests.cs | 21 ++++++++++ 6 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs create mode 100644 MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs create mode 100644 MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs new file mode 100644 index 0000000000..5994ce9226 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs @@ -0,0 +1,36 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Json Omdb converter factory. + /// </summary> + /// <remarks> + /// Remove when Omdb is moved to plugin. + /// </remarks> + public class JsonOmdbNotAvailableConverterFactory : JsonConverterFactory + { + /// <inheritdoc /> + public override bool CanConvert(Type typeToConvert) + { + return (typeToConvert.IsGenericType + && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>) + && typeToConvert.GenericTypeArguments[0].IsValueType) + || typeToConvert == typeof(string); + } + + /// <inheritdoc /> + public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (typeToConvert == typeof(string)) + { + return (JsonConverter)Activator.CreateInstance(typeof(JsonOmdbNotAvailableStringConverter)); + } + + var structType = typeToConvert.GenericTypeArguments[0]; + return (JsonConverter)Activator.CreateInstance(typeof(JsonOmdbNotAvailableStructConverter<>).MakeGenericType(structType)); + } + } +} diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs new file mode 100644 index 0000000000..2b343a5059 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a string <c>N/A</c> to <c>string.Empty</c>. + /// </summary> + public class JsonOmdbNotAvailableStringConverter : JsonConverter<string> + { + /// <inheritdoc /> + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var str = reader.GetString(); + if (str != null && str.Equals("N/A", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + } + + return JsonSerializer.Deserialize<string>(ref reader, options); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(value, options); + } + } +} diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs new file mode 100644 index 0000000000..b9e67ce2de --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs @@ -0,0 +1,35 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a string <c>N/A</c> to <c>string.Empty</c>. + /// </summary> + /// <typeparam name="T">The resulting type.</typeparam> + public class JsonOmdbNotAvailableStructConverter<T> : JsonConverter<T?> + where T : struct + { + /// <inheritdoc /> + public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var str = reader.GetString(); + if (str != null && str.Equals("N/A", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + } + + return JsonSerializer.Deserialize<T>(ref reader, options); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) + { + JsonSerializer.Serialize(value, options); + } + } +} diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 3c21629990..1ebd1b13a3 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -8,10 +8,12 @@ using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Json; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -467,74 +469,104 @@ namespace MediaBrowser.Providers.Plugins.Omdb return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase); } - internal class SeasonRootObject + public class SeasonRootObject { + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Title { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string seriesID { get; set; } - public int Season { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + public int? Season { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public int? totalSeasons { get; set; } public RootObject[] Episodes { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Response { get; set; } } - internal class RootObject + public class RootObject { + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Title { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Year { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Rated { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Released { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Runtime { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Genre { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Director { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Writer { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Actors { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Plot { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Language { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Country { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Awards { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Poster { get; set; } public List<OmdbRating> Ratings { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Metascore { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string imdbRating { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string imdbVotes { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string imdbID { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Type { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string DVD { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string BoxOffice { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Production { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Website { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] public string Response { get; set; } - public int Episode { get; set; } + [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + public int? Episode { get; set; } public float? GetRottenTomatoScore() { diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index af4684f562..91b34546f3 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -29,6 +29,7 @@ <ItemGroup> <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" /> + <ProjectReference Include="..\..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" /> </ItemGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs new file mode 100644 index 0000000000..90537dc1ff --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using MediaBrowser.Common.Json; +using MediaBrowser.Providers.Plugins.Omdb; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public static class JsonOmdbConverterTests + { + [Fact] + public static void Deserialize_Omdb_Response_Not_Available_Success() + { + const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}"; + var seasonRootObject = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, JsonDefaults.GetOptions()); + Assert.NotNull(seasonRootObject); + Assert.Null(seasonRootObject?.Awards); + Assert.Null(seasonRootObject?.Episode); + Assert.Null(seasonRootObject?.Metascore); + } + } +} From fc212e5e5f698482abbf19912787cd2691bae981 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 24 Dec 2020 08:16:50 -0700 Subject: [PATCH 0859/1930] Remove JsonOmdbNotAvailableConverterFactory --- .../JsonOmdbNotAvailableConverterFactory.cs | 36 ----------- .../Plugins/Omdb/OmdbProvider.cs | 60 +++++++++---------- 2 files changed, 30 insertions(+), 66 deletions(-) delete mode 100644 MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs deleted file mode 100644 index 5994ce9226..0000000000 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableConverterFactory.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace MediaBrowser.Common.Json.Converters -{ - /// <summary> - /// Json Omdb converter factory. - /// </summary> - /// <remarks> - /// Remove when Omdb is moved to plugin. - /// </remarks> - public class JsonOmdbNotAvailableConverterFactory : JsonConverterFactory - { - /// <inheritdoc /> - public override bool CanConvert(Type typeToConvert) - { - return (typeToConvert.IsGenericType - && typeToConvert.GetGenericTypeDefinition() == typeof(Nullable<>) - && typeToConvert.GenericTypeArguments[0].IsValueType) - || typeToConvert == typeof(string); - } - - /// <inheritdoc /> - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) - { - if (typeToConvert == typeof(string)) - { - return (JsonConverter)Activator.CreateInstance(typeof(JsonOmdbNotAvailableStringConverter)); - } - - var structType = typeToConvert.GenericTypeArguments[0]; - return (JsonConverter)Activator.CreateInstance(typeof(JsonOmdbNotAvailableStructConverter<>).MakeGenericType(structType)); - } - } -} diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 1ebd1b13a3..e700e6969b 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -471,101 +471,101 @@ namespace MediaBrowser.Providers.Plugins.Omdb public class SeasonRootObject { - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Title { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string seriesID { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? Season { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? totalSeasons { get; set; } public RootObject[] Episodes { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Response { get; set; } } public class RootObject { - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Title { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Year { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Rated { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Released { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Runtime { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Genre { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Director { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Writer { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Actors { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Plot { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Language { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Country { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Awards { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Poster { get; set; } public List<OmdbRating> Ratings { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Metascore { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbRating { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbVotes { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbID { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Type { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string DVD { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string BoxOffice { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Production { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Website { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Response { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableConverterFactory))] + [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? Episode { get; set; } public float? GetRottenTomatoScore() From e09dd5aa87a61c38e3995d351efd8419555939f6 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Thu, 24 Dec 2020 08:26:26 -0700 Subject: [PATCH 0860/1930] Add targeted tests --- .../Json/JsonOmdbConverterTests.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index 90537dc1ff..aae95e7314 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -1,5 +1,7 @@ using System.Text.Json; +using System.Text.Json.Serialization; using MediaBrowser.Common.Json; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Providers.Plugins.Omdb; using Xunit; @@ -17,5 +19,39 @@ namespace Jellyfin.Common.Tests.Json Assert.Null(seasonRootObject?.Episode); Assert.Null(seasonRootObject?.Metascore); } + + [Fact] + public static void Deserialize_Not_Available_Int_Success() + { + const string Input = "\"N/A\""; + var options = new JsonSerializerOptions + { + NumberHandling = JsonNumberHandling.AllowReadingFromString, + Converters = + { + new JsonOmdbNotAvailableStructConverter<int>() + } + }; + + var result = JsonSerializer.Deserialize<int?>(Input, options); + Assert.Null(result); + } + + [Fact] + public static void Deserialize_Not_Available_String_Success() + { + const string Input = "\"N/A\""; + var options = new JsonSerializerOptions + { + Converters = + { + new JsonOmdbNotAvailableStringConverter() + } + }; + + options.Converters.Add(new JsonOmdbNotAvailableStringConverter()); + var result = JsonSerializer.Deserialize<string>(Input, options); + Assert.Null(result); + } } } From af62ab490c1afc4702db88e5f004aa2fb5930b33 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Fri, 25 Dec 2020 15:21:57 +0100 Subject: [PATCH 0861/1930] Update tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj Co-authored-by: Bond-009 <bond.009@outlook.com> --- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 91b34546f3..19c5612c06 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -29,7 +29,7 @@ <ItemGroup> <ProjectReference Include="../../MediaBrowser.Common/MediaBrowser.Common.csproj" /> - <ProjectReference Include="..\..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" /> + <ProjectReference Include="../../MediaBrowser.Providers/MediaBrowser.Providers.csproj" /> </ItemGroup> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> From 4839c2006bfa01e55e447e474234501a7e2496a2 Mon Sep 17 00:00:00 2001 From: nyanmisaka <nst799610810@gmail.com> Date: Sat, 26 Dec 2020 01:24:25 +0800 Subject: [PATCH 0862/1930] fix boxes in library name backdrop for CJK character --- Jellyfin.Drawing.Skia/StripCollageBuilder.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs index 0e94f87f6a..e9f9aad57d 100644 --- a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs +++ b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text.RegularExpressions; using SkiaSharp; namespace Jellyfin.Drawing.Skia @@ -118,6 +119,16 @@ namespace Jellyfin.Drawing.Skia }; canvas.DrawRect(0, 0, width, height, paintColor); + var typeFace = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright); + + // use the system fallback to find a typeface for the given CJK character + var nonCjkPattern = @"[^\p{IsCJKUnifiedIdeographs}\p{IsCJKUnifiedIdeographsExtensionA}\p{IsKatakana}\p{IsHiragana}\p{IsHangulSyllables}\p{IsHangulJamo}]"; + var filteredName = Regex.Replace(libraryName ?? string.Empty, nonCjkPattern, string.Empty); + if (!string.IsNullOrEmpty(filteredName)) + { + typeFace = SKFontManager.Default.MatchCharacter(null, SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright, null, filteredName[0]); + } + // draw library name var textPaint = new SKPaint { @@ -125,7 +136,7 @@ namespace Jellyfin.Drawing.Skia Style = SKPaintStyle.Fill, TextSize = 112, TextAlign = SKTextAlign.Center, - Typeface = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright), + Typeface = typeFace, IsAntialias = true }; From aacda01ca5a1197a1b6e637488639dae6455d6d8 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Fri, 25 Dec 2020 19:21:58 +0100 Subject: [PATCH 0863/1930] Add more tests --- .../JsonOmdbNotAvailableStringConverter.cs | 2 + .../Json/JsonOmdbConverterTests.cs | 86 ++++++++++++++----- 2 files changed, 66 insertions(+), 22 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs index 2b343a5059..4fec2ea3fd 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs @@ -19,6 +19,8 @@ namespace MediaBrowser.Common.Json.Converters { return null; } + + return str; } return JsonSerializer.Deserialize<string>(ref reader, options); diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index aae95e7314..e1436a648e 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -7,10 +7,20 @@ using Xunit; namespace Jellyfin.Common.Tests.Json { - public static class JsonOmdbConverterTests + public class JsonOmdbConverterTests { + private readonly JsonSerializerOptions _options; + + public JsonOmdbConverterTests() + { + _options = new JsonSerializerOptions(); + _options.Converters.Add(new JsonOmdbNotAvailableStringConverter()); + _options.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); + _options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + } + [Fact] - public static void Deserialize_Omdb_Response_Not_Available_Success() + public void Deserialize_Omdb_Response_Not_Available_Success() { const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}"; var seasonRootObject = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, JsonDefaults.GetOptions()); @@ -21,36 +31,68 @@ namespace Jellyfin.Common.Tests.Json } [Fact] - public static void Deserialize_Not_Available_Int_Success() + public void Deserialize_Not_Available_Int_Success() { const string Input = "\"N/A\""; - var options = new JsonSerializerOptions - { - NumberHandling = JsonNumberHandling.AllowReadingFromString, - Converters = - { - new JsonOmdbNotAvailableStructConverter<int>() - } - }; - var result = JsonSerializer.Deserialize<int?>(Input, options); + var result = JsonSerializer.Deserialize<int?>(Input, _options); Assert.Null(result); } [Fact] - public static void Deserialize_Not_Available_String_Success() + public void Deserialize_Not_Available_String_Success() { const string Input = "\"N/A\""; - var options = new JsonSerializerOptions - { - Converters = - { - new JsonOmdbNotAvailableStringConverter() - } - }; - options.Converters.Add(new JsonOmdbNotAvailableStringConverter()); - var result = JsonSerializer.Deserialize<string>(Input, options); + var result = JsonSerializer.Deserialize<string>(Input, _options); + Assert.Null(result); + } + + [Fact] + public void Deserialize_Normal_String_Success() + { + const string Expected = "Jellyfin"; + const string Input = "\"Jellyfin\""; + + var result = JsonSerializer.Deserialize<string>(Input, _options); + Assert.Equal(Expected, result); + } + + [Fact] + public void Deserialize_Null_Success() + { + const string Input = "null"; + + var result = JsonSerializer.Deserialize<string>(Input, _options); + Assert.Null(result); + } + + [Fact] + public void Deserialize_Number_Success() + { + const int Number = 8; + const string Input = "8"; + + var result = JsonSerializer.Deserialize<int>(Input, _options); + Assert.Equal(Number, result); + } + + [Fact] + public void Deserialize_Quoted_Number_Success() + { + const int Number = 8; + const string Input = "\"8\""; + + var result = JsonSerializer.Deserialize<int>(Input, _options); + Assert.Equal(Number, result); + } + + [Fact] + public void Deserialize_NA_Number_Success() + { + const string Input = "\"N/A\""; + + var result = JsonSerializer.Deserialize<int?>(Input, _options); Assert.Null(result); } } From 470f40442cd6ecbcfe81888804bf4e6a04846aec Mon Sep 17 00:00:00 2001 From: Nyanmisaka <nst799610810@gmail.com> Date: Sat, 26 Dec 2020 02:28:38 +0800 Subject: [PATCH 0864/1930] not apply to progressive playback --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 29978a56c6..efab87a38e 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1725,6 +1725,7 @@ namespace MediaBrowser.Controller.MediaEncoding // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout). // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices if (isTranscodingAudio + && state.TranscodingType != TranscodingJobType.Progressive && resultChannels.HasValue && (resultChannels.Value > 2 && resultChannels.Value < 6 || resultChannels.Value == 7)) { From e0499f87690bca88c878b2115ba9e2dbb00f0ad4 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Fri, 25 Dec 2020 19:37:38 +0100 Subject: [PATCH 0865/1930] Remove attributes --- .../Plugins/Omdb/OmdbItemProvider.cs | 7 +++- .../Plugins/Omdb/OmdbProvider.cs | 38 +++---------------- .../Json/JsonOmdbConverterTests.cs | 2 +- 3 files changed, 13 insertions(+), 34 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 3ef404b535..71d5510632 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Json; +using MediaBrowser.Common.Json.Converters; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -32,7 +33,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IFileSystem _fileSystem; private readonly IServerConfigurationManager _configurationManager; private readonly IApplicationHost _appHost; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions; public OmdbItemProvider( IApplicationHost appHost, @@ -46,6 +47,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb _fileSystem = fileSystem; _configurationManager = configurationManager; _appHost = appHost; + + _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); } public string Name => "The Open Movie Database"; diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index e700e6969b..a177ae30a9 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb private readonly IHttpClientFactory _httpClientFactory; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IApplicationHost _appHost; - private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions; public OmdbProvider(IHttpClientFactory httpClientFactory, IFileSystem fileSystem, IApplicationHost appHost, IServerConfigurationManager configurationManager) { @@ -38,6 +38,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb _fileSystem = fileSystem; _configurationManager = configurationManager; _appHost = appHost; + + _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); } public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken) @@ -344,7 +348,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb return path; } - public static async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken) + public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken) { using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); @@ -471,101 +475,71 @@ namespace MediaBrowser.Providers.Plugins.Omdb public class SeasonRootObject { - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Title { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string seriesID { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? Season { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? totalSeasons { get; set; } public RootObject[] Episodes { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Response { get; set; } } public class RootObject { - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Title { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Year { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Rated { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Released { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Runtime { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Genre { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Director { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Writer { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Actors { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Plot { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Language { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Country { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Awards { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Poster { get; set; } public List<OmdbRating> Ratings { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Metascore { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbRating { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbVotes { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string imdbID { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Type { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string DVD { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string BoxOffice { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Production { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Website { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStringConverter))] public string Response { get; set; } - [JsonConverter(typeof(JsonOmdbNotAvailableStructConverter<int>))] public int? Episode { get; set; } public float? GetRottenTomatoScore() diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index e1436a648e..06a4855bfd 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -23,7 +23,7 @@ namespace Jellyfin.Common.Tests.Json public void Deserialize_Omdb_Response_Not_Available_Success() { const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}"; - var seasonRootObject = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, JsonDefaults.GetOptions()); + var seasonRootObject = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, _options); Assert.NotNull(seasonRootObject); Assert.Null(seasonRootObject?.Awards); Assert.Null(seasonRootObject?.Episode); From 41324300ec67c16e19d98b9d568debdaeb72a138 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Milinkovi=C4=87?= <mm49900@gmail.com> Date: Fri, 25 Dec 2020 13:47:11 +0000 Subject: [PATCH 0866/1930] Translated using Weblate (Croatian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hr/ --- Emby.Server.Implementations/Localization/Core/hr.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index 9be91b7240..9eb80b83ba 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -115,5 +115,8 @@ "TasksChannelsCategory": "Internet kanali", "TasksLibraryCategory": "Biblioteka", "TaskCleanActivityLogDescription": "Briše zapise dnevnika aktivnosti starije od navedenog vremena.", - "TaskCleanActivityLog": "Očisti dnevnik aktivnosti" + "TaskCleanActivityLog": "Očisti dnevnik aktivnosti", + "Undefined": "Nedefinirano", + "Forced": "Forsirani", + "Default": "Zadano" } From 108d2da0aad9978620c0ee1b1e97d15221240091 Mon Sep 17 00:00:00 2001 From: mahi160 <omarsifat288@gmail.com> Date: Fri, 25 Dec 2020 09:24:18 +0000 Subject: [PATCH 0867/1930] Translated using Weblate (Bengali) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bn/ --- Emby.Server.Implementations/Localization/Core/bn.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json index 5667bf337e..84c8a99f7a 100644 --- a/Emby.Server.Implementations/Localization/Core/bn.json +++ b/Emby.Server.Implementations/Localization/Core/bn.json @@ -112,5 +112,7 @@ "TaskRefreshPeople": "পিপল রিফ্রেশ করুন", "TaskCleanLogsDescription": "{0} দিনের বেশী পুরানো লগ ফাইলগুলি মুছে ফেলুন।", "TaskCleanLogs": "লগ ডিরেক্টরি ক্লিন করুন", - "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।" + "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।", + "Undefined": "অসঙ্গায়িত", + "Forced": "জোরপূর্বক" } From f73bb92ce3a86a024cd72a59bbc461707687a4c7 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Sat, 26 Dec 2020 20:00:54 +0100 Subject: [PATCH 0868/1930] Remove manual N/A removal and write directly to stream --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 8 +++----- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 2 -- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index a70a72b74f..2545ffdd2e 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -64,7 +64,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _logger.LogInformation("Recording completed to file {0}", targetFile); } - private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) + private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { _targetPath = targetFile; Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); @@ -93,8 +93,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); - var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(mediaSource, _jsonOptions) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); - _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length); + await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false); + await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken); _process = new Process { @@ -113,8 +113,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _ = StartStreamingLog(_process.StandardError.BaseStream, _logFileStream); _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); - - return _taskCompletionSource.Task; } private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index a177ae30a9..9f3fdd60b1 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -353,8 +353,6 @@ namespace MediaBrowser.Providers.Plugins.Omdb using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // OMDb is sending "N/A" for no empty number fields - content = content.Replace("\"N/A\"", "\"\"", StringComparison.InvariantCulture); return JsonSerializer.Deserialize<T>(content, _jsonOptions); } From 21fd124bcaabcc1c01d58757ed54b5fe09273c36 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Sun, 27 Dec 2020 11:15:46 +0100 Subject: [PATCH 0869/1930] Code revie --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 2 +- .../ScheduledTasks/ScheduledTaskWorker.cs | 6 +++--- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 2545ffdd2e..78a82118ed 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -94,7 +94,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false); - await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken); + await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false); _process = new Process { diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 3dca05bf98..0bb627192f 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -151,7 +151,7 @@ namespace Emby.Server.Implementations.ScheduledTasks } else { - _logger.LogDebug("Scheduled Task history file {path} is empty. Skipping deserialization.", path); + _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path); } } catch (Exception ex) @@ -577,8 +577,8 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(Path.GetDirectoryName(path)); - using FileStream stream = File.OpenWrite(path); - JsonSerializer.SerializeAsync(stream, triggers, _jsonOptions); + var json = JsonSerializer.Serialize(triggers, _jsonOptions); + File.WriteAllText(path, json); } /// <summary> diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 9f3fdd60b1..25371e27ea 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -351,9 +351,9 @@ namespace MediaBrowser.Providers.Plugins.Omdb public async Task<T> GetDeserializedOmdbResponse<T>(HttpClient httpClient, string url, CancellationToken cancellationToken) { using var response = await GetOmdbResponse(httpClient, url, cancellationToken).ConfigureAwait(false); - var content = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + await using Stream content = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - return JsonSerializer.Deserialize<T>(content, _jsonOptions); + return await JsonSerializer.DeserializeAsync<T>(content, _jsonOptions, cancellationToken).ConfigureAwait(false); } public static Task<HttpResponseMessage> GetOmdbResponse(HttpClient httpClient, string url, CancellationToken cancellationToken) From d96c8d7efdeced56b8d8ed716cd38689d4c86f38 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Sun, 27 Dec 2020 15:57:27 +0000 Subject: [PATCH 0870/1930] Remove todo --- Jellyfin.Networking/Manager/NetworkManager.cs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 43f2f7add6..2585355412 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -913,15 +913,6 @@ namespace Jellyfin.Networking.Manager { string[] lanAddresses = config.LocalNetworkAddresses; - // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334 - - if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1) - { - lanAddresses = lanAddresses[0].Split(','); - } - - // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334 - // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. if (config.IgnoreVirtualInterfaces) { From 926c70f9f7181ba86a367ca078302486501ff995 Mon Sep 17 00:00:00 2001 From: WWWesten <wwwesten@gmail.com> Date: Sun, 27 Dec 2020 11:57:08 +0000 Subject: [PATCH 0871/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- .../Localization/Core/kk.json | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index 47c0879be4..7ce9822b6d 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -108,5 +108,15 @@ "TasksLibraryCategory": "Tasyǵyshhana", "TasksMaintenanceCategory": "Qyzmet kórsetý", "Undefined": "Anyqtalmady", - "Forced": "Májbúrli" + "Forced": "Májbúrli", + "TaskDownloadMissingSubtitlesDescription": "Metaderekter teńshelimi negіzіnde joq sýbtıtrlerdі Internetten іzdeıdі.", + "TaskRefreshChannelsDescription": "Internet-arnalar málimetterin jańartady.", + "TaskCleanTranscodeDescription": "Bіr kúnnen asqan qaıta kodtaý faıldaryn joıady.", + "TaskUpdatePluginsDescription": "Avtomatty túrde jańartýǵa teńshelgen plagınder úshin jańartýlardy júktep alady jáne ornatady.", + "TaskRefreshPeopleDescription": "Tasyǵyshhanadaǵy aktórler men rejısórler metaderekterіn jańartady.", + "TaskCleanLogsDescription": "{0} kúnnen asqan jurnal faıldaryn joıady.", + "TaskRefreshLibraryDescription": "Tasyǵyshhanadaǵy jańa faıldardy skanerleıdі jáne metaderekterdі jańartady.", + "TaskRefreshChapterImagesDescription": "Sahnalarǵa bólіngen beıneler úshіn nobaılar jasaıdy.", + "TaskCleanCacheDescription": "Júıede qajet emes keshtelgen faıldardy joıady.", + "TaskCleanActivityLogDescription": "Áreketter jurnalyndaǵy teńshelgen jasynan asqan jazbalaly joıady." } From 48d8536d2f920e768ea71c8005cd934a87805f05 Mon Sep 17 00:00:00 2001 From: MrTimscampi <julien.machiels@protonmail.com> Date: Mon, 28 Dec 2020 09:19:08 +0100 Subject: [PATCH 0872/1930] Enable TMDB and OMDB by default --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 0dbd51bdc1..7013cb300e 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -49,8 +49,6 @@ namespace MediaBrowser.Model.Configuration new MetadataOptions { ItemType = "Series", - DisabledMetadataFetchers = new[] { "TheMovieDb" }, - DisabledImageFetchers = new[] { "TheMovieDb" } }, new MetadataOptions { @@ -69,13 +67,10 @@ namespace MediaBrowser.Model.Configuration new MetadataOptions { ItemType = "Season", - DisabledMetadataFetchers = new[] { "TheMovieDb" }, }, new MetadataOptions { ItemType = "Episode", - DisabledMetadataFetchers = new[] { "The Open Movie Database", "TheMovieDb" }, - DisabledImageFetchers = new[] { "The Open Movie Database", "TheMovieDb" } } }; } From bad516d4739202b2c81ed95b33e48f0f16857874 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Mon, 28 Dec 2020 15:32:50 +0100 Subject: [PATCH 0873/1930] Disable broken rule --- jellyfin.ruleset | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 45ab725eb2..371f02566b 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -10,6 +10,8 @@ <!-- disable warning SA1009: Closing parenthesis should be followed by a space. --> <Rule Id="SA1009" Action="None" /> + <!-- disable warning SA1011: Closing square bracket should be followed by a space. --> + <Rule Id="SA1011" Action="None" /> <!-- disable warning SA1101: Prefix local calls with 'this.' --> <Rule Id="SA1101" Action="None" /> <!-- disable warning SA1108: Block statements should not contain embedded comments --> From d0382db37df977d284a440f408ae78798e9fba02 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Mon, 28 Dec 2020 15:33:15 +0100 Subject: [PATCH 0874/1930] Minor improvements to ass parser --- MediaBrowser.MediaEncoding/Subtitles/AssParser.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs index 86b87fddd8..e0b7914fbe 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles using (var reader = new StreamReader(stream)) { string line; - while (reader.ReadLine() != "[Events]") + while (!string.Equals(reader.ReadLine(), "[Events]", StringComparison.Ordinal)) { } @@ -46,12 +46,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles var subEvent = new SubtitleTrackEvent { Id = eventIndex.ToString(_usCulture) }; eventIndex++; - var sections = line.Substring(10).Split(','); + const string Dialogue = "Dialogue: "; + var sections = line.Substring(Dialogue.Length).Split(','); subEvent.StartPositionTicks = GetTicks(sections[headers["Start"]]); subEvent.EndPositionTicks = GetTicks(sections[headers["End"]]); - subEvent.Text = string.Join(",", sections.Skip(headers["Text"])); + subEvent.Text = string.Join(',', sections[headers["Text"]..]); RemoteNativeFormatting(subEvent); subEvent.Text = subEvent.Text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase); @@ -62,7 +63,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - trackInfo.TrackEvents = trackEvents.ToArray(); + trackInfo.TrackEvents = trackEvents; return trackInfo; } @@ -72,9 +73,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles ? span.Ticks : 0; } - private Dictionary<string, int> ParseFieldHeaders(string line) + internal static Dictionary<string, int> ParseFieldHeaders(string line) { - var fields = line.Substring(8).Split(',').Select(x => x.Trim()).ToList(); + const string Format = "Format: "; + var fields = line.Substring(Format.Length).Split(',').Select(x => x.Trim()).ToList(); return new Dictionary<string, int> { From 07cc28946bcb8a3d9199f2e887e44f73d39fac86 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Mon, 28 Dec 2020 15:33:36 +0100 Subject: [PATCH 0875/1930] Add tests for ass parser --- .../Subtitles/AssParserTests.cs | 38 +++++++++++++++++++ .../Test Data/example.ass | 22 +++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs new file mode 100644 index 0000000000..14ad498399 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs @@ -0,0 +1,38 @@ +using System; +using System.Globalization; +using System.IO; +using System.Threading; +using MediaBrowser.MediaEncoding.Subtitles; +using Xunit; + +namespace Jellyfin.MediaEncoding.Subtitles.Tests +{ + public class AssParserTests + { + [Fact] + public void Parse_Valid_Success() + { + using (var stream = File.OpenRead("Test Data/example.ass")) + { + var parsed = new AssParser().Parse(stream, CancellationToken.None); + Assert.Single(parsed.TrackEvents); + var trackEvent = parsed.TrackEvents[0]; + + Assert.Equal("1", trackEvent.Id); + Assert.Equal(TimeSpan.Parse("00:00:01.18", CultureInfo.InvariantCulture).Ticks, trackEvent.StartPositionTicks); + Assert.Equal(TimeSpan.Parse("00:00:06.85", CultureInfo.InvariantCulture).Ticks, trackEvent.EndPositionTicks); + Assert.Equal("Like an Angel with pity on nobody\r\nThe second line in subtitle", trackEvent.Text); + } + } + + [Fact] + public void ParseFieldHeaders_Valid_Success() + { + const string Line = "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"; + var headers = AssParser.ParseFieldHeaders(Line); + Assert.Equal(1, headers["Start"]); + Assert.Equal(2, headers["End"]); + Assert.Equal(9, headers["Text"]); + } + } +} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass new file mode 100644 index 0000000000..d5ac31d702 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.ass @@ -0,0 +1,22 @@ +[Script Info] +; Script generated by Aegisub +; http://www.aegisub.org +Title: Neon Genesis Evangelion - Episode 26 (neutral Spanish) +Original Script: RoRo +Script Updated By: version 2.8.01 +ScriptType: v4.00+ +Collisions: Normal +PlayResY: 600 +PlayDepth: 0 +Timer: 100,0000 +Video Aspect Ratio: 0 +Video Zoom: 6 +Video Position: 0 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: DefaultVCD, Arial,28,&H00B4FCFC,&H00B4FCFC,&H00000008,&H80000008,-1,0,0,0,100,100,0.00,0.00,1,1.00,2.00,2,30,30,30,0 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:01.18,0:00:06.85,DefaultVCD, NTP,0000,0000,0000,,{\pos(400,570)}Like an Angel with pity on nobody\NThe second line in subtitle From 5ac36a8b5859d5416005ab411774aa9464a533d2 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Mon, 28 Dec 2020 15:43:55 +0100 Subject: [PATCH 0876/1930] Add tests for srt parser --- .../Subtitles/SrtParser.cs | 4 +-- .../Subtitles/SrtParserTests.cs | 35 +++++++++++++++++++ .../Test Data/example.srt | 8 +++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index cc35efb3f0..4a87f87dc1 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var multiline = new List<string>(); while ((line = reader.ReadLine()) != null) { - if (string.IsNullOrEmpty(line)) + if (line.Length == 0) { break; } @@ -87,7 +87,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - trackInfo.TrackEvents = trackEvents.ToArray(); + trackInfo.TrackEvents = trackEvents; return trackInfo; } diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs new file mode 100644 index 0000000000..3e2d2de10e --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs @@ -0,0 +1,35 @@ +using System; +using System.Globalization; +using System.IO; +using System.Threading; +using MediaBrowser.MediaEncoding.Subtitles; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Jellyfin.MediaEncoding.Subtitles.Tests +{ + public class SrtParserTests + { + [Fact] + public void Parse_Valid_Success() + { + using (var stream = File.OpenRead("Test Data/example.srt")) + { + var parsed = new SrtParser(new NullLogger<SrtParser>()).Parse(stream, CancellationToken.None); + Assert.Equal(2, parsed.TrackEvents.Count); + + var trackEvent1 = parsed.TrackEvents[0]; + Assert.Equal("1", trackEvent1.Id); + Assert.Equal(TimeSpan.Parse("00:02:17.440", CultureInfo.InvariantCulture).Ticks, trackEvent1.StartPositionTicks); + Assert.Equal(TimeSpan.Parse("00:02:20.375", CultureInfo.InvariantCulture).Ticks, trackEvent1.EndPositionTicks); + Assert.Equal("Senator, we're making\r\nour final approach into Coruscant.", trackEvent1.Text); + + var trackEvent2 = parsed.TrackEvents[1]; + Assert.Equal("2", trackEvent2.Id); + Assert.Equal(TimeSpan.Parse("00:02:20.476", CultureInfo.InvariantCulture).Ticks, trackEvent2.StartPositionTicks); + Assert.Equal(TimeSpan.Parse("00:02:22.501", CultureInfo.InvariantCulture).Ticks, trackEvent2.EndPositionTicks); + Assert.Equal("Very good, Lieutenant.", trackEvent2.Text); + } + } + } +} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt new file mode 100644 index 0000000000..78d74014ef --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/example.srt @@ -0,0 +1,8 @@ +1 +00:02:17,440 --> 00:02:20,375 +Senator, we're making +our final approach into Coruscant. + +2 +00:02:20,476 --> 00:02:22,501 +Very good, Lieutenant. From 9e0f4257838ca79b0babe7bbb62ae2a79797fc26 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Mon, 28 Dec 2020 23:41:46 +0100 Subject: [PATCH 0877/1930] Make RootObject and SeasonRootObject internal again --- MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 4 ++-- MediaBrowser.Providers/Properties/AssemblyInfo.cs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 25371e27ea..2372e31834 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -471,7 +471,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb return string.Equals(lang, "en", StringComparison.OrdinalIgnoreCase); } - public class SeasonRootObject + internal class SeasonRootObject { public string Title { get; set; } @@ -486,7 +486,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb public string Response { get; set; } } - public class RootObject + internal class RootObject { public string Title { get; set; } diff --git a/MediaBrowser.Providers/Properties/AssemblyInfo.cs b/MediaBrowser.Providers/Properties/AssemblyInfo.cs index f1c46899ce..fe4749c799 100644 --- a/MediaBrowser.Providers/Properties/AssemblyInfo.cs +++ b/MediaBrowser.Providers/Properties/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Resources; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -14,6 +15,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] +[assembly: InternalsVisibleTo("Jellyfin.Common.Tests")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from From 8ac1ed16ca6d539cf9061b3c9de139dcf148f401 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Tue, 29 Dec 2020 00:15:36 +0100 Subject: [PATCH 0878/1930] Use Theory instead of Fact for unit tests --- .../Json/JsonOmdbConverterTests.cs | 71 ++++++------------- 1 file changed, 20 insertions(+), 51 deletions(-) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index 06a4855bfd..6f85fe0929 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -1,6 +1,5 @@ using System.Text.Json; using System.Text.Json.Serialization; -using MediaBrowser.Common.Json; using MediaBrowser.Common.Json.Converters; using MediaBrowser.Providers.Plugins.Omdb; using Xunit; @@ -30,70 +29,40 @@ namespace Jellyfin.Common.Tests.Json Assert.Null(seasonRootObject?.Metascore); } - [Fact] - public void Deserialize_Not_Available_Int_Success() + [Theory] + [InlineData("\"N/A\"")] + [InlineData("null")] + public void Deserialization_To_Nullable_Int_Shoud_Be_Null(string input) { - const string Input = "\"N/A\""; - - var result = JsonSerializer.Deserialize<int?>(Input, _options); + var result = JsonSerializer.Deserialize<int?>(input, _options); Assert.Null(result); } - [Fact] - public void Deserialize_Not_Available_String_Success() + [Theory] + [InlineData("\"N/A\"")] + [InlineData("null")] + public void Deserialization_To_Nullable_String_Shoud_Be_Null(string input) { - const string Input = "\"N/A\""; - - var result = JsonSerializer.Deserialize<string>(Input, _options); + var result = JsonSerializer.Deserialize<string?>(input, _options); Assert.Null(result); } + [Theory] + [InlineData("\"8\"", 8)] + [InlineData("8", 8)] + public void Deserialize_Int_Success(string input, int expected) + { + var result = JsonSerializer.Deserialize<int>(input, _options); + Assert.Equal(result, expected); + } + [Fact] public void Deserialize_Normal_String_Success() { - const string Expected = "Jellyfin"; const string Input = "\"Jellyfin\""; - + const string Expected = "Jellyfin"; var result = JsonSerializer.Deserialize<string>(Input, _options); Assert.Equal(Expected, result); } - - [Fact] - public void Deserialize_Null_Success() - { - const string Input = "null"; - - var result = JsonSerializer.Deserialize<string>(Input, _options); - Assert.Null(result); - } - - [Fact] - public void Deserialize_Number_Success() - { - const int Number = 8; - const string Input = "8"; - - var result = JsonSerializer.Deserialize<int>(Input, _options); - Assert.Equal(Number, result); - } - - [Fact] - public void Deserialize_Quoted_Number_Success() - { - const int Number = 8; - const string Input = "\"8\""; - - var result = JsonSerializer.Deserialize<int>(Input, _options); - Assert.Equal(Number, result); - } - - [Fact] - public void Deserialize_NA_Number_Success() - { - const string Input = "\"N/A\""; - - var result = JsonSerializer.Deserialize<int?>(Input, _options); - Assert.Null(result); - } } } From 3dec1fd6b23fa4f7f9bc3f66edca8ec0f285ae0f Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Tue, 29 Dec 2020 00:35:59 +0100 Subject: [PATCH 0879/1930] Use UTF8 encoding and async correctly --- Emby.Server.Implementations/ApplicationHost.cs | 3 ++- Emby.Server.Implementations/Channels/ChannelManager.cs | 7 ++++--- .../LiveTv/EmbyTV/ItemDataProvider.cs | 8 +++++--- .../ScheduledTasks/ScheduledTaskWorker.cs | 7 ++++--- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 115d94b316..8fa712914a 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -10,6 +10,7 @@ using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -1047,7 +1048,7 @@ namespace Emby.Server.Implementations var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { - var jsonString = File.ReadAllText(metafile); + var jsonString = File.ReadAllText(metafile, Encoding.UTF8); var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, _jsonOptions); if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index cf6a87ecfd..2d5b19fa69 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -341,7 +342,7 @@ namespace Emby.Server.Implementations.Channels try { - var jsonString = File.ReadAllText(path); + var jsonString = File.ReadAllText(path, Encoding.UTF8); return JsonSerializer.Deserialize<List<MediaSourceInfo>>(jsonString, _jsonOptions) ?? new List<MediaSourceInfo>(); } @@ -1180,11 +1181,11 @@ namespace Emby.Server.Implementations.Channels { if (enableMediaProbe && !info.IsLiveStream && item.HasPathProtocol) { - await SaveMediaSources(item, new List<MediaSourceInfo>()); + await SaveMediaSources(item, new List<MediaSourceInfo>()).ConfigureAwait(false); } else { - await SaveMediaSources(item, info.MediaSources); + await SaveMediaSources(item, info.MediaSources).ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index f16d96a592..c80ecd6b3c 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; +using System.Threading.Tasks; using MediaBrowser.Common.Json; using Microsoft.Extensions.Logging; @@ -45,7 +47,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var jsonString = File.ReadAllText(_dataPath); + var jsonString = File.ReadAllText(_dataPath, Encoding.UTF8); _items = JsonSerializer.Deserialize<T[]>(jsonString, _jsonOptions); return; } @@ -61,8 +63,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private void SaveList() { Directory.CreateDirectory(Path.GetDirectoryName(_dataPath)); - using FileStream stream = File.OpenWrite(_dataPath); - JsonSerializer.SerializeAsync(stream, _items, _jsonOptions); + var jsonString = JsonSerializer.Serialize(_items, _jsonOptions); + File.WriteAllText(_dataPath, jsonString); } public IReadOnlyList<T> GetAll() diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 0bb627192f..29440b64a0 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -144,7 +145,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { try { - var jsonString = File.ReadAllText(path); + var jsonString = File.ReadAllText(path, Encoding.UTF8); if (!string.IsNullOrWhiteSpace(jsonString)) { _lastExecutionResult = JsonSerializer.Deserialize<TaskResult>(jsonString, _jsonOptions); @@ -540,7 +541,7 @@ namespace Emby.Server.Implementations.ScheduledTasks TaskTriggerInfo[] list = null; if (File.Exists(path)) { - var jsonString = File.ReadAllText(path); + var jsonString = File.ReadAllText(path, Encoding.UTF8); list = JsonSerializer.Deserialize<TaskTriggerInfo[]>(jsonString, _jsonOptions); } @@ -578,7 +579,7 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(Path.GetDirectoryName(path)); var json = JsonSerializer.Serialize(triggers, _jsonOptions); - File.WriteAllText(path, json); + File.WriteAllText(path, json, Encoding.UTF8); } /// <summary> From 782c23338989edb17fe8739e7dcad315c983fff2 Mon Sep 17 00:00:00 2001 From: Shaunak Basu <basushaunak@msn.com> Date: Tue, 29 Dec 2020 07:39:12 +0000 Subject: [PATCH 0880/1930] Translated using Weblate (Bengali) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bn/ --- Emby.Server.Implementations/Localization/Core/bn.json | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json index 84c8a99f7a..a23037af8e 100644 --- a/Emby.Server.Implementations/Localization/Core/bn.json +++ b/Emby.Server.Implementations/Localization/Core/bn.json @@ -14,8 +14,8 @@ "HeaderFavoriteArtists": "প্রিয় শিল্পীরা", "HeaderFavoriteAlbums": "প্রিয় এলবামগুলো", "HeaderContinueWatching": "দেখতে থাকুন", - "HeaderAlbumArtists": "এলবাম শিল্পী", - "Genres": "জেনার", + "HeaderAlbumArtists": "এলবাম শিল্পীবৃন্দ", + "Genres": "শৈলী", "Folders": "ফোল্ডারগুলো", "Favorites": "পছন্দসমূহ", "FailedLoginAttemptWithUserName": "{0} লগিন করতে ব্যর্থ হয়েছে", @@ -114,5 +114,8 @@ "TaskCleanLogs": "লগ ডিরেক্টরি ক্লিন করুন", "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।", "Undefined": "অসঙ্গায়িত", - "Forced": "জোরপূর্বক" + "Forced": "জোরকরে", + "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন", + "TaskCleanActivityLog": "কাজের ফাইল খালি করুন", + "Default": "প্রাথমিক" } From 8dfe89ea5203fb53e111cf5dc2b846fede9097a1 Mon Sep 17 00:00:00 2001 From: Shaunak Basu <basushaunak@msn.com> Date: Tue, 29 Dec 2020 07:45:32 +0000 Subject: [PATCH 0881/1930] Translated using Weblate (Hindi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hi/ --- .../Localization/Core/hi.json | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index df68d3bbd4..4cc2b378b5 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -1,3 +1,30 @@ { - "Albums": "आल्बुम्" + "Albums": "संग्रह", + "HeaderRecordingGroups": "रिकॉर्डिंग समूह", + "HeaderNextUp": "इसके बाद", + "HeaderLiveTV": "लाइव टीवी", + "HeaderFavoriteSongs": "पसंदीदा गीत", + "HeaderFavoriteShows": "पसंदीदा शोज", + "HeaderFavoriteEpisodes": "पसंदीदा एपिसोड्स", + "HeaderFavoriteArtists": "पसंदीदा कलाकारसमूह", + "HeaderFavoriteAlbums": "पसंदीदा एलबम्स", + "HeaderContinueWatching": "देखते रहिए", + "HeaderAlbumArtists": "एल्बम कलकरसमुह", + "Genres": "शैली", + "Forced": "बलपूर्वक", + "Folders": "फोल्डेरें", + "Favorites": "पसंदीदा", + "FailedLoginAttemptWithUserName": "{0} से लॉगिन असफल हुआ है", + "DeviceOnlineWithName": "{0} से संयोग हो गया है", + "DeviceOfflineWithName": "{0} से संयोग विच्छिन्न हो गया है", + "Default": "प्राथमिक", + "Collections": "संग्रह", + "ChapterNameValue": "अध्याय", + "Channels": "चैनल", + "CameraImageUploadedFrom": "कैमरा से एक नया चित्र अपलोड किया गया है", + "Books": "किताब", + "AuthenticationSucceededWithUserName": "सफलता से प्रमाणीकृत", + "Artists": "कलाकारों", + "Application": "एप्लिकेशन", + "AppDeviceValues": "एप: {0}, मशीन: {1}" } From cae38f3a7ed80231f1e34cb69f4af9328ff8839f Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 29 Dec 2020 16:08:16 -0700 Subject: [PATCH 0882/1930] Add JsonConverter for Nullable Guids --- .../Converters/JsonNullableGuidConverter.cs | 33 +++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 1 + .../Json/JsonNullableGuidConverterTests.cs | 69 +++++++++++++++++++ 3 files changed, 103 insertions(+) create mode 100644 MediaBrowser.Common/Json/Converters/JsonNullableGuidConverter.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableGuidConverter.cs b/MediaBrowser.Common/Json/Converters/JsonNullableGuidConverter.cs new file mode 100644 index 0000000000..6d96d5496f --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonNullableGuidConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a GUID object or value to/from JSON. + /// </summary> + public class JsonNullableGuidConverter : JsonConverter<Guid?> + { + /// <inheritdoc /> + public override Guid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var guidStr = reader.GetString(); + return guidStr == null ? null : new Guid(guidStr); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options) + { + if (value == null || value == Guid.Empty) + { + writer.WriteNullValue(); + } + else + { + writer.WriteStringValue(value.Value.ToString("N", CultureInfo.InvariantCulture)); + } + } + } +} diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 1ec2a87c53..2ef24a884a 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -34,6 +34,7 @@ namespace MediaBrowser.Common.Json Converters = { new JsonGuidConverter(), + new JsonNullableGuidConverter(), new JsonVersionConverter(), new JsonStringEnumConverter(), new JsonNullableStructConverterFactory(), diff --git a/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs new file mode 100644 index 0000000000..efc0c4af9a --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs @@ -0,0 +1,69 @@ +using System; +using System.Globalization; +using System.Text.Json; +using MediaBrowser.Common.Json.Converters; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public class JsonNullableGuidConverterTests + { + private readonly JsonSerializerOptions _options; + + public JsonNullableGuidConverterTests() + { + _options = new JsonSerializerOptions(); + _options.Converters.Add(new JsonNullableGuidConverter()); + } + + [Fact] + public void Deserialize_Valid_Success() + { + Guid? value = JsonSerializer.Deserialize<Guid?>(@"""a852a27afe324084ae66db579ee3ee18""", _options); + Assert.Equal(new Guid("a852a27afe324084ae66db579ee3ee18"), value); + } + + [Fact] + public void Deserialize_ValidDashed_Success() + { + Guid? value = JsonSerializer.Deserialize<Guid?>(@"""e9b2dcaa-529c-426e-9433-5e9981f27f2e""", _options); + Assert.Equal(new Guid("e9b2dcaa-529c-426e-9433-5e9981f27f2e"), value); + } + + [Fact] + public void Roundtrip_Valid_Success() + { + Guid guid = new Guid("a852a27afe324084ae66db579ee3ee18"); + string value = JsonSerializer.Serialize(guid, _options); + Assert.Equal(guid, JsonSerializer.Deserialize<Guid?>(value, _options)); + } + + [Fact] + public void Deserialize_Null_EmptyGuid() + { + Assert.Null(JsonSerializer.Deserialize<Guid?>("null", _options)); + } + + [Fact] + public void Serialize_EmptyGuid_EmptyGuid() + { + Assert.Equal("null", JsonSerializer.Serialize((Guid?)Guid.Empty, _options)); + } + + [Fact] + public void Serialize_Valid_NoDash_Success() + { + var guid = (Guid?)new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA"); + var str = JsonSerializer.Serialize(guid, _options); + Assert.Equal($"\"{guid:N}\"", str); + } + + [Fact] + public void Serialize_Nullable_Success() + { + Guid? guid = new Guid("531797E9-9457-40E0-88BC-B1D6D38752FA"); + var str = JsonSerializer.Serialize(guid, _options); + Assert.Equal($"\"{guid:N}\"", str); + } + } +} From 633507eee1317670b2007abc5e760ecb64b383a8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Dec 2020 09:34:26 +0000 Subject: [PATCH 0883/1930] Bump DotNet.Glob from 3.1.0 to 3.1.2 Bumps [DotNet.Glob](https://github.com/dazinator/DotNet.Glob) from 3.1.0 to 3.1.2. - [Release notes](https://github.com/dazinator/DotNet.Glob/releases) - [Changelog](https://github.com/dazinator/DotNet.Glob/blob/develop/ReleaseNotes.md) - [Commits](https://github.com/dazinator/DotNet.Glob/compare/3.1.0...3.1.2) Signed-off-by: dependabot[bot] <support@github.com> --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 1e54c3b330..592873fe4d 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -31,7 +31,7 @@ <PackageReference Include="prometheus-net.DotNetRuntime" Version="3.4.1" /> <PackageReference Include="sharpcompress" Version="0.26.0" /> <PackageReference Include="SQLitePCL.pretty.netstandard" Version="2.1.0" /> - <PackageReference Include="DotNet.Glob" Version="3.1.0" /> + <PackageReference Include="DotNet.Glob" Version="3.1.2" /> </ItemGroup> <ItemGroup> From 9460611fbb42ec8b4edfbd72a0e964ebd75c072f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 30 Dec 2020 09:34:28 +0000 Subject: [PATCH 0884/1930] Bump prometheus-net from 4.0.0 to 4.1.1 Bumps [prometheus-net](https://github.com/prometheus-net/prometheus-net) from 4.0.0 to 4.1.1. - [Release notes](https://github.com/prometheus-net/prometheus-net/releases) - [Changelog](https://github.com/prometheus-net/prometheus-net/blob/master/History) - [Commits](https://github.com/prometheus-net/prometheus-net/compare/v4.0.0...v4.1.1) Signed-off-by: dependabot[bot] <support@github.com> --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index bc000fd458..fe33888666 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -42,7 +42,7 @@ <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="5.0.1" /> - <PackageReference Include="prometheus-net" Version="4.0.0" /> + <PackageReference Include="prometheus-net" Version="4.1.1" /> <PackageReference Include="prometheus-net.AspNetCore" Version="4.0.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> From 2bb84c0675b95d1b2d42912248467fa52ecebe5c Mon Sep 17 00:00:00 2001 From: Niels van Velzen <git@ndat.nl> Date: Wed, 30 Dec 2020 11:16:09 +0100 Subject: [PATCH 0885/1930] Fix limit parameter error for search hints endpoint --- Emby.Server.Implementations/Library/SearchEngine.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 1d9529dff4..94602582b7 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Library if (query.Limit.HasValue) { - results = results.GetRange(0, query.Limit.Value); + results = results.GetRange(0, Math.Min(query.Limit.Value, results.Count)); } return new QueryResult<SearchHintInfo> From 99adbf04975dcb233b49ea9f3eead358dd4d39fa Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Wed, 30 Dec 2020 08:48:33 -0500 Subject: [PATCH 0886/1930] Split resume function for Audiobooks --- .../Library/UserDataManager.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index f9e5e6bbcd..df8c6adfac 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -14,6 +14,7 @@ using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using Book = MediaBrowser.Controller.Entities.Book; +using AudioBook = MediaBrowser.Controller.Entities.AudioBook; namespace Emby.Server.Implementations.Library { @@ -219,7 +220,7 @@ namespace Emby.Server.Implementations.Library var hasRuntime = runtimeTicks > 0; // If a position has been reported, and if we know the duration - if (positionTicks > 0 && hasRuntime) + if (positionTicks > 0 && hasRuntime && !(item is AudioBook)) { var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100; @@ -245,6 +246,24 @@ namespace Emby.Server.Implementations.Library } } } + else if (positionTicks > 0 && hasRuntime && (item is AudioBook)) + { + var minIn = TimeSpan.FromTicks(positionTicks).TotalSeconds / 60; + // 10,000 ticks per millisecond * 60,000 milliseconds per minute = 600,000,000 ticks per minute + var minOut = (runtimeTicks - positionTicks) / 600000000; + + if (minIn > _config.Configuration.MinAudiobookResume) + { + // ignore progress during the beginning + positionTicks = 0; + } + else if (minOut < _config.Configuration.MaxAudiobookResume || positionTicks >= runtimeTicks) + { + // mark as completed close to the end + positionTicks = 0; + data.Played = playedToCompletion = true; + } + } else if (!hasRuntime) { // If we don't know the runtime we'll just have to assume it was fully played From cd979e6b6291d426f3e180e36b5a8ba68c208cbd Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Wed, 30 Dec 2020 08:52:11 -0500 Subject: [PATCH 0887/1930] Add default of 5 minutes --- .../Configuration/ServerConfiguration.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 7013cb300e..9fb978e9be 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -298,6 +298,18 @@ namespace MediaBrowser.Model.Configuration /// <value>The min resume duration seconds.</value> public int MinResumeDurationSeconds { get; set; } = 300; + /// <summary> + /// Gets or sets the minimum minutes of a book that must be played in order for playstate to be updated. + /// </summary> + /// <value>The min resume in minutes.</value> + public int MinAudiobookResume { get; set; } = 5; + + /// <summary> + /// Gets or sets the remaining minutes of a book that can be played while still saving playstate. If this percentage is crossed playstate will be reset to the beginning and the item will be marked watched. + /// </summary> + /// <value>The remaining time in minutes.</value> + public int MaxAudiobookResume { get; set; } = 5; + /// <summary> /// Gets or sets the delay in seconds that we will wait after a file system change to try and discover what has been added/removed /// Some delay is necessary with some items because their creation is not atomic. It involves the creation of several From 77b478c726df8012e8eb27ee59f3bd937848a661 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Wed, 30 Dec 2020 09:12:13 -0500 Subject: [PATCH 0888/1930] Update Emby.Server.Implementations/Library/UserDataManager.cs Co-authored-by: Bond-009 <bond.009@outlook.com> --- Emby.Server.Implementations/Library/UserDataManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index df8c6adfac..1b38f5e0e0 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -248,7 +248,7 @@ namespace Emby.Server.Implementations.Library } else if (positionTicks > 0 && hasRuntime && (item is AudioBook)) { - var minIn = TimeSpan.FromTicks(positionTicks).TotalSeconds / 60; + var minIn = TimeSpan.FromTicks(positionTicks).TotalMinutes; // 10,000 ticks per millisecond * 60,000 milliseconds per minute = 600,000,000 ticks per minute var minOut = (runtimeTicks - positionTicks) / 600000000; From c7cb177260e80859d18e40615673dc2b7afeda9c Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Wed, 30 Dec 2020 09:12:36 -0500 Subject: [PATCH 0889/1930] Update Emby.Server.Implementations/Library/UserDataManager.cs Co-authored-by: Bond-009 <bond.009@outlook.com> --- Emby.Server.Implementations/Library/UserDataManager.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 1b38f5e0e0..415e207102 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -249,8 +249,7 @@ namespace Emby.Server.Implementations.Library else if (positionTicks > 0 && hasRuntime && (item is AudioBook)) { var minIn = TimeSpan.FromTicks(positionTicks).TotalMinutes; - // 10,000 ticks per millisecond * 60,000 milliseconds per minute = 600,000,000 ticks per minute - var minOut = (runtimeTicks - positionTicks) / 600000000; + var minOut = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; if (minIn > _config.Configuration.MinAudiobookResume) { From f411353c8ca27eb17db4258d400a38721041c9a2 Mon Sep 17 00:00:00 2001 From: artiume <siderite@gmail.com> Date: Wed, 30 Dec 2020 09:30:02 -0500 Subject: [PATCH 0890/1930] Update Emby.Server.Implementations/Library/UserDataManager.cs Co-authored-by: Bond-009 <bond.009@outlook.com> --- Emby.Server.Implementations/Library/UserDataManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 415e207102..d16275b192 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -246,7 +246,7 @@ namespace Emby.Server.Implementations.Library } } } - else if (positionTicks > 0 && hasRuntime && (item is AudioBook)) + else if (positionTicks > 0 && hasRuntime && item is AudioBook) { var minIn = TimeSpan.FromTicks(positionTicks).TotalMinutes; var minOut = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; From 4c291da45c57f1999868182490b55fb7872c26ba Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 30 Dec 2020 17:31:26 +0000 Subject: [PATCH 0891/1930] Encoding fix for System Logs. (#4564) --- Emby.Dlna/Service/BaseControlHandler.cs | 2 +- Jellyfin.Api/Controllers/SystemController.cs | 2 +- Jellyfin.Server/Program.cs | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 198852ec17..8d2486fee6 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -49,7 +49,7 @@ namespace Emby.Dlna.Service { ControlRequestInfo requestInfo = null; - using (var streamReader = new StreamReader(request.InputXml)) + using (var streamReader = new StreamReader(request.InputXml, Encoding.UTF8)) { var readerSettings = new XmlReaderSettings() { diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index d79bea9855..e67a27ae30 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -203,7 +203,7 @@ namespace Jellyfin.Api.Controllers // For older files, assume fully static var fileShare = file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite; FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, fileShare); - return File(stream, "text/plain"); + return File(stream, "text/plain; charset=utf-8"); } /// <summary> diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index a1a7a30534..f05cdfe9bd 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -598,7 +598,8 @@ namespace Jellyfin.Server .WriteTo.Async(x => x.File( Path.Combine(appPaths.LogDirectoryPath, "log_.log"), rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}")) + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}", + encoding: Encoding.UTF8)) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); From dbfbf9fb5bc79f4c23552a0a881c55c4300ab75b Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 30 Dec 2020 19:45:31 -0700 Subject: [PATCH 0892/1930] Fix bad merge --- .../ApplicationHost.cs | 96 ------------------- 1 file changed, 96 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 9d4643fcf5..094134318c 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1026,102 +1026,6 @@ namespace Emby.Server.Implementations protected abstract void RestartInternal(); - /// <inheritdoc/> - public IEnumerable<LocalPlugin> GetLocalPlugins(string path, bool cleanup = true) - { - var minimumVersion = new Version(0, 0, 0, 1); - var versions = new List<LocalPlugin>(); - if (!Directory.Exists(path)) - { - // Plugin path doesn't exist, don't try to enumerate subfolders. - return Enumerable.Empty<LocalPlugin>(); - } - - var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly); - - foreach (var dir in directories) - { - try - { - var metafile = Path.Combine(dir, "meta.json"); - if (File.Exists(metafile)) - { - var jsonString = File.ReadAllText(metafile, Encoding.UTF8); - var manifest = JsonSerializer.Deserialize<PluginManifest>(jsonString, _jsonOptions); - - if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) - { - targetAbi = minimumVersion; - } - - if (!Version.TryParse(manifest.Version, out var version)) - { - version = minimumVersion; - } - - if (ApplicationVersion >= targetAbi) - { - // Only load Plugins if the plugin is built for this version or below. - versions.Add(new LocalPlugin(manifest.Guid, manifest.Name, version, dir)); - } - } - else - { - // No metafile, so lets see if the folder is versioned. - metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1]; - - int versionIndex = dir.LastIndexOf('_'); - if (versionIndex != -1 && Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version parsedVersion)) - { - // Versioned folder. - versions.Add(new LocalPlugin(Guid.Empty, metafile, parsedVersion, dir)); - } - else - { - // Un-versioned folder - Add it under the path name and version 0.0.0.1. - versions.Add(new LocalPlugin(Guid.Empty, metafile, minimumVersion, dir)); - } - } - } - catch - { - continue; - } - } - - string lastName = string.Empty; - versions.Sort(LocalPlugin.Compare); - // Traverse backwards through the list. - // The first item will be the latest version. - for (int x = versions.Count - 1; x >= 0; x--) - { - if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase)) - { - versions[x].DllFiles.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories)); - lastName = versions[x].Name; - continue; - } - - if (!string.IsNullOrEmpty(lastName) && cleanup) - { - // Attempt a cleanup of old folders. - try - { - Logger.LogDebug("Deleting {Path}", versions[x].Path); - Directory.Delete(versions[x].Path, true); - } - catch (Exception e) - { - Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path); - } - - versions.RemoveAt(x); - } - } - - return versions; - } - /// <summary> /// Gets the composable part assemblies. /// </summary> From 79227fcfef61f3452fa594efa93cf65be5804956 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 31 Dec 2020 06:43:16 +0000 Subject: [PATCH 0893/1930] Bump AutoFixture.Xunit2 from 4.14.0 to 4.15.0 Bumps [AutoFixture.Xunit2](https://github.com/AutoFixture/AutoFixture) from 4.14.0 to 4.15.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.14.0...v4.15.0) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 559289f1e9..7f73f43d17 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -15,7 +15,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.15.0" /> <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> - <PackageReference Include="AutoFixture.Xunit2" Version="4.14.0" /> + <PackageReference Include="AutoFixture.Xunit2" Version="4.15.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> From fdb3632e7aa4ca7d763991a9852eb97256a71414 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 31 Dec 2020 06:45:10 +0000 Subject: [PATCH 0894/1930] Bump prometheus-net.AspNetCore from 4.0.0 to 4.1.1 Bumps [prometheus-net.AspNetCore](https://github.com/prometheus-net/prometheus-net) from 4.0.0 to 4.1.1. - [Release notes](https://github.com/prometheus-net/prometheus-net/releases) - [Changelog](https://github.com/prometheus-net/prometheus-net/blob/master/History) - [Commits](https://github.com/prometheus-net/prometheus-net/compare/v4.0.0...v4.1.1) Signed-off-by: dependabot[bot] <support@github.com> --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index fe33888666..5940cf9389 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -43,7 +43,7 @@ <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="5.0.1" /> <PackageReference Include="prometheus-net" Version="4.1.1" /> - <PackageReference Include="prometheus-net.AspNetCore" Version="4.0.0" /> + <PackageReference Include="prometheus-net.AspNetCore" Version="4.1.1" /> <PackageReference Include="Serilog.AspNetCore" Version="3.4.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" /> From 45331ad83a24a624e991389dfe0e1404ac34f9bc Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Thu, 31 Dec 2020 11:32:32 +0100 Subject: [PATCH 0895/1930] Cover all branches in JsonNullableGuidConverter --- .../Json/JsonNullableGuidConverterTests.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs index efc0c4af9a..22bc7afb96 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs @@ -39,17 +39,29 @@ namespace Jellyfin.Common.Tests.Json } [Fact] - public void Deserialize_Null_EmptyGuid() + public void Deserialize_Null_Null() { Assert.Null(JsonSerializer.Deserialize<Guid?>("null", _options)); } [Fact] - public void Serialize_EmptyGuid_EmptyGuid() + public void Deserialize_EmptyGuid_EmptyGuid() + { + Assert.Equal(Guid.Empty, JsonSerializer.Deserialize<Guid?>(@"""00000000-0000-0000-0000-000000000000""", _options)); + } + + [Fact] + public void Serialize_EmptyGuid_Null() { Assert.Equal("null", JsonSerializer.Serialize((Guid?)Guid.Empty, _options)); } + [Fact] + public void Serialize_Null_Null() + { + Assert.Equal("null", JsonSerializer.Serialize((Guid?)null, _options)); + } + [Fact] public void Serialize_Valid_NoDash_Success() { From cc92f7afe599c9d1c4bfa35a67f6e89d1a790107 Mon Sep 17 00:00:00 2001 From: martinek-stepan <68327580+martinek-stepan@users.noreply.github.com> Date: Thu, 31 Dec 2020 12:09:25 +0100 Subject: [PATCH 0896/1930] Enable nullable for MediaBrowser.XbmcMetadata project (#4612) Co-authored-by: Cody Robibero <cody@robibe.ro> Co-authored-by: Stepan <ste.martinek+git@gmail.com> --- Jellyfin.Data/Jellyfin.Data.csproj | 2 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- .../Providers/ExternalIdInfo.cs | 21 ++++++++++++++++--- .../Manager/ProviderManager.cs | 12 +++++------ MediaBrowser.XbmcMetadata/EntryPoint.cs | 2 +- .../MediaBrowser.XbmcMetadata.csproj | 1 + .../Parsers/BaseNfoParser.cs | 9 ++++---- .../Parsers/MovieNfoParser.cs | 4 ++-- .../Parsers/SeriesNfoParser.cs | 6 +++--- .../Providers/BaseNfoProvider.cs | 2 +- .../Providers/BaseVideoNfoProvider.cs | 2 +- .../Savers/BaseNfoSaver.cs | 3 ++- .../Savers/MovieNfoSaver.cs | 2 +- 13 files changed, 42 insertions(+), 26 deletions(-) diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 572038d001..4fb5594d4d 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -1,4 +1,4 @@ -<Project Sdk="Microsoft.NET.Sdk"> +<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 334fe82097..c271a9cf85 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -1,4 +1,4 @@ -<Project Sdk="Microsoft.NET.Sdk"> +<Project Sdk="Microsoft.NET.Sdk"> <!-- ProjectGuid is only included as a requirement for SonarQube analysis --> <PropertyGroup> diff --git a/MediaBrowser.Model/Providers/ExternalIdInfo.cs b/MediaBrowser.Model/Providers/ExternalIdInfo.cs index 01784554f9..afe95e6eee 100644 --- a/MediaBrowser.Model/Providers/ExternalIdInfo.cs +++ b/MediaBrowser.Model/Providers/ExternalIdInfo.cs @@ -5,17 +5,32 @@ namespace MediaBrowser.Model.Providers /// </summary> public class ExternalIdInfo { + /// <summary> + /// Represents the external id information for serialization to the client. + /// </summary> + /// <param name="name">Name of the external id provider (IE: IMDB, MusicBrainz, etc).</param> + /// <param name="key">Key for this id. This key should be unique across all providers.</param> + /// <param name="type">Specific media type for this id</param> + /// <param name="urlFormatString">URL format string.</param> + public ExternalIdInfo(string name, string key, ExternalIdMediaType? type, string urlFormatString) + { + Name = name; + Key = key; + Type = type; + UrlFormatString = urlFormatString; + } + /// <summary> /// Gets or sets the display name of the external id provider (IE: IMDB, MusicBrainz, etc). /// </summary> // TODO: This should be renamed to ProviderName - public string? Name { get; set; } + public string Name { get; set; } /// <summary> /// Gets or sets the unique key for this id. This key should be unique across all providers. /// </summary> // TODO: This property is not actually unique across the concrete types at the moment. It should be updated to be unique. - public string? Key { get; set; } + public string Key { get; set; } /// <summary> /// Gets or sets the specific media type for this id. This is used to distinguish between the different @@ -31,6 +46,6 @@ namespace MediaBrowser.Model.Providers /// <summary> /// Gets or sets the URL format string. /// </summary> - public string? UrlFormatString { get; set; } + public string UrlFormatString { get; set; } } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index a20c47cf2e..913f14d9b8 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -960,13 +960,11 @@ namespace MediaBrowser.Providers.Manager public IEnumerable<ExternalIdInfo> GetExternalIdInfos(IHasProviderIds item) { return GetExternalIds(item) - .Select(i => new ExternalIdInfo - { - Name = i.ProviderName, - Key = i.Key, - Type = i.Type, - UrlFormatString = i.UrlFormatString - }); + .Select(i => new ExternalIdInfo( + name: i.ProviderName, + key: i.Key, + type: i.Type, + urlFormatString: i.UrlFormatString)); } /// <inheritdoc/> diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index 11b36285c9..981b7b9d2f 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.XbmcMetadata return Task.CompletedTask; } - private void OnUserDataSaved(object sender, UserDataSaveEventArgs e) + private void OnUserDataSaved(object? sender, UserDataSaveEventArgs e) { if (e.SaveReason == UserDataSaveReason.PlaybackFinished || e.SaveReason == UserDataSaveReason.TogglePlayed || e.SaveReason == UserDataSaveReason.UpdateUserRating) { diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 87d1e9464c..40f06c731f 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -19,6 +19,7 @@ <GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateDocumentationFile>true</GenerateDocumentationFile> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <Nullable>enable</Nullable> </PropertyGroup> <!-- Code Analyzers--> diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index b064644090..c287113c5c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -37,6 +37,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers Logger = logger; _config = config; ProviderManager = providerManager; + _validProviderIds = new Dictionary<string, string>(); } protected CultureInfo UsCulture { get; } = new CultureInfo("en-US"); @@ -72,7 +73,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile)); } - _validProviderIds = _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var idInfos = ProviderManager.GetExternalIdInfos(item.Item); @@ -376,7 +377,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } return null; - }).Where(i => i.HasValue).Select(i => i.Value).ToArray(); + }).OfType<MetadataField>().ToArray(); } break; @@ -711,10 +712,10 @@ namespace MediaBrowser.XbmcMetadata.Parsers default: string readerName = reader.Name; - if (_validProviderIds.TryGetValue(readerName, out string providerIdValue)) + if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue)) { var id = reader.ReadElementContentAsString(); - if (!string.IsNullOrWhiteSpace(id)) + if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id)) { item.SetProviderId(providerIdValue, id); } diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index b74a9fd8ae..15a2fb63ea 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -39,8 +39,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers { case "id": { - string imdbId = reader.GetAttribute("IMDB"); - string tmdbId = reader.GetAttribute("TMDB"); + string? imdbId = reader.GetAttribute("IMDB"); + string? tmdbId = reader.GetAttribute("TMDB"); if (string.IsNullOrWhiteSpace(imdbId)) { diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index f079d4a7e6..74a724989a 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -40,9 +40,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers { case "id": { - string imdbId = reader.GetAttribute("IMDB"); - string tmdbId = reader.GetAttribute("TMDB"); - string tvdbId = reader.GetAttribute("TVDB"); + string? imdbId = reader.GetAttribute("IMDB"); + string? tmdbId = reader.GetAttribute("TMDB"); + string? tvdbId = reader.GetAttribute("TVDB"); if (string.IsNullOrWhiteSpace(tvdbId)) { diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs index 6ad6c18a5b..abd3e78d76 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseNfoProvider.cs @@ -74,6 +74,6 @@ namespace MediaBrowser.XbmcMetadata.Providers protected abstract void Fetch(MetadataResult<T> result, string path, CancellationToken cancellationToken); - protected abstract FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService); + protected abstract FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs index 2b1589d47b..e7aa3ca074 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// <inheritdoc /> - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) { return MovieNfoSaver.GetMovieSavePaths(info) .Select(directoryService.GetFile) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index d8230d188e..1adc5029df 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -200,7 +200,8 @@ namespace MediaBrowser.XbmcMetadata.Savers private void SaveToFile(Stream stream, string path) { - Directory.CreateDirectory(Path.GetDirectoryName(path)); + var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); + Directory.CreateDirectory(directory); // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs index dca796415a..8411217352 100644 --- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.XbmcMetadata.Savers /// <inheritdoc /> protected override string GetLocalSavePath(BaseItem item) - => GetMovieSavePaths(new ItemInfo(item)).FirstOrDefault(); + => GetMovieSavePaths(new ItemInfo(item)).FirstOrDefault() ?? Path.ChangeExtension(item.Path, ".nfo"); internal static IEnumerable<string> GetMovieSavePaths(ItemInfo item) { From 149c2b2169192da29d82c440175d8d9049dea8b3 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 31 Dec 2020 11:39:34 +0000 Subject: [PATCH 0897/1930] Added referenced assembly failure detection, and DI failure protection. --- Emby.Server.Implementations/ApplicationHost.cs | 2 ++ Emby.Server.Implementations/Plugins/PluginManager.cs | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 094134318c..1b9bb86bbd 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -413,6 +413,8 @@ namespace Emby.Server.Implementations catch (Exception ex) { Logger.LogError(ex, "Error creating {Type}", type); + // If this is a plugin fail it. + _pluginManager.FailPlugin(type.Assembly); return null; } finally diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 51a75f6a39..1ab01252d0 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -111,6 +111,10 @@ namespace Emby.Server.Implementations.Plugins try { assembly = Assembly.LoadFrom(file); + + // This force loads all reference dll's that the plugin uses in the try..catch block. + // Removing this will cause JF to bomb out if referenced dll's cause issues. + assembly.GetExportedTypes(); } catch (FileLoadException ex) { From c76faa97086a9d677ce3bc419d325c0ace89a8be Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 31 Dec 2020 13:18:13 +0000 Subject: [PATCH 0898/1930] Update IPNetAddress.cs Corrected loopback subnet --- MediaBrowser.Common/Net/IPNetAddress.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index a6f5fe4b37..5fab52eac7 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -33,7 +33,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// IP4Loopback address host. /// </summary> - public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/32"); + public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8"); /// <summary> /// IP6Loopback address host. From 6717b8c91a874e74ad688a30b3d662dadf88711f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 31 Dec 2020 14:13:22 +0000 Subject: [PATCH 0899/1930] Bump AutoFixture.AutoMoq from 4.14.0 to 4.15.0 Bumps [AutoFixture.AutoMoq](https://github.com/AutoFixture/AutoFixture) from 4.14.0 to 4.15.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.14.0...v4.15.0) Signed-off-by: dependabot[bot] <support@github.com> --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 7f73f43d17..45c93987b0 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -14,7 +14,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.15.0" /> - <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> + <PackageReference Include="AutoFixture.AutoMoq" Version="4.15.0" /> <PackageReference Include="AutoFixture.Xunit2" Version="4.15.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="5.0.1" /> <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" /> diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index b7a006070f..80259a55f2 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -15,7 +15,7 @@ <ItemGroup> <PackageReference Include="AutoFixture" Version="4.15.0" /> - <PackageReference Include="AutoFixture.AutoMoq" Version="4.14.0" /> + <PackageReference Include="AutoFixture.AutoMoq" Version="4.15.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> <PackageReference Include="Moq" Version="4.15.2" /> <PackageReference Include="xunit" Version="2.4.1" /> From bd1c115e46795f7db38366d31de79bf2ff88ca8d Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 31 Dec 2020 15:59:48 +0000 Subject: [PATCH 0900/1930] renamed imagePath to imageUrl --- MediaBrowser.Model/Updates/PackageInfo.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Model/Updates/PackageInfo.cs b/MediaBrowser.Model/Updates/PackageInfo.cs index 2b6e940d15..7a82685f0e 100644 --- a/MediaBrowser.Model/Updates/PackageInfo.cs +++ b/MediaBrowser.Model/Updates/PackageInfo.cs @@ -77,9 +77,9 @@ namespace MediaBrowser.Model.Updates #pragma warning restore CA2227 // Collection properties should be read only /// <summary> - /// Gets or sets the image path for the package. + /// Gets or sets the image url for the package. /// </summary> - [JsonPropertyName("imagePath")] - public string? ImagePath { get; set; } + [JsonPropertyName("imageUrl")] + public string? ImageUrl { get; set; } } } From 11700db3123242eda03d72e1aca0740592005f4b Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Fri, 1 Jan 2021 00:25:47 +0000 Subject: [PATCH 0901/1930] Update StreamingHelpers.cs Null exception fix --- Jellyfin.Api/Helpers/StreamingHelpers.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index c6d844c4fe..4957ee8b8d 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -210,6 +210,7 @@ namespace Jellyfin.Api.Helpers && !state.VideoRequest.MaxHeight.HasValue; if (isVideoResolutionNotRequested + && state.VideoStream != null && state.VideoRequest.VideoBitRate.HasValue && state.VideoStream.BitRate.HasValue && state.VideoRequest.VideoBitRate.Value >= state.VideoStream.BitRate.Value) From 1fdeac0a7d7a502e92352db8feaf0208270d1b6e Mon Sep 17 00:00:00 2001 From: Gary Wilber <Spacetech326@gmail.com> Date: Thu, 31 Dec 2020 18:40:24 -0800 Subject: [PATCH 0902/1930] Ignore inaccessible files during library scans --- .../IO/ManagedFileSystem.cs | 37 +++++++++++-------- .../Library/Resolvers/PlaylistResolver.cs | 2 +- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 3cb025111d..5ebc9b61b5 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -582,9 +582,7 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false) { - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - - return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption)); + return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive))); } public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false) @@ -594,16 +592,16 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string> extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + var enumerationOptions = GetEnumerationOptions(recursive); // On linux and osx the search pattern is case sensitive // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1) { - return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption)); + return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], enumerationOptions)); } - var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption); + var files = new DirectoryInfo(path).EnumerateFiles("*", enumerationOptions); if (extensions != null && extensions.Count > 0) { @@ -625,10 +623,10 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false) { var directoryInfo = new DirectoryInfo(path); - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + var enumerationOptions = GetEnumerationOptions(recursive); - return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption)) - .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption))); + return ToMetadata(directoryInfo.EnumerateDirectories("*", enumerationOptions)) + .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", enumerationOptions))); } private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos) @@ -638,8 +636,7 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false) { - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - return Directory.EnumerateDirectories(path, "*", searchOption); + return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive)); } public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false) @@ -649,16 +646,16 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; + var enumerationOptions = GetEnumerationOptions(recursive); // On linux and osx the search pattern is case sensitive // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1) { - return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption); + return Directory.EnumerateFiles(path, "*" + extensions[0], enumerationOptions); } - var files = Directory.EnumerateFiles(path, "*", searchOption); + var files = Directory.EnumerateFiles(path, "*", enumerationOptions); if (extensions != null && extensions.Length > 0) { @@ -679,8 +676,16 @@ namespace Emby.Server.Implementations.IO public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false) { - var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - return Directory.EnumerateFileSystemEntries(path, "*", searchOption); + return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive)); + } + + private EnumerationOptions GetEnumerationOptions(bool recursive) + { + return new EnumerationOptions + { + RecurseSubdirectories = recursive, + IgnoreInaccessible = true + }; } private static void RunProcess(string path, string args, string workingDirectory) diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs index 41561916f7..c76d41e5cc 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs @@ -41,7 +41,7 @@ namespace Emby.Server.Implementations.Library.Resolvers } // It's a directory-based playlist if the directory contains a playlist file - var filePaths = Directory.EnumerateFiles(args.Path); + var filePaths = Directory.EnumerateFiles(args.Path, "*", new EnumerationOptions { IgnoreInaccessible = true }); if (filePaths.Any(f => f.EndsWith(PlaylistXmlSaver.DefaultPlaylistFilename, StringComparison.OrdinalIgnoreCase))) { return new Playlist From f154c0dfad7b587c7540a5dc280b01f599a708d1 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Fri, 1 Jan 2021 14:56:14 +0100 Subject: [PATCH 0903/1930] Change stable ci nuget build command --- .ci/azure-pipelines-package.yml | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 0a63b329ba..9ddd73e197 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -193,6 +193,10 @@ jobs: pool: vmImage: 'ubuntu-latest' + variables: + - name: JellyfinVersion + value: 0.0.0 + steps: - task: UseDotNet@2 displayName: 'Use .NET 5.0 sdk' @@ -200,13 +204,23 @@ jobs: packageType: 'sdk' version: '5.0.x' + - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )" + displayName: Set release version (stable) + condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') + - task: DotNetCoreCLI@2 displayName: 'Build Stable Nuget packages' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') inputs: - command: 'pack' - packagesToPack: 'Jellyfin.Data/Jellyfin.Data.csproj;MediaBrowser.Common/MediaBrowser.Common.csproj;MediaBrowser.Controller/MediaBrowser.Controller.csproj;MediaBrowser.Model/MediaBrowser.Model.csproj;Emby.Naming/Emby.Naming.csproj' - versioningScheme: 'off' + command: 'custom' + projects: | + Jellyfin.Data/Jellyfin.Data.csproj + MediaBrowser.Common/MediaBrowser.Common.csproj + MediaBrowser.Controller/MediaBrowser.Controller.csproj + MediaBrowser.Model/MediaBrowser.Model.csproj + Emby.Naming/Emby.Naming.csproj + custom: 'pack' + arguments: -o $(Build.ArtifactStagingDirectory) -p:Version=$(JellyfinVersion) - task: DotNetCoreCLI@2 displayName: 'Build Unstable Nuget packages' @@ -233,7 +247,7 @@ jobs: condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') inputs: command: 'push' - packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;$(Build.ArtifactStagingDirectory)/**/*.snupkg' + packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg' nuGetFeedType: 'external' publishFeedCredentials: 'NugetOrg' allowPackageConflicts: true # This ignores an error if the version already exists From 1b894798b172c65ec27ff56a607b8f11b695b735 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 1 Jan 2021 09:34:39 -0700 Subject: [PATCH 0904/1930] Change log level for converters --- Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 2 +- Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs | 2 +- Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs | 2 +- .../Json/Converters/JsonCommaDelimitedArrayConverter.cs | 2 +- .../Json/Converters/JsonPipeDelimitedArrayConverter.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs index e90f48d2fe..c04f3c721b 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -69,7 +69,7 @@ namespace Jellyfin.Api.ModelBinders } catch (FormatException e) { - _logger.LogWarning(e, "Error converting value."); + _logger.LogDebug(e, "Error converting value."); } } diff --git a/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs index 5d296227e6..be2045fbab 100644 --- a/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Api.ModelBinders } catch (FormatException e) { - _logger.LogWarning(e, "Error converting value."); + _logger.LogDebug(e, "Error converting value."); } } diff --git a/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs index a42e0e4da8..639ab07930 100644 --- a/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/PipeDelimitedArrayModelBinder.cs @@ -69,7 +69,7 @@ namespace Jellyfin.Api.ModelBinders } catch (FormatException e) { - _logger.LogWarning(e, "Error converting value."); + _logger.LogDebug(e, "Error converting value."); } } diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index a259cb7bcb..38a7e1d20f 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -45,7 +45,7 @@ namespace MediaBrowser.Common.Json.Converters { // TODO log when upgraded to .Net6 // https://github.com/dotnet/runtime/issues/42975 - // _logger.LogWarning(e, "Error converting value."); + // _logger.LogDebug(e, "Error converting value."); } } diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs index 75fbcea1f0..377db1a446 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -45,7 +45,7 @@ namespace MediaBrowser.Common.Json.Converters { // TODO log when upgraded to .Net6 // https://github.com/dotnet/runtime/issues/42975 - // _logger.LogWarning(e, "Error converting value."); + // _logger.LogDebug(e, "Error converting value."); } } From d077c425d3c266d65e4c1b5174ecf512eb53adef Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Fri, 1 Jan 2021 12:35:03 -0700 Subject: [PATCH 0905/1930] Add only correct person blurhash --- Emby.Server.Implementations/Dto/DtoService.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 686944a286..d5e1f51248 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -582,7 +582,20 @@ namespace Emby.Server.Implementations.Dto { baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary); baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture); - baseItemPerson.ImageBlurHashes = dto.ImageBlurHashes; + // Only add BlurHash for the person's image. + baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>(); + foreach (var (imageType, blurHash) in dto.ImageBlurHashes) + { + baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>(); + foreach (var (imageId, blurHashValue) in blurHash) + { + if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase)) + { + baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue; + } + } + } + list.Add(baseItemPerson); } } From cf52503630e4014c30b1e095874d9661d2c19406 Mon Sep 17 00:00:00 2001 From: Manjot Singh <commercial@manjot.net> Date: Sat, 2 Jan 2021 11:00:16 +0000 Subject: [PATCH 0906/1930] Added translation using Weblate (Punjabi) --- Emby.Server.Implementations/Localization/Core/pa.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/pa.json diff --git a/Emby.Server.Implementations/Localization/Core/pa.json b/Emby.Server.Implementations/Localization/Core/pa.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/pa.json @@ -0,0 +1 @@ +{} From 5932b967b71615468969201717e61e1278e81714 Mon Sep 17 00:00:00 2001 From: Manjot Singh <commercial@manjot.net> Date: Sat, 2 Jan 2021 11:01:05 +0000 Subject: [PATCH 0907/1930] Translated using Weblate (Punjabi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pa/ --- .../Localization/Core/pa.json | 122 +++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pa.json b/Emby.Server.Implementations/Localization/Core/pa.json index 0967ef424b..469fa89b6e 100644 --- a/Emby.Server.Implementations/Localization/Core/pa.json +++ b/Emby.Server.Implementations/Localization/Core/pa.json @@ -1 +1,121 @@ -{} +{ + "TaskRefreshChapterImages": "ਐਬਸਟਰੈਕਟ ਅਧਿਆਇ ਅਧਿਆਇ", + "TaskDownloadMissingSubtitlesDescription": "ਮੈਟਾਡੇਟਾ ਕੌਂਫਿਗਰੇਸ਼ਨ ਦੇ ਅਧਾਰ ਤੇ ਗਾਇਬ ਉਪਸਿਰਲੇਖਾਂ ਲਈ ਇੰਟਰਨੈਟ ਦੀ ਭਾਲ ਕਰਦਾ ਹੈ.", + "TaskDownloadMissingSubtitles": "ਗਾਇਬ ਉਪਸਿਰਲੇਖ ਡਾ Download ਨਲੋਡ ਕਰੋ", + "TaskRefreshChannelsDescription": "ਇੰਟਰਨੈੱਟ ਚੈਨਲ ਦੀ ਜਾਣਕਾਰੀ ਨੂੰ ਤਾਜ਼ਾ ਕਰਦਾ ਹੈ.", + "TaskRefreshChannels": "ਚੈਨਲਾਂ ਨੂੰ ਤਾਜ਼ਾ ਕਰੋ", + "TaskCleanTranscodeDescription": "ਇੱਕ ਦਿਨ ਤੋਂ ਵੱਧ ਪੁਰਾਣੀ ਟ੍ਰਾਂਸਕੋਡ ਫਾਈਲਾਂ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ.", + "TaskCleanTranscode": "ਕਲੀਨ ਟ੍ਰਾਂਸਕੋਡ ਡਾਇਰੈਕਟਰੀ", + "TaskUpdatePluginsDescription": "ਪਲਗਇੰਸਾਂ ਲਈ ਡਾਉਨਲੋਡ ਅਤੇ ਸਥਾਪਨਾ ਅਪਡੇਟਾਂ ਜੋ ਆਪਣੇ ਆਪ ਅਪਡੇਟ ਕਰਨ ਲਈ ਕੌਂਫਿਗਰ ਕੀਤੀਆਂ ਜਾਂਦੀਆਂ ਹਨ.", + "TaskUpdatePlugins": "ਪਲੱਗਇਨ ਅਪਡੇਟ ਕਰੋ", + "TaskRefreshPeopleDescription": "ਤੁਹਾਡੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਅਦਾਕਾਰਾਂ ਅਤੇ ਨਿਰਦੇਸ਼ਕਾਂ ਲਈ ਮੈਟਾਡੇਟਾ ਨੂੰ ਅਪਡੇਟ ਕਰਦਾ ਹੈ.", + "TaskRefreshPeople": "ਲੋਕਾਂ ਨੂੰ ਤਾਜ਼ਾ ਕਰੋ", + "TaskCleanLogsDescription": "ਲੌਗ ਫਾਈਲਾਂ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ ਜੋ {0} ਦਿਨਾਂ ਤੋਂ ਵੱਧ ਪੁਰਾਣੀਆਂ ਹਨ.", + "TaskCleanLogs": "ਕਲੀਨ ਲਾਗ ਡਾਇਰੈਕਟਰੀ", + "TaskRefreshLibraryDescription": "ਨਵੀਆਂ ਫਾਈਲਾਂ ਲਈ ਆਪਣੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਨੂੰ ਸਕੈਨ ਕਰਦਾ ਹੈ ਅਤੇ ਮੈਟਾਡੇਟਾ ਨੂੰ ਤਾਜ਼ਾ ਕਰਦਾ ਹੈ.", + "TaskRefreshLibrary": "ਸਕੈਨ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ", + "TaskRefreshChapterImagesDescription": "ਚੈਪਟਰਾਂ ਵਾਲੇ ਵੀਡੀਓ ਲਈ ਥੰਬਨੇਲ ਬਣਾਉਂਦੇ ਹਨ.", + "TaskCleanCacheDescription": "ਸਿਸਟਮ ਦੁਆਰਾ ਹੁਣ ਕੈਚੇ ਫਾਈਲਾਂ ਦੀ ਜਰੂਰਤ ਨਹੀਂ ਹੈ.", + "TaskCleanCache": "ਸਾਫ਼ ਕੈਸ਼ ਡਾਇਰੈਕਟਰੀ", + "TaskCleanActivityLogDescription": "ਕੌਂਫਿਗਰ ਕੀਤੀ ਉਮਰ ਤੋਂ ਪੁਰਾਣੀ ਗਤੀਵਿਧੀ ਲੌਗ ਐਂਟਰੀਜ ਨੂੰ ਮਿਟਾਉਂਦਾ ਹੈ.", + "TaskCleanActivityLog": "ਸਾਫ਼ ਗਤੀਵਿਧੀ ਲਾਗ", + "TasksChannelsCategory": "ਇੰਟਰਨੈੱਟ ਚੈਨਲ", + "TasksApplicationCategory": "ਐਪਲੀਕੇਸ਼ਨ", + "TasksLibraryCategory": "ਲਾਇਬ੍ਰੇਰੀ", + "TasksMaintenanceCategory": "ਰੱਖ-ਰਖਾਅ", + "VersionNumber": "ਵਰਜਨ {0}", + "ValueSpecialEpisodeName": "ਵਿਸ਼ੇਸ਼ - {0}", + "ValueHasBeenAddedToLibrary": "{0} ਤੁਹਾਡੀ ਮੀਡੀਆ ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ ਹੈ", + "UserStoppedPlayingItemWithValues": "{0} ਨੇ {2} 'ਤੇ {1} ਖੇਡਣਾ ਪੂਰਾ ਕਰ ਲਿਆ ਹੈ", + "UserStartedPlayingItemWithValues": "{0} {2} 'ਤੇ {1} ਖੇਡ ਰਿਹਾ ਹੈ", + "UserPolicyUpdatedWithName": "ਉਪਭੋਗਤਾ ਨੀਤੀ ਨੂੰ {0} ਲਈ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ", + "UserPasswordChangedWithName": "ਪਾਸਵਰਡ ਯੂਜ਼ਰ ਲਈ ਬਦਲਿਆ ਗਿਆ ਹੈ {0}", + "UserOnlineFromDevice": "{0} ਤੋਂ isਨਲਾਈਨ ਹੈ {1}", + "UserOfflineFromDevice": "{0} ਤੋਂ ਡਿਸਕਨੈਕਟ ਹੋ ਗਿਆ ਹੈ {1}", + "UserLockedOutWithName": "ਯੂਜ਼ਰ {0} ਨੂੰ ਲਾਕ ਆਉਟ ਕਰ ਦਿੱਤਾ ਗਿਆ ਹੈ", + "UserDownloadingItemWithValues": "{0} ਡਾ{ਨਲੋਡ ਕਰ ਰਿਹਾ ਹੈ {1}", + "UserDeletedWithName": "ਯੂਜ਼ਰ {0} ਨੂੰ ਮਿਟਾ ਦਿੱਤਾ ਗਿਆ ਹੈ", + "UserCreatedWithName": "ਯੂਜ਼ਰ {0} ਬਣਾਇਆ ਗਿਆ ਹੈ", + "User": "ਯੂਜ਼ਰ", + "Undefined": "ਪਰਿਭਾਸ਼ਤ", + "TvShows": "ਟੀਵੀ ਸ਼ੋਅਜ਼", + "System": "ਸਿਸਟਮ", + "Sync": "ਸਿੰਕ", + "SubtitleDownloadFailureFromForItem": "ਉਪਸਿਰਲੇਖ {1} ਲਈ {0} ਤੋਂ ਡਾ toਨਲੋਡ ਕਰਨ ਵਿੱਚ ਅਸਫਲ ਰਹੇ", + "StartupEmbyServerIsLoading": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਲੋਡ ਹੋ ਰਿਹਾ ਹੈ. ਕਿਰਪਾ ਕਰਕੇ ਜਲਦੀ ਹੀ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ.", + "Songs": "ਗਾਣੇ", + "Shows": "ਸ਼ੋਅਜ਼", + "ServerNameNeedsToBeRestarted": "{0} ਮੁੜ ਚਾਲੂ ਕਰਨ ਦੀ ਲੋੜ ਹੈ", + "ScheduledTaskStartedWithName": "{0} ਸ਼ੁਰੂ ਹੋਇਆ", + "ScheduledTaskFailedWithName": "{0} ਅਸਫਲ", + "ProviderValue": "ਦੇਣ ਵਾਲੇ: {0}", + "PluginUpdatedWithName": "{0} ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਸੀ", + "PluginUninstalledWithName": "{0} ਅਣਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ ਸੀ", + "PluginInstalledWithName": "{0} ਲਗਾਇਆ ਗਿਆ ਸੀ", + "Plugin": "ਪਲੱਗਇਨ", + "Playlists": "ਪਲੇਲਿਸਟਸ", + "Photos": "ਫੋਟੋਆਂ", + "NotificationOptionVideoPlaybackStopped": "ਵੀਡੀਓ ਪਲੇਬੈਕ ਰੋਕਿਆ ਗਿਆ", + "NotificationOptionVideoPlayback": "ਵੀਡੀਓ ਪਲੇਬੈਕ ਸ਼ੁਰੂ ਹੋਇਆ", + "NotificationOptionUserLockedOut": "ਉਪਭੋਗਤਾ ਨੂੰ ਲਾਕ ਆਉਟ ਕੀਤਾ ਗਿਆ", + "NotificationOptionTaskFailed": "ਨਿਰਧਾਰਤ ਕਾਰਜ ਅਸਫਲਤਾ", + "NotificationOptionServerRestartRequired": "ਸਰਵਰ ਨੂੰ ਮੁੜ ਚਾਲੂ ਕਰਨ ਦੀ ਲੋੜ ਹੈ", + "NotificationOptionPluginUpdateInstalled": "ਪਲੱਗਇਨ ਅਪਡੇਟ ਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ", + "NotificationOptionPluginUninstalled": "ਪਲੱਗਇਨ ਅਣਇੰਸਟੌਲ ਕੀਤਾ", + "NotificationOptionPluginInstalled": "ਪਲੱਗਇਨ ਸਥਾਪਿਤ ਕੀਤਾ", + "NotificationOptionPluginError": "ਪਲੱਗਇਨ ਅਸਫਲ", + "NotificationOptionNewLibraryContent": "ਨਵੀਂ ਸਮੱਗਰੀ ਸ਼ਾਮਲ ਕੀਤੀ ਗਈ", + "NotificationOptionInstallationFailed": "ਇੰਸਟਾਲੇਸ਼ਨ ਅਸਫਲ", + "NotificationOptionCameraImageUploaded": "ਕੈਮਰਾ ਤਸਵੀਰ ਅਪਲੋਡ ਕੀਤੀ ਗਈ", + "NotificationOptionAudioPlaybackStopped": "ਆਡੀਓ ਪਲੇਅਬੈਕ ਰੋਕਿਆ ਗਿਆ", + "NotificationOptionAudioPlayback": "ਆਡੀਓ ਪਲੇਅਬੈਕ ਸ਼ੁਰੂ ਹੋਇਆ", + "NotificationOptionApplicationUpdateInstalled": "ਐਪਲੀਕੇਸ਼ਨ ਅਪਡੇਟ ਇੰਸਟੌਲ ਕੀਤਾ ਗਿਆ", + "NotificationOptionApplicationUpdateAvailable": "ਐਪਲੀਕੇਸ਼ਨ ਅਪਡੇਟ ਉਪਲਬਧ ਹੈ", + "NewVersionIsAvailable": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਦਾ ਨਵਾਂ ਸੰਸਕਰਣ ਡਾਉਨਲੋਡ ਲਈ ਉਪਲਬਧ ਹੈ.", + "NameSeasonUnknown": "ਸੀਜ਼ਨ ਅਣਜਾਣ", + "NameSeasonNumber": "ਸੀਜ਼ਨ {0}", + "NameInstallFailed": "{0} ਇੰਸਟਾਲੇਸ਼ਨ ਫੇਲ੍ਹ ਹੋਈ", + "MusicVideos": "ਸੰਗੀਤ ਵੀਡੀਓ", + "Music": "ਸੰਗੀਤ", + "Movies": "ਫਿਲਮਾਂ", + "MixedContent": "ਮਿਸ਼ਰਤ ਸਮੱਗਰੀ", + "MessageServerConfigurationUpdated": "ਸਰਵਰ ਕੌਂਫਿਗਰੇਸ਼ਨ ਨੂੰ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ", + "MessageNamedServerConfigurationUpdatedWithValue": "ਸਰਵਰ ਕੌਂਫਿਗਰੇਸ਼ਨ ਸੈਕਸ਼ਨ {0} ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ", + "MessageApplicationUpdatedTo": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਨੂੰ ਅੱਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ {0}", + "MessageApplicationUpdated": "ਜੈਲੀਫਿਨ ਸਰਵਰ ਅਪਡੇਟ ਕੀਤਾ ਗਿਆ ਹੈ", + "Latest": "ਤਾਜ਼ਾ", + "LabelRunningTimeValue": "ਚੱਲਦਾ ਸਮਾਂ: {0}", + "LabelIpAddressValue": "IP ਪਤਾ: {0}", + "ItemRemovedWithName": "{0} ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚੋਂ ਹਟਾ ਦਿੱਤਾ ਗਿਆ ਸੀ", + "ItemAddedWithName": "{0} ਲਾਇਬ੍ਰੇਰੀ ਵਿੱਚ ਸ਼ਾਮਲ ਕੀਤਾ ਗਿਆ ਸੀ", + "Inherit": "ਵਿਰਾਸਤ", + "HomeVideos": "ਘਰੇਲੂ ਵੀਡੀਓ", + "HeaderRecordingGroups": "ਰਿਕਾਰਡਿੰਗ ਸਮੂਹ", + "HeaderNextUp": "ਅੱਗੇ", + "HeaderLiveTV": "ਲਾਈਵ ਟੀ", + "HeaderFavoriteSongs": "ਮਨਪਸੰਦ ਗਾਣੇ", + "HeaderFavoriteShows": "ਮਨਪਸੰਦ ਸ਼ੋਅ", + "HeaderFavoriteEpisodes": "ਮਨਪਸੰਦ ਐਪੀਸੋਡ", + "HeaderFavoriteArtists": "ਮਨਪਸੰਦ ਕਲਾਕਾਰ", + "HeaderFavoriteAlbums": "ਮਨਪਸੰਦ ਐਲਬਮ", + "HeaderContinueWatching": "ਵੇਖਣਾ ਜਾਰੀ ਰੱਖੋ", + "HeaderAlbumArtists": "ਐਲਬਮ ਕਲਾਕਾਰ", + "Genres": "ਸ਼ੈਲੀਆਂ", + "Forced": "ਮਜਬੂਰ", + "Folders": "ਫੋਲਡਰ", + "Favorites": "ਮਨਪਸੰਦ", + "FailedLoginAttemptWithUserName": "ਤੋਂ ਲਾਗਇਨ ਕੋਸ਼ਿਸ਼ ਫੇਲ ਹੋਈ {0}", + "DeviceOnlineWithName": "{0} ਜੁੜਿਆ ਹੋਇਆ ਹੈ", + "DeviceOfflineWithName": "{0} ਡਿਸਕਨੈਕਟ ਹੋ ਗਿਆ ਹੈ", + "Default": "ਮੂਲ", + "Collections": "ਸੰਗ੍ਰਹਿ", + "ChapterNameValue": "ਅਧਿਆਇ {0}", + "Channels": "ਚੈਨਲ", + "CameraImageUploadedFrom": "ਤੋਂ ਇੱਕ ਨਵਾਂ ਕੈਮਰਾ ਚਿੱਤਰ ਅਪਲੋਡ ਕੀਤਾ ਗਿਆ ਹੈ {0}", + "Books": "ਕਿਤਾਬਾਂ", + "AuthenticationSucceededWithUserName": "{0} ਸਫਲਤਾਪੂਰਕ ਪ੍ਰਮਾਣਿਤ", + "Artists": "ਕਲਾਕਾਰ", + "Application": "ਐਪਲੀਕੇਸ਼ਨ", + "AppDeviceValues": "ਐਪ: {0}, ਜੰਤਰ: {1}", + "Albums": "ਐਲਬਮਾਂ" +} From 8dd83327b5b9b77912b3b69ec00dc31898a86bc7 Mon Sep 17 00:00:00 2001 From: Matt Montgomery <33811686+ConfusedPolarBear@users.noreply.github.com> Date: Fri, 1 Jan 2021 17:26:31 -0600 Subject: [PATCH 0908/1930] Remove quick connect tokens after usage --- Emby.Server.Implementations/Session/SessionManager.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 885f65c64e..92cbb08129 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1456,7 +1456,12 @@ namespace Emby.Server.Implementations.Session throw new SecurityException("Unknown quick connect token"); } - request.UserId = result.Items[0].UserId; + var info = result.Items[0]; + request.UserId = info.UserId; + + // There's no need to keep the quick connect token in the database, as AuthenticateNewSessionInternal() issues a long lived token. + _authRepo.Delete(info); + return AuthenticateNewSessionInternal(request, false); } From e15b2ea10f21e4fb101074a59fd35561a0f48014 Mon Sep 17 00:00:00 2001 From: lemmens95 <lars_lemmens@hotmail.com> Date: Sat, 2 Jan 2021 19:37:30 +0000 Subject: [PATCH 0909/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index 1e80d0b5f9..ffc329e35b 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -26,7 +26,7 @@ "HeaderNextUp": "Volgende", "HeaderRecordingGroups": "Opnamegroepen", "HomeVideos": "Home video's", - "Inherit": "Overerven", + "Inherit": "Erven", "ItemAddedWithName": "{0} is toegevoegd aan de bibliotheek", "ItemRemovedWithName": "{0} is verwijderd uit de bibliotheek", "LabelIpAddressValue": "IP-adres: {0}", From d1da1aa4076f6eaa408fbc50d600686b7b219fc6 Mon Sep 17 00:00:00 2001 From: Azunyan- <panton123@gmail.com> Date: Sat, 2 Jan 2021 23:00:15 +0000 Subject: [PATCH 0910/1930] Translated using Weblate (Swedish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sv/ --- Emby.Server.Implementations/Localization/Core/sv.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json index bea294ba2e..552710d703 100644 --- a/Emby.Server.Implementations/Localization/Core/sv.json +++ b/Emby.Server.Implementations/Localization/Core/sv.json @@ -113,5 +113,9 @@ "TasksApplicationCategory": "Applikation", "TasksLibraryCategory": "Bibliotek", "TasksMaintenanceCategory": "Underhåll", - "TaskRefreshPeople": "Uppdatera Personer" + "TaskRefreshPeople": "Uppdatera Personer", + "TaskCleanActivityLogDescription": "Radera aktivitets logg inlägg som är äldre än definerad ålder.", + "TaskCleanActivityLog": "Rensa Aktivitets Logg", + "Undefined": "odefinierad", + "Forced": "Tvinga" } From a15e126ef87d2c1dc81206ae6abe07e16c3d1469 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sat, 2 Jan 2021 19:23:54 -0700 Subject: [PATCH 0911/1930] Fix inverted SkipWhile --- Jellyfin.Api/Controllers/TvShowsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 03fd1846d7..ca18901e5d 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -267,7 +267,7 @@ namespace Jellyfin.Api.Controllers if (startItemId.HasValue) { episodes = episodes - .SkipWhile(i => startItemId.Value.Equals(i.Id)) + .SkipWhile(i => !startItemId.Value.Equals(i.Id)) .ToList(); } From a3a31952f4739a98d12de12ebe25d5535cf4a805 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Sun, 3 Jan 2021 09:35:22 -0700 Subject: [PATCH 0912/1930] Fix OMDb converter --- .../JsonOmdbNotAvailableStructConverter.cs | 4 +++ .../Plugins/Omdb/OmdbProvider.cs | 32 +++---------------- 2 files changed, 8 insertions(+), 28 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs index b9e67ce2de..062c497373 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Text.Json; using System.Text.Json.Serialization; @@ -21,6 +22,9 @@ namespace MediaBrowser.Common.Json.Converters { return null; } + + var converter = TypeDescriptor.GetConverter(typeToConvert); + return (T?)converter.ConvertFromString(str); } return JsonSerializer.Deserialize<T>(ref reader, options); diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 2372e31834..a759f5408c 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -214,39 +214,15 @@ namespace MediaBrowser.Providers.Plugins.Omdb internal async Task<RootObject> GetRootObject(string imdbId, CancellationToken cancellationToken) { var path = await EnsureItemInfo(imdbId, cancellationToken).ConfigureAwait(false); - - string resultString; - - using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - using (var reader = new StreamReader(stream, new UTF8Encoding(false))) - { - resultString = reader.ReadToEnd(); - resultString = resultString.Replace("\"N/A\"", "\"\""); - } - } - - var result = JsonSerializer.Deserialize<RootObject>(resultString, _jsonOptions); - return result; + await using var stream = File.OpenRead(path); + return await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions, cancellationToken); } internal async Task<SeasonRootObject> GetSeasonRootObject(string imdbId, int seasonId, CancellationToken cancellationToken) { var path = await EnsureSeasonInfo(imdbId, seasonId, cancellationToken).ConfigureAwait(false); - - string resultString; - - using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) - { - using (var reader = new StreamReader(stream, new UTF8Encoding(false))) - { - resultString = reader.ReadToEnd(); - resultString = resultString.Replace("\"N/A\"", "\"\""); - } - } - - var result = JsonSerializer.Deserialize<SeasonRootObject>(resultString, _jsonOptions); - return result; + await using var stream = File.OpenRead(path); + return await JsonSerializer.DeserializeAsync<SeasonRootObject>(stream, _jsonOptions, cancellationToken); } internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds) From 0282a1ed09e40464d944977411cf3ae302aa32a4 Mon Sep 17 00:00:00 2001 From: obradovichv <53901450+obradovichv@users.noreply.github.com> Date: Sun, 3 Jan 2021 20:13:21 +0200 Subject: [PATCH 0913/1930] Fix string culture specificity Fix bug in SsaParser.cs primary color {\1c} formatting that would leave behind the {\1c} closing token and instead append </font> token unconditionally to the dialogue text. Add tests. Change AlphanumComparatorTests.cs complementary test data generation from an array shuffle to an array reversal. Although it was previously using a seeded Random, the shuffle itself could result in no rearrangement of elements if the seed or test data changed over time. The reversal guarantees reordering of elements and has the added benefit of simplifying the test code since no special handling is needed for arrays of 2 elements. Change DailyTrigger.cs logging of TriggerDate format to "yyyy-MM-dd HH:mm:ss.fff zzz" for consistency with configured log timestamp format and change DueTime format to culture-invariant "c" format. --- .../ScheduledTasks/Triggers/DailyTrigger.cs | 2 +- .../Subtitles/SsaParser.cs | 10 +- .../AlphanumComparatorTests.cs | 16 +--- .../SsaParserTests.cs | 96 +++++++++++++++++++ 4 files changed, 107 insertions(+), 17 deletions(-) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs index 8b67d37d7a..3b40320ab8 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs @@ -50,7 +50,7 @@ namespace Emby.Server.Implementations.ScheduledTasks var dueTime = triggerDate - now; - logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:g}, which is {DueTime:g} from now.", taskName, triggerDate, dueTime); + logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime); Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs index db6b475830..bc84c5074d 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs @@ -325,7 +325,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">"); } - text += "</font>"; + int indexOfEndTag = text.IndexOf("{\\1c}", start, StringComparison.Ordinal); + if (indexOfEndTag > 0) + { + text = text.Remove(indexOfEndTag, "{\\1c}".Length).Insert(indexOfEndTag, "</font>"); + } + else + { + text += "</font>"; + } } } } diff --git a/tests/Jellyfin.Controller.Tests/AlphanumComparatorTests.cs b/tests/Jellyfin.Controller.Tests/AlphanumComparatorTests.cs index 929bb92aa8..0adf098c33 100644 --- a/tests/Jellyfin.Controller.Tests/AlphanumComparatorTests.cs +++ b/tests/Jellyfin.Controller.Tests/AlphanumComparatorTests.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Sorting; using Xunit; @@ -8,8 +7,6 @@ namespace Jellyfin.Controller.Tests { public class AlphanumComparatorTests { - private readonly Random _rng = new Random(42); - // InlineData is pre-sorted [Theory] [InlineData(null, "", "1", "9", "10", "a", "z")] @@ -25,18 +22,7 @@ namespace Jellyfin.Controller.Tests [InlineData("12345678912345678912345678913234567891a", "12345678912345678912345678913234567891b")] public void AlphanumComparatorTest(params string?[] strings) { - var copy = (string?[])strings.Clone(); - if (strings.Length == 2) - { - var tmp = copy[0]; - copy[0] = copy[1]; - copy[1] = tmp; - } - else - { - copy.Shuffle(_rng); - } - + var copy = strings.Reverse().ToArray(); Array.Sort(copy, new AlphanumComparator()); Assert.True(strings.SequenceEqual(copy)); } diff --git a/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs new file mode 100644 index 0000000000..d11cb242c1 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using MediaBrowser.MediaEncoding.Subtitles; +using MediaBrowser.Model.MediaInfo; +using Xunit; + +namespace Jellyfin.MediaEncoding.Tests +{ + public class SsaParserTests + { + // commonly shared invariant value between tests, assumes default format order + private const string InvariantDialoguePrefix = "[Events]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,"; + + private SsaParser parser = new SsaParser(); + + [Theory] + [InlineData("[EvEnTs]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,text", "text")] // label casing insensitivity + [InlineData("[Events]\n,0:00:00.00,0:00:00.01,,,,,,,labelless dialogue", "labelless dialogue")] // no "Dialogue:" label, it is optional + [InlineData("[Events]\nFormat: Text, Start, End, Layer, Effect, Style\nDialogue: reordered text,0:00:00.00,0:00:00.01", "reordered text")] // reordered formats + [InlineData(InvariantDialoguePrefix + "Cased TEXT", "Cased TEXT")] // preserve text casing + [InlineData(InvariantDialoguePrefix + " text ", " text ")] // do not trim text + [InlineData(InvariantDialoguePrefix + "text, more text", "text, more text")] // append excess dialogue values (> 10) to text + [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text{\\fn} end", "start <font face=\"Font Name\">text</font> end")] // font name + [InlineData(InvariantDialoguePrefix + "start {\\fs10}text{\\fs} end", "start <font size=\"10\">text</font> end")] // font size + [InlineData(InvariantDialoguePrefix + "start {\\c&H112233}text{\\c} end", "start <font color=\"#332211\">text</font> end")] // color + [InlineData(InvariantDialoguePrefix + "start {\\1c&H112233}text{\\1c} end", "start <font color=\"#332211\">text</font> end")] // primay color + [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text1 {\\fs10}text2{\\fs}{\\fn} {\\1c&H112233}text3{\\1c} end", "start <font face=\"Font Name\">text1 <font size=\"10\">text2</font></font> <font color=\"#332211\">text3</font> end")] // nested formatting + public void Parse(string ssa, string expectedText) + { + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) + { + SubtitleTrackInfo subtitleTrackInfo = parser.Parse(stream, CancellationToken.None); + SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[0]; + Assert.Equal(expectedText, actual.Text); + } + } + + [Theory] + [MemberData(nameof(Parse_MultipleDialogues_TestData))] + public void Parse_MultipleDialogues(string ssa, IReadOnlyList<SubtitleTrackEvent> expectedSubtitleTrackEvents) + { + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) + { + SubtitleTrackInfo subtitleTrackInfo = parser.Parse(stream, CancellationToken.None); + + Assert.Equal(expectedSubtitleTrackEvents.Count, subtitleTrackInfo.TrackEvents.Count); + + for (int i = 0; i < expectedSubtitleTrackEvents.Count; ++i) + { + SubtitleTrackEvent expected = expectedSubtitleTrackEvents[i]; + SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[i]; + + Assert.Equal(expected.StartPositionTicks, actual.StartPositionTicks); + Assert.Equal(expected.EndPositionTicks, actual.EndPositionTicks); + Assert.Equal(expected.Text, actual.Text); + } + } + } + + public static IEnumerable<object[]> Parse_MultipleDialogues_TestData() + { + yield return new object[] + { + @"[Events] + Format: Layer, Start, End, Text + Dialogue: ,0:00:01.18,0:00:01.85,dialogue1 + Dialogue: ,0:00:02.18,0:00:02.85,dialogue2 + Dialogue: ,0:00:03.18,0:00:03.85,dialogue3 + ", + new List<SubtitleTrackEvent> + { + new SubtitleTrackEvent + { + StartPositionTicks = 11800000, + EndPositionTicks = 18500000, + Text = "dialogue1" + }, + new SubtitleTrackEvent + { + StartPositionTicks = 21800000, + EndPositionTicks = 28500000, + Text = "dialogue2" + }, + new SubtitleTrackEvent + { + StartPositionTicks = 31800000, + EndPositionTicks = 38500000, + Text = "dialogue3" + } + } + }; + } + } +} From d45e2fe95a187b388837c8f0232d7ac50aafbfd4 Mon Sep 17 00:00:00 2001 From: obradovichv <53901450+obradovichv@users.noreply.github.com> Date: Sun, 3 Jan 2021 20:32:33 +0200 Subject: [PATCH 0914/1930] Update contributors --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a63db6ed7c..9b427d10fd 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -80,6 +80,7 @@ - [nvllsvm](https://github.com/nvllsvm) - [nyanmisaka](https://github.com/nyanmisaka) - [OancaAndrei](https://github.com/OancaAndrei) + - [obradovichv](https://github.com/obradovichv) - [oddstr13](https://github.com/oddstr13) - [orryverducci](https://github.com/orryverducci) - [petermcneil](https://github.com/petermcneil) From c1d1b6e9f411c0b2d6d4d2d16e48c8a265111871 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Mon, 4 Jan 2021 07:52:44 -0700 Subject: [PATCH 0915/1930] Fix serialization loop --- ... => JsonOmdbNotAvailableInt32Converter.cs} | 21 ++++++++++++------- .../JsonOmdbNotAvailableStringConverter.cs | 2 +- .../Plugins/Omdb/OmdbItemProvider.cs | 2 +- .../Plugins/Omdb/OmdbProvider.cs | 2 +- .../Json/JsonOmdbConverterTests.cs | 2 +- 5 files changed, 17 insertions(+), 12 deletions(-) rename MediaBrowser.Common/Json/Converters/{JsonOmdbNotAvailableStructConverter.cs => JsonOmdbNotAvailableInt32Converter.cs} (54%) diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs similarity index 54% rename from MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs rename to MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs index 062c497373..cb3d83f584 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStructConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs @@ -8,12 +8,10 @@ namespace MediaBrowser.Common.Json.Converters /// <summary> /// Converts a string <c>N/A</c> to <c>string.Empty</c>. /// </summary> - /// <typeparam name="T">The resulting type.</typeparam> - public class JsonOmdbNotAvailableStructConverter<T> : JsonConverter<T?> - where T : struct + public class JsonOmdbNotAvailableInt32Converter : JsonConverter<int?> { /// <inheritdoc /> - public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { @@ -24,16 +22,23 @@ namespace MediaBrowser.Common.Json.Converters } var converter = TypeDescriptor.GetConverter(typeToConvert); - return (T?)converter.ConvertFromString(str); + return (int?)converter.ConvertFromString(str); } - return JsonSerializer.Deserialize<T>(ref reader, options); + return JsonSerializer.Deserialize<int?>(ref reader, options); } /// <inheritdoc /> - public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options) { - JsonSerializer.Serialize(value, options); + if (value.HasValue) + { + writer.WriteNumberValue(value.Value); + } + else + { + writer.WriteNullValue(); + } } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs index 4fec2ea3fd..6a8790374b 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs @@ -29,7 +29,7 @@ namespace MediaBrowser.Common.Json.Converters /// <inheritdoc /> public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { - JsonSerializer.Serialize(value, options); + writer.WriteStringValue(value); } } } diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 71d5510632..97fcbfb6fe 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); - _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); } public string Name => "The Open Movie Database"; diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index a759f5408c..3da999ad06 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); - _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); + _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); } public async Task Fetch<T>(MetadataResult<T> itemResult, string imdbId, string language, string country, CancellationToken cancellationToken) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index 6f85fe0929..03226cf31b 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -14,7 +14,7 @@ namespace Jellyfin.Common.Tests.Json { _options = new JsonSerializerOptions(); _options.Converters.Add(new JsonOmdbNotAvailableStringConverter()); - _options.Converters.Add(new JsonOmdbNotAvailableStructConverter<int>()); + _options.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); _options.NumberHandling = JsonNumberHandling.AllowReadingFromString; } From 12144d2d9ec15a45535018e4bd0f3d056ebbe8f8 Mon Sep 17 00:00:00 2001 From: Aron Szakacs <ferox7878@gmail.com> Date: Sun, 3 Jan 2021 14:01:38 +0000 Subject: [PATCH 0916/1930] Translated using Weblate (German (Swiss)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/gsw/ --- Emby.Server.Implementations/Localization/Core/gsw.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/gsw.json b/Emby.Server.Implementations/Localization/Core/gsw.json index ee1f8775e5..3364ee3332 100644 --- a/Emby.Server.Implementations/Localization/Core/gsw.json +++ b/Emby.Server.Implementations/Localization/Core/gsw.json @@ -113,5 +113,10 @@ "TaskUpdatePlugins": "Aktualisiere Erweiterungen", "TaskRefreshPeopleDescription": "Aktualisiert Metadaten für Schausteller und Regisseure in deiner Bibliothek.", "TaskRefreshPeople": "Aktualisiere Schauspieler", - "TaskCleanLogsDescription": "Löscht Log Dateien die älter als {0} Tage sind." + "TaskCleanLogsDescription": "Löscht Log Dateien die älter als {0} Tage sind.", + "TaskCleanActivityLogDescription": "Löscht Aktivitätsprotokolleinträge, die älter als das konfigurierte Alter sind.", + "TaskCleanActivityLog": "Aktivitätsprotokoll aufräumen", + "Undefined": "Undefiniert", + "Forced": "Erzwungen", + "Default": "Standard" } From a4a261e9409487645ee22e3fc0957438c55b18b0 Mon Sep 17 00:00:00 2001 From: suelio bertulino lima <sueliio@outlook.com> Date: Sun, 3 Jan 2021 16:42:25 +0000 Subject: [PATCH 0917/1930] Translated using Weblate (Portuguese (Brazil)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt_BR/ --- Emby.Server.Implementations/Localization/Core/pt-BR.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt-BR.json b/Emby.Server.Implementations/Localization/Core/pt-BR.json index 8d25e27f6b..5ec8f1e88a 100644 --- a/Emby.Server.Implementations/Localization/Core/pt-BR.json +++ b/Emby.Server.Implementations/Localization/Core/pt-BR.json @@ -115,5 +115,8 @@ "TasksLibraryCategory": "Biblioteca", "TasksMaintenanceCategory": "Manutenção", "TaskCleanActivityLogDescription": "Apaga o registro de atividades mais antigo que a idade configurada.", - "TaskCleanActivityLog": "Limpar Registro de Atividades" + "TaskCleanActivityLog": "Limpar Registro de Atividades", + "Undefined": "Indefinido", + "Forced": "Forçado", + "Default": "Padrão" } From 530c4dc11b4ccb5f2a0d02490b2f16f4b10caf15 Mon Sep 17 00:00:00 2001 From: Joe Ceresini <joe@ceresini.com> Date: Tue, 5 Jan 2021 00:30:31 -0500 Subject: [PATCH 0918/1930] Use variables for version, and fix conflict --- fedora/jellyfin.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fedora/jellyfin.spec b/fedora/jellyfin.spec index 197126ee56..71583c24ef 100644 --- a/fedora/jellyfin.spec +++ b/fedora/jellyfin.spec @@ -28,7 +28,7 @@ BuildRequires: libcurl-devel, fontconfig-devel, freetype-devel, openssl-devel, # COPR @dotnet-sig/dotnet or # https://packages.microsoft.com/rhel/7/prod/ BuildRequires: dotnet-runtime-5.0, dotnet-sdk-5.0 -Requires: %{name}-server = %{version}-%{release}, %{name}-web >= 10.6, %{name}-web < 10.7 +Requires: %{name}-server = %{version}-%{release}, %{name}-web = %{version}-%{release} # Disable Automatic Dependency Processing AutoReqProv: no From 13f347a81343942458e8a8565c20241d1a25cc17 Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Tue, 5 Jan 2021 07:00:48 -0700 Subject: [PATCH 0919/1930] Fix potential null reference --- Emby.Server.Implementations/Dto/DtoService.cs | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index d5e1f51248..8a901516c0 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -582,16 +582,22 @@ namespace Emby.Server.Implementations.Dto { baseItemPerson.PrimaryImageTag = GetTagAndFillBlurhash(dto, entity, ImageType.Primary); baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture); - // Only add BlurHash for the person's image. - baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>(); - foreach (var (imageType, blurHash) in dto.ImageBlurHashes) + if (dto.ImageBlurHashes != null) { - baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>(); - foreach (var (imageId, blurHashValue) in blurHash) + // Only add BlurHash for the person's image. + baseItemPerson.ImageBlurHashes = new Dictionary<ImageType, Dictionary<string, string>>(); + foreach (var (imageType, blurHash) in dto.ImageBlurHashes) { - if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase)) + if (blurHash != null) { - baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue; + baseItemPerson.ImageBlurHashes[imageType] = new Dictionary<string, string>(); + foreach (var (imageId, blurHashValue) in blurHash) + { + if (string.Equals(baseItemPerson.PrimaryImageTag, imageId, StringComparison.OrdinalIgnoreCase)) + { + baseItemPerson.ImageBlurHashes[imageType][imageId] = blurHashValue; + } + } } } } From cfca27e99a40204bc8e4fff963ef1a67aeed1876 Mon Sep 17 00:00:00 2001 From: Bill Thornton <billt2006@gmail.com> Date: Tue, 5 Jan 2021 10:06:55 -0500 Subject: [PATCH 0920/1930] Fix capitalization of Playstate message --- Emby.Dlna/PlayTo/PlayToController.cs | 2 +- Emby.Server.Implementations/Session/SessionManager.cs | 2 +- MediaBrowser.Model/Session/SessionMessageType.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 4861093044..311fae2400 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -826,7 +826,7 @@ namespace Emby.Dlna.PlayTo return SendPlayCommand(data as PlayRequest, cancellationToken); } - if (name == SessionMessageType.PlayState) + if (name == SessionMessageType.Playstate) { return SendPlaystateCommand(data as PlaystateRequest, cancellationToken); } diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 885f65c64e..4e026a0e6a 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1310,7 +1310,7 @@ namespace Emby.Server.Implementations.Session } } - return SendMessageToSession(session, SessionMessageType.PlayState, command, cancellationToken); + return SendMessageToSession(session, SessionMessageType.Playstate, command, cancellationToken); } private static void AssertCanControl(SessionInfo session, SessionInfo controllingSession) diff --git a/MediaBrowser.Model/Session/SessionMessageType.cs b/MediaBrowser.Model/Session/SessionMessageType.cs index 23c41026dc..84f4716b4d 100644 --- a/MediaBrowser.Model/Session/SessionMessageType.cs +++ b/MediaBrowser.Model/Session/SessionMessageType.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Model.Session Play, SyncPlayCommand, SyncPlayGroupUpdate, - PlayState, + Playstate, RestartRequired, ServerShuttingDown, ServerRestarting, From 989c6dcffa57f0c85d9050d4f9a1de070aa81566 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Tue, 5 Jan 2021 23:01:46 +0100 Subject: [PATCH 0921/1930] Update azure-pipelines-package.yml --- .ci/azure-pipelines-package.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 9ddd73e197..20f4dfe33b 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -195,7 +195,7 @@ jobs: variables: - name: JellyfinVersion - value: 0.0.0 + value: $[replace(variables['Build.SourceBranch'],'refs/tags/v','')] steps: - task: UseDotNet@2 @@ -204,10 +204,6 @@ jobs: packageType: 'sdk' version: '5.0.x' - - script: echo "##vso[task.setvariable variable=JellyfinVersion]$( awk -F '/' '{ print $NF }' <<<'$(Build.SourceBranch)' | sed 's/^v//' )" - displayName: Set release version (stable) - condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') - - task: DotNetCoreCLI@2 displayName: 'Build Stable Nuget packages' condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') From 162e8d3045907a0be055cec895856dca39399bd0 Mon Sep 17 00:00:00 2001 From: GlibTongue <itsmeglib+GitHubGlibTongue@gmail.com> Date: Tue, 5 Jan 2021 03:55:58 +0000 Subject: [PATCH 0922/1930] Translated using Weblate (Urdu (Pakistan)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ur_PK/ --- Emby.Server.Implementations/Localization/Core/ur_PK.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ur_PK.json b/Emby.Server.Implementations/Localization/Core/ur_PK.json index fa7b2d4d0c..5d6d0775c4 100644 --- a/Emby.Server.Implementations/Localization/Core/ur_PK.json +++ b/Emby.Server.Implementations/Localization/Core/ur_PK.json @@ -8,7 +8,7 @@ "Collections": "مجموعہ", "Folders": "فولڈرز", "HeaderLiveTV": "براہ راست ٹی وی", - "Channels": "چینل", + "Channels": "چینلز", "HeaderContinueWatching": "دیکھنا جاری رکھیں", "Playlists": "پلے لسٹس", "ValueSpecialEpisodeName": "خاص - {0}", @@ -17,7 +17,7 @@ "Artists": "فنکار", "Sync": "مطابقت", "Photos": "تصوریں", - "Albums": "البم", + "Albums": "البمز", "Favorites": "پسندیدہ", "Songs": "گانے", "Books": "کتابیں", From 75ed532fca9e5b3e8f83ca72cf54ecbafa3e1d1d Mon Sep 17 00:00:00 2001 From: crobibero <cody@robibe.ro> Date: Wed, 6 Jan 2021 07:07:38 -0700 Subject: [PATCH 0923/1930] Add serialize test --- .../Json/JsonOmdbConverterTests.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index 03226cf31b..faed086a12 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -64,5 +64,25 @@ namespace Jellyfin.Common.Tests.Json var result = JsonSerializer.Deserialize<string>(Input, _options); Assert.Equal(Expected, result); } + + [Fact] + public void Roundtrip_Valid_Success() + { + const string Input = "{\"Title\":\"Chapter 1\",\"Year\":\"2013\",\"Rated\":\"TV-MA\",\"Released\":\"01 Feb 2013\",\"Season\":\"N/A\",\"Episode\":\"N/A\",\"Runtime\":\"55 min\",\"Genre\":\"Drama\",\"Director\":\"David Fincher\",\"Writer\":\"Michael Dobbs (based on the novels by), Andrew Davies (based on the mini-series by), Beau Willimon (created for television by), Beau Willimon, Sam Forman (staff writer)\",\"Actors\":\"Kevin Spacey, Robin Wright, Kate Mara, Corey Stoll\",\"Plot\":\"Congressman Francis Underwood has been declined the chair for Secretary of State. He's now gathering his own team to plot his revenge. Zoe Barnes, a reporter for the Washington Herald, will do anything to get her big break.\",\"Language\":\"English\",\"Country\":\"USA\",\"Awards\":\"N/A\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTY5MTU4NDQzNV5BMl5BanBnXkFtZTgwMzk2ODcxMzE@._V1_SX300.jpg\",\"Ratings\":[{\"Source\":\"Internet Movie Database\",\"Value\":\"8.7/10\"}],\"Metascore\":\"N/A\",\"imdbRating\":\"8.7\",\"imdbVotes\":\"6736\",\"imdbID\":\"tt2161930\",\"seriesID\":\"N/A\",\"Type\":\"episode\",\"Response\":\"True\"}"; + var trip1 = JsonSerializer.Deserialize<OmdbProvider.RootObject>(Input, _options); + Assert.NotNull(trip1); + Assert.NotNull(trip1?.Title); + Assert.Null(trip1?.Awards); + Assert.Null(trip1?.Episode); + Assert.Null(trip1?.Metascore); + + var serializedTrip1 = JsonSerializer.Serialize(trip1!, _options); + var trip2 = JsonSerializer.Deserialize<OmdbProvider.RootObject>(serializedTrip1, _options); + Assert.NotNull(trip2); + Assert.NotNull(trip2?.Title); + Assert.Null(trip2?.Awards); + Assert.Null(trip2?.Episode); + Assert.Null(trip2?.Metascore); + } } } From 66ab4e77cd68ceddc728f6239189d7177e85035d Mon Sep 17 00:00:00 2001 From: Oatavandi <oatavandi@gmail.com> Date: Wed, 6 Jan 2021 16:57:06 +0000 Subject: [PATCH 0924/1930] Added translation using Weblate (Malayalam) --- Emby.Server.Implementations/Localization/Core/ml.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/ml.json diff --git a/Emby.Server.Implementations/Localization/Core/ml.json b/Emby.Server.Implementations/Localization/Core/ml.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/ml.json @@ -0,0 +1 @@ +{} From 0f4bbbc63cf2d4f79301a0be7a5431ea5b8cdbb7 Mon Sep 17 00:00:00 2001 From: Ian <ianjazz246@gmail.com> Date: Wed, 6 Jan 2021 10:26:40 -0800 Subject: [PATCH 0925/1930] Fix 3169 and 2879 by making MusicArtistResolver run ahead of MusicAlbumResolver --- CONTRIBUTORS.md | 1 + .../Library/Resolvers/Audio/AudioResolver.cs | 2 +- .../Library/Resolvers/Audio/MusicAlbumResolver.cs | 2 +- .../Library/Resolvers/Movies/MovieResolver.cs | 2 +- MediaBrowser.Controller/Resolvers/ResolverPriority.cs | 7 ++++++- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a63db6ed7c..33799f24b4 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -141,6 +141,7 @@ - [Pusta](https://github.com/pusta) - [nielsvanvelzen](https://github.com/nielsvanvelzen) - [skyfrk](https://github.com/skyfrk) + - [ianjazz246](https://github.com/ianjazz246) # Emby Contributors diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 2c4497c693..90b6a8a7db 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// Gets the priority. /// </summary> /// <value>The priority.</value> - public override ResolverPriority Priority => ResolverPriority.Fourth; + public override ResolverPriority Priority => ResolverPriority.Fifth; public MultiItemResolverResult ResolveMultiple( Folder parent, diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index 18ceb5e761..bf32381ebf 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -40,7 +40,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio /// Gets the priority. /// </summary> /// <value>The priority.</value> - public override ResolverPriority Priority => ResolverPriority.Second; + public override ResolverPriority Priority => ResolverPriority.Third; /// <summary> /// Resolves the specified args. diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index baf0e3cf91..8ef7172de1 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies /// Gets the priority. /// </summary> /// <value>The priority.</value> - public override ResolverPriority Priority => ResolverPriority.Third; + public override ResolverPriority Priority => ResolverPriority.Fourth; /// <inheritdoc /> public MultiItemResolverResult ResolveMultiple( diff --git a/MediaBrowser.Controller/Resolvers/ResolverPriority.cs b/MediaBrowser.Controller/Resolvers/ResolverPriority.cs index ac73a5ea89..d4f975b6d1 100644 --- a/MediaBrowser.Controller/Resolvers/ResolverPriority.cs +++ b/MediaBrowser.Controller/Resolvers/ResolverPriority.cs @@ -25,9 +25,14 @@ namespace MediaBrowser.Controller.Resolvers /// </summary> Fourth = 4, + /// <summary> + /// The Fifth. + /// </summary> + Fifth = 5, + /// <summary> /// The last. /// </summary> - Last = 5 + Last = 6 } } From 8044f1f72f06ddb9a0e4af205249fc0d6c300f99 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 6 Jan 2021 20:30:57 +0000 Subject: [PATCH 0926/1930] Update NetworkParseTests.cs --- .../NetworkTesting/NetworkParseTests.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index c350685af0..b7c1510d27 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -54,13 +54,13 @@ namespace Jellyfin.Networking.Tests /// <summary> /// Checks the ability to ignore interfaces /// </summary> - /// <param name="interfaces">Mock network setup, in the format (IP address, interface index, interface name) : .... </param> + /// <param name="interfaces">Mock network setup, in the format (IP address, interface index, interface name) | .... </param> /// <param name="lan">LAN addresses.</param> /// <param name="value">Bind addresses that are excluded.</param> [Theory] - [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] - [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] - [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212;200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] + [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.1.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) { var conf = new NetworkConfiguration() @@ -434,7 +434,7 @@ namespace Jellyfin.Networking.Tests EnableIPV4 = true }; - NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; + NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11"; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; @@ -501,7 +501,7 @@ namespace Jellyfin.Networking.Tests PublishedServerUriBySubnet = new string[] { publishedServers } }; - NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11"; + NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11"; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>()); NetworkManager.MockNetworkSettings = string.Empty; From 90d72d662826d0d99f03a7c1de58c184e712fe50 Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 6 Jan 2021 20:39:25 +0000 Subject: [PATCH 0927/1930] Update NetworkManager.cs Changed split character --- Jellyfin.Networking/Manager/NetworkManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 60b899519e..d85983e12c 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -387,7 +387,7 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that isn't a loopback. var interfaces = CreateCollection(_interfaceAddresses .Exclude(_bindExclusions) - .Where(p => IsInLocalNetwork(p)) + .Where(IsInLocalNetwork(p)) .OrderBy(p => p.Tag)); if (interfaces.Count > 0) @@ -591,7 +591,7 @@ namespace Jellyfin.Networking.Manager else // Used in testing only. { // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway. - var interfaceList = MockNetworkSettings.Split(':'); + var interfaceList = MockNetworkSettings.Split('|'); foreach (var details in interfaceList) { var parts = details.Split(','); From a664aac88149f3e9b62fa8558a14f8012d258fbd Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Wed, 6 Jan 2021 20:46:22 +0000 Subject: [PATCH 0928/1930] optimization --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index d85983e12c..8bb97937c3 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -387,7 +387,7 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that isn't a loopback. var interfaces = CreateCollection(_interfaceAddresses .Exclude(_bindExclusions) - .Where(IsInLocalNetwork(p)) + .Where(IsInLocalNetwork) .OrderBy(p => p.Tag)); if (interfaces.Count > 0) From 0ac993e1b31b7639a43a45cb3fc5dccdf2052ef7 Mon Sep 17 00:00:00 2001 From: Oatavandi <oatavandi@gmail.com> Date: Wed, 6 Jan 2021 17:02:11 +0000 Subject: [PATCH 0929/1930] Translated using Weblate (Malayalam) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ml/ --- .../Localization/Core/ml.json | 122 +++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ml.json b/Emby.Server.Implementations/Localization/Core/ml.json index 0967ef424b..e764963cff 100644 --- a/Emby.Server.Implementations/Localization/Core/ml.json +++ b/Emby.Server.Implementations/Localization/Core/ml.json @@ -1 +1,121 @@ -{} +{ + "AppDeviceValues": "അപ്ലിക്കേഷൻ: {0}, ഉപകരണം: {1}", + "Application": "അപ്ലിക്കേഷൻ", + "AuthenticationSucceededWithUserName": "{0} വിജയകരമായി പ്രാമാണീകരിച്ചു", + "CameraImageUploadedFrom": "Camera 0 from എന്നതിൽ നിന്ന് ഒരു പുതിയ ക്യാമറ ചിത്രം അപ്‌ലോഡുചെയ്‌തു", + "ChapterNameValue": "അധ്യായം {0}", + "DeviceOfflineWithName": "{0} വിച്ഛേദിച്ചു", + "DeviceOnlineWithName": "{0} ബന്ധിപ്പിച്ചു", + "FailedLoginAttemptWithUserName": "Log 0 from എന്നതിൽ നിന്നുള്ള പ്രവേശന ശ്രമം പരാജയപ്പെട്ടു", + "Forced": "നിർബന്ധിച്ചു", + "HeaderFavoriteAlbums": "പ്രിയപ്പെട്ട ആൽബങ്ങൾ", + "HeaderFavoriteArtists": "പ്രിയപ്പെട്ട കലാകാരന്മാർ", + "HeaderFavoriteEpisodes": "പ്രിയപ്പെട്ട എപ്പിസോഡുകൾ", + "HeaderFavoriteShows": "പ്രിയപ്പെട്ട ഷോകൾ", + "HeaderFavoriteSongs": "പ്രിയപ്പെട്ട ഗാനങ്ങൾ", + "HeaderLiveTV": "തത്സമയ ടിവി", + "HeaderNextUp": "അടുത്തത്", + "HeaderRecordingGroups": "ഗ്രൂപ്പുകൾ റെക്കോർഡുചെയ്യുന്നു", + "HomeVideos": "ഹോം വീഡിയോകൾ", + "Inherit": "അനന്തരാവകാശം", + "ItemAddedWithName": "{0} ലൈബ്രറിയിൽ ചേർത്തു", + "ItemRemovedWithName": "{0} ലൈബ്രറിയിൽ നിന്ന് നീക്കംചെയ്തു", + "LabelIpAddressValue": "IP വിലാസം: {0}", + "LabelRunningTimeValue": "പ്രവർത്തന സമയം: {0}", + "Latest": "ഏറ്റവും പുതിയ", + "MessageApplicationUpdated": "ജെല്ലിഫിൻ സെർവർ അപ്‌ഡേറ്റുചെയ്‌തു", + "MessageApplicationUpdatedTo": "ജെല്ലിഫിൻ സെർവർ {0 to ലേക്ക് അപ്‌ഡേറ്റുചെയ്‌തു", + "MessageNamedServerConfigurationUpdatedWithValue": "സെർവർ കോൺഫിഗറേഷൻ വിഭാഗം {0 അപ്‌ഡേറ്റുചെയ്‌തു", + "MessageServerConfigurationUpdated": "സെർവർ കോൺഫിഗറേഷൻ അപ്‌ഡേറ്റുചെയ്‌തു", + "MixedContent": "മിശ്രിത ഉള്ളടക്കം", + "Music": "സംഗീതം", + "MusicVideos": "സംഗീത വീഡിയോകൾ", + "NameInstallFailed": "{0} ഇൻസ്റ്റാളേഷൻ പരാജയപ്പെട്ടു", + "NameSeasonNumber": "സീസൺ {0}", + "NameSeasonUnknown": "സീസൺ അജ്ഞാതം", + "NewVersionIsAvailable": "ജെല്ലിഫിൻ സെർവറിന്റെ പുതിയ പതിപ്പ് ഡ .ൺ‌ലോഡിനായി ലഭ്യമാണ്.", + "NotificationOptionApplicationUpdateAvailable": "അപ്ലിക്കേഷൻ അപ്‌ഡേറ്റ് ലഭ്യമാണ്", + "NotificationOptionApplicationUpdateInstalled": "അപ്ലിക്കേഷൻ അപ്‌ഡേറ്റ് ഇൻസ്റ്റാളുചെയ്‌തു", + "NotificationOptionAudioPlayback": "ഓഡിയോ പ്ലേബാക്ക് ആരംഭിച്ചു", + "NotificationOptionAudioPlaybackStopped": "ഓഡിയോ പ്ലേബാക്ക് നിർത്തി", + "NotificationOptionCameraImageUploaded": "ക്യാമറ ചിത്രം അപ്‌ലോഡുചെയ്‌തു", + "NotificationOptionInstallationFailed": "ഇൻസ്റ്റാളേഷൻ പരാജയം", + "NotificationOptionNewLibraryContent": "പുതിയ ഉള്ളടക്കം ചേർത്തു", + "NotificationOptionPluginError": "പ്ലഗിൻ പരാജയം", + "NotificationOptionPluginInstalled": "പ്ലഗിൻ ഇൻസ്റ്റാളുചെയ്‌തു", + "NotificationOptionPluginUninstalled": "പ്ലഗിൻ അൺഇൻസ്റ്റാൾ ചെയ്തു", + "NotificationOptionPluginUpdateInstalled": "പ്ലഗിൻ അപ്‌ഡേറ്റ് ഇൻസ്റ്റാളുചെയ്‌തു", + "NotificationOptionServerRestartRequired": "സെർവർ പുനരാരംഭിക്കൽ ആവശ്യമാണ്", + "NotificationOptionTaskFailed": "ഷെഡ്യൂൾ ചെയ്ത ടാസ്‌ക് പരാജയം", + "NotificationOptionUserLockedOut": "ഉപയോക്താവ് ലോക്ക് out ട്ട് ചെയ്‌തു", + "NotificationOptionVideoPlayback": "വീഡിയോ പ്ലേബാക്ക് ആരംഭിച്ചു", + "NotificationOptionVideoPlaybackStopped": "വീഡിയോ പ്ലേബാക്ക് നിർത്തി", + "Plugin": "പ്ലഗിൻ", + "PluginInstalledWithName": "{0} ഇൻസ്റ്റാളുചെയ്‌തു", + "PluginUninstalledWithName": "{0 un അൺഇൻസ്റ്റാൾ ചെയ്തു", + "PluginUpdatedWithName": "{0} അപ്‌ഡേറ്റുചെയ്‌തു", + "ProviderValue": "ദാതാവ്: {0}", + "ScheduledTaskFailedWithName": "{0} പരാജയപ്പെട്ടു", + "ScheduledTaskStartedWithName": "{0} ആരംഭിച്ചു", + "ServerNameNeedsToBeRestarted": "{0} പുനരാരംഭിക്കേണ്ടതുണ്ട്", + "StartupEmbyServerIsLoading": "ജെല്ലിഫിൻ സെർവർ ലോഡുചെയ്യുന്നു. ഉടൻ തന്നെ വീണ്ടും ശ്രമിക്കുക.", + "SubtitleDownloadFailureFromForItem": "സബ്ടൈറ്റിലുകൾ {1} ന് {0 from ൽ നിന്ന് ഡ download ൺലോഡ് ചെയ്യുന്നതിൽ പരാജയപ്പെട്ടു", + "System": "സിസ്റ്റം", + "TvShows": "ടിവി ഷോകൾ", + "Undefined": "നിർവചിച്ചിട്ടില്ല", + "User": "ഉപയോക്താവ്", + "UserCreatedWithName": "ഉപയോക്താവ് {0 created സൃഷ്ടിച്ചു", + "UserDeletedWithName": "ഉപയോക്താവ് {0 deleted ഇല്ലാതാക്കി", + "UserDownloadingItemWithValues": "{0} ഡൗൺലോഡുചെയ്യുന്നു {1}", + "UserLockedOutWithName": "{0} ഉപയോക്താവ് ലോക്ക് out ട്ട് ചെയ്‌തു", + "UserOfflineFromDevice": "{0} {1} ൽ നിന്ന് വിച്ഛേദിച്ചു", + "UserOnlineFromDevice": "{0} {1} മുതൽ ഓൺ‌ലൈനിലാണ്", + "UserPasswordChangedWithName": "{0} ഉപയോക്താവിനായി പാസ്‌വേഡ് മാറ്റി", + "UserPolicyUpdatedWithName": "{0} എന്നതിനായി ഉപയോക്തൃ നയം അപ്‌ഡേറ്റുചെയ്‌തു", + "UserStartedPlayingItemWithValues": "{0} {2} ൽ {1} പ്ലേ ചെയ്യുന്നു", + "UserStoppedPlayingItemWithValues": "{0} {2} ൽ {1 play കളിക്കുന്നത് പൂർത്തിയാക്കി", + "ValueHasBeenAddedToLibrary": "Media 0 your നിങ്ങളുടെ മീഡിയ ലൈബ്രറിയിലേക്ക് ചേർത്തു", + "VersionNumber": "പതിപ്പ് {0}", + "TasksMaintenanceCategory": "പരിപാലനം", + "TasksLibraryCategory": "പുസ്തകശാല", + "TasksApplicationCategory": "അപ്ലിക്കേഷൻ", + "TasksChannelsCategory": "ഇന്റർനെറ്റ് ചാനലുകൾ", + "TaskCleanActivityLog": "പ്രവർത്തന ലോഗ് വൃത്തിയാക്കുക", + "TaskCleanActivityLogDescription": "കോൺഫിഗർ ചെയ്‌ത പ്രായത്തേക്കാൾ പഴയ പ്രവർത്തന ലോഗ് എൻട്രികൾ ഇല്ലാതാക്കുന്നു.", + "TaskCleanCache": "കാഷെ ഡയറക്ടറി വൃത്തിയാക്കുക", + "TaskCleanCacheDescription": "സിസ്റ്റത്തിന് ഇനി ആവശ്യമില്ലാത്ത കാഷെ ഫയലുകൾ ഇല്ലാതാക്കുന്നു.", + "TaskRefreshChapterImages": "ചാപ്റ്റർ ഇമേജുകൾ എക്‌സ്‌ട്രാക്റ്റുചെയ്യുക", + "TaskRefreshChapterImagesDescription": "അധ്യായങ്ങളുള്ള വീഡിയോകൾക്കായി ലഘുചിത്രങ്ങൾ സൃഷ്ടിക്കുന്നു.", + "TaskRefreshLibrary": "മീഡിയ ലൈബ്രറി സ്കാൻ ചെയ്യുക", + "TaskRefreshLibraryDescription": "പുതിയ ഫയലുകൾക്കായി നിങ്ങളുടെ മീഡിയ ലൈബ്രറി സ്കാൻ ചെയ്യുകയും മെറ്റാഡാറ്റ പുതുക്കുകയും ചെയ്യുന്നു.", + "TaskCleanLogs": "ലോഗ് ഡയറക്ടറി വൃത്തിയാക്കുക", + "TaskCleanLogsDescription": "Log 0} ദിവസത്തിൽ കൂടുതൽ പഴക്കമുള്ള ലോഗ് ഫയലുകൾ ഇല്ലാതാക്കുന്നു.", + "TaskRefreshPeople": "ആളുകളെ പുതുക്കുക", + "TaskRefreshPeopleDescription": "നിങ്ങളുടെ മീഡിയ ലൈബ്രറിയിലെ അഭിനേതാക്കൾക്കും സംവിധായകർക്കും മെറ്റാഡാറ്റ അപ്‌ഡേറ്റുചെയ്യുന്നു.", + "TaskUpdatePlugins": "പ്ലഗിനുകൾ അപ്‌ഡേറ്റുചെയ്യുക", + "TaskUpdatePluginsDescription": "യാന്ത്രികമായി അപ്‌ഡേറ്റുചെയ്യുന്നതിന് കോൺഫിഗർ ചെയ്‌തിരിക്കുന്ന പ്ലഗിനുകൾക്കായുള്ള അപ്‌ഡേറ്റുകൾ ഡൗൺലോഡുചെയ്യുകയും ഇൻസ്റ്റാളുചെയ്യുകയും ചെയ്യുന്നു.", + "TaskCleanTranscode": "ട്രാൻസ്‌കോഡ് ഡയറക്‌ടറി വൃത്തിയാക്കുക", + "TaskCleanTranscodeDescription": "ഒരു ദിവസത്തിൽ കൂടുതൽ പഴക്കമുള്ള ട്രാൻസ്‌കോഡ് ഫയലുകൾ ഇല്ലാതാക്കുന്നു.", + "TaskRefreshChannels": "ചാനലുകൾ പുതുക്കുക", + "TaskRefreshChannelsDescription": "ഇന്റർനെറ്റ് ചാനൽ വിവരങ്ങൾ പുതുക്കുന്നു.", + "TaskDownloadMissingSubtitles": "നഷ്‌ടമായ സബ്‌ടൈറ്റിലുകൾ ഡൗൺലോഡുചെയ്യുക", + "TaskDownloadMissingSubtitlesDescription": "മെറ്റാഡാറ്റ കോൺഫിഗറേഷനെ അടിസ്ഥാനമാക്കി നഷ്‌ടമായ സബ്‌ടൈറ്റിലുകൾക്കായി ഇന്റർനെറ്റ് തിരയുന്നു.", + "ValueSpecialEpisodeName": "പ്രത്യേക - {0}", + "Collections": "ശേഖരങ്ങൾ", + "Folders": "ഫോൾഡറുകൾ", + "HeaderAlbumArtists": "ആൽബം ആർട്ടിസ്റ്റുകൾ", + "Sync": "സമന്വയിപ്പിക്കുക", + "Movies": "സിനിമകൾ", + "Photos": "ഫോട്ടോകൾ", + "Albums": "ആൽബങ്ങൾ", + "Playlists": "പ്ലേലിസ്റ്റുകൾ", + "Songs": "ഗാനങ്ങൾ", + "HeaderContinueWatching": "കാണുന്നത് തുടരുക", + "Artists": "കലാകാരന്മാർ", + "Shows": "ഷോകൾ", + "Default": "സ്ഥിരസ്ഥിതി", + "Favorites": "പ്രിയങ്കരങ്ങൾ", + "Books": "പുസ്തകങ്ങൾ", + "Genres": "വിഭാഗങ്ങൾ", + "Channels": "ചാനലുകൾ" +} From 7acee4070e425b9060faa893d61a5e2d2f387bfc Mon Sep 17 00:00:00 2001 From: minystory <minystory@gmail.com> Date: Thu, 7 Jan 2021 14:51:32 +0000 Subject: [PATCH 0930/1930] Translated using Weblate (Korean) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ko/ --- Emby.Server.Implementations/Localization/Core/ko.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ko.json b/Emby.Server.Implementations/Localization/Core/ko.json index b8b39833c8..9179bbc8de 100644 --- a/Emby.Server.Implementations/Localization/Core/ko.json +++ b/Emby.Server.Implementations/Localization/Core/ko.json @@ -115,5 +115,8 @@ "TasksChannelsCategory": "인터넷 채널", "TasksLibraryCategory": "라이브러리", "TaskCleanActivityLogDescription": "구성된 기간보다 오래된 활동내역 삭제.", - "TaskCleanActivityLog": "활동내역청소" + "TaskCleanActivityLog": "활동내역청소", + "Undefined": "일치하지 않음", + "Forced": "강제하기", + "Default": "기본 설정" } From 192efff7913ac17444bfdc6a3898657702dcf0ed Mon Sep 17 00:00:00 2001 From: BaronGreenback <jimcartlidge@yahoo.co.uk> Date: Thu, 7 Jan 2021 17:17:22 +0000 Subject: [PATCH 0931/1930] Update DlnaEntryPoint.cs --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 3f7b558f61..82490ec310 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -315,7 +315,7 @@ namespace Emby.Dlna.Main var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); // DLNA will only work over http, so we must reset to http:// : {port} uri.Scheme = "http://"; - uri.Port = _netConfig.PublicPort; + uri.Port = _netConfig.HttpServerPortNumber; var device = new SsdpRootDevice { From 87c2802984c92de5a958d75a7ca05401c5431faa Mon Sep 17 00:00:00 2001 From: David Ullmer <daullmer@gmail.com> Date: Fri, 8 Jan 2021 11:25:23 +0100 Subject: [PATCH 0932/1930] Add additional chinese languages --- Emby.Server.Implementations/Localization/iso6392.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Emby.Server.Implementations/Localization/iso6392.txt b/Emby.Server.Implementations/Localization/iso6392.txt index 40f8614f1b..488901822d 100644 --- a/Emby.Server.Implementations/Localization/iso6392.txt +++ b/Emby.Server.Implementations/Localization/iso6392.txt @@ -77,6 +77,8 @@ chb|||Chibcha|chibcha che||ce|Chechen|tchétchène chg|||Chagatai|djaghataï chi|zho|zh|Chinese|chinois +chi|zho|zh-tw|Chinese; Traditional|chinois +chi|zho|zh-hk|Chinese; Hong Kong|chinois chk|||Chuukese|chuuk chm|||Mari|mari chn|||Chinook jargon|chinook, jargon From cb6ae4a18855cdb688637d32c7d5cdd1aab73444 Mon Sep 17 00:00:00 2001 From: Christian <christian.engelbarts@outlook.de> Date: Fri, 8 Jan 2021 08:52:59 +0000 Subject: [PATCH 0933/1930] Translated using Weblate (German) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/de/ --- .../Localization/Core/de.json | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json index 6ab22b8a4b..4a505d0b3c 100644 --- a/Emby.Server.Implementations/Localization/Core/de.json +++ b/Emby.Server.Implementations/Localization/Core/de.json @@ -94,22 +94,22 @@ "VersionNumber": "Version {0}", "TaskDownloadMissingSubtitlesDescription": "Durchsucht das Internet nach fehlenden Untertiteln, basierend auf den Meta Einstellungen.", "TaskDownloadMissingSubtitles": "Lade fehlende Untertitel herunter", - "TaskRefreshChannelsDescription": "Erneuere Internet Kanal Informationen.", - "TaskRefreshChannels": "Erneuere Kanäle", - "TaskCleanTranscodeDescription": "Löscht Transkodierdateien welche älter als ein Tag sind.", - "TaskCleanTranscode": "Lösche Transkodier Pfad", - "TaskUpdatePluginsDescription": "Lädt Updates für Plugins herunter, welche dazu eingestellt sind automatisch zu updaten und installiert sie.", - "TaskUpdatePlugins": "Update Plugins", - "TaskRefreshPeopleDescription": "Erneuert Metadaten für Schauspieler und Regisseure in deinen Bibliotheken.", - "TaskRefreshPeople": "Erneuere Schauspieler", - "TaskCleanLogsDescription": "Lösche Log Dateien die älter als {0} Tage sind.", - "TaskCleanLogs": "Lösche Log Pfad", - "TaskRefreshLibraryDescription": "Scanne alle Bibliotheken für hinzugefügte Datein und erneuere Metadaten.", + "TaskRefreshChannelsDescription": "Aktualisiere Internet Kanal Informationen.", + "TaskRefreshChannels": "Aktualisiere Kanäle", + "TaskCleanTranscodeDescription": "Löscht Transkodierdateien, welche älter als einen Tag sind.", + "TaskCleanTranscode": "Lösche Transkodier-Pfad", + "TaskUpdatePluginsDescription": "Lädt Updates für Plugins herunter, welche für automatische Updates konfiguriert sind und installiert diese.", + "TaskUpdatePlugins": "Aktualisiere Plugins", + "TaskRefreshPeopleDescription": "Aktualisiert Metadaten für Schauspieler und Regisseure in deinen Bibliotheken.", + "TaskRefreshPeople": "Aktualisiere Schauspieler", + "TaskCleanLogsDescription": "Lösche Log Dateien, die älter als {0} Tage sind.", + "TaskCleanLogs": "Lösche Log-Verzeichnis", + "TaskRefreshLibraryDescription": "Scanne alle Bibliotheken nach neu hinzugefügten Dateien und aktualisiere Metadaten.", "TaskRefreshLibrary": "Scanne Medien-Bibliothek", - "TaskRefreshChapterImagesDescription": "Kreiert Vorschaubilder für Videos welche Kapitel haben.", + "TaskRefreshChapterImagesDescription": "Erstellt Vorschaubilder für Videos, welche Kapitel besitzen.", "TaskRefreshChapterImages": "Extrahiert Kapitel-Bilder", - "TaskCleanCacheDescription": "Löscht Zwischenspeicherdatein die nicht länger von System gebraucht werden.", - "TaskCleanCache": "Leere Cache Pfad", + "TaskCleanCacheDescription": "Löscht nicht mehr benötigte Zwischenspeicherdateien.", + "TaskCleanCache": "Leere Zwischenspeicher", "TasksChannelsCategory": "Internet Kanäle", "TasksApplicationCategory": "Anwendung", "TasksLibraryCategory": "Bibliothek", From 357429b8ea232619cdbdeda44e5f4b94c7a40f26 Mon Sep 17 00:00:00 2001 From: David <daullmer@gmail.com> Date: Fri, 8 Jan 2021 14:48:08 +0100 Subject: [PATCH 0934/1930] Add .nfo ratings tag --- .../Parsers/BaseNfoParser.cs | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index c287113c5c..2a64bb243a 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -624,6 +624,21 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "ratings": + { + if (!reader.IsEmptyElement) + { + using var subtree = reader.ReadSubtree(); + FetchFromRatingsNode(subtree, item); + } + else + { + reader.Read(); + } + + break; + } + case "aired": case "formed": case "premiered": @@ -866,6 +881,90 @@ namespace MediaBrowser.XbmcMetadata.Parsers } } + private void FetchFromRatingsNode(XmlReader reader, T item) + { + reader.MoveToContent(); + reader.Read(); + + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) + { + if (reader.NodeType == XmlNodeType.Element) + { + switch (reader.Name) + { + case "rating": + { + if (reader.IsEmptyElement) + { + reader.Read(); + continue; + } + + var ratingName = reader.GetAttribute("name"); + + using var subtree = reader.ReadSubtree(); + FetchFromRatingNode(subtree, item, ratingName); + + break; + } + + default: + reader.Skip(); + break; + } + } + else + { + reader.Read(); + } + } + } + + private void FetchFromRatingNode(XmlReader reader, T item, string? ratingName) + { + reader.MoveToContent(); + reader.Read(); + + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) + { + if (reader.NodeType == XmlNodeType.Element) + { + switch (reader.Name) + { + case "value": + var val = reader.ReadElementContentAsString(); + + if (!string.IsNullOrWhiteSpace(val)) + { + if (float.TryParse(val.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue)) + { + // if ratingName contains tomato --> assume critic rating + if (ratingName != null && ratingName.Contains("tomato", StringComparison.InvariantCultureIgnoreCase)) + { + item.CriticRating = ratingValue; + } + else + { + item.CommunityRating = ratingValue; + } + } + } + + break; + default: + reader.Skip(); + break; + } + } + else + { + reader.Read(); + } + } + } + /// <summary> /// Gets the persons from XML node. /// </summary> From 620fbf0f89d33ab5d4d66373c7f9fe4580691f22 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 9 Jan 2021 10:51:59 +0100 Subject: [PATCH 0935/1930] Remove CropWhitespace function --- Emby.Drawing/ImageProcessor.cs | 5 -- Jellyfin.Api/Controllers/ImageController.cs | 5 +- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 85 ++----------------- .../Drawing/ImageProcessingOptions.cs | 3 - 4 files changed, 6 insertions(+), 92 deletions(-) diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 8a2301d2d6..af6e5b339b 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -181,11 +181,6 @@ namespace Emby.Drawing { if (!File.Exists(cacheFilePath)) { - if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath)) - { - options.CropWhiteSpace = false; - } - string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat); if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase)) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index c606d327c5..cd12963104 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -1681,7 +1681,7 @@ namespace Jellyfin.Api.Controllers int? width, int? height, int? quality, - bool? cropWhitespace, + bool? cropWhitespace, // TODO: Remove bool? addPlayedIndicator, int? blur, string? backgroundColor, @@ -1756,7 +1756,6 @@ namespace Jellyfin.Api.Controllers backgroundColor, foregroundLayer, imageInfo, - cropWhitespace.Value, outputFormats, cacheDuration, responseHeaders, @@ -1855,7 +1854,6 @@ namespace Jellyfin.Api.Controllers string? backgroundColor, string? foregroundLayer, ItemImageInfo imageInfo, - bool cropWhitespace, IReadOnlyCollection<ImageFormat> supportedFormats, TimeSpan? cacheDuration, IDictionary<string, string> headers, @@ -1868,7 +1866,6 @@ namespace Jellyfin.Api.Controllers var options = new ImageProcessingOptions { - CropWhiteSpace = cropWhitespace, Height = height, ImageIndex = index ?? 0, Image = imageInfo, diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index eab5777d5d..a786c01a60 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -91,9 +91,6 @@ namespace Jellyfin.Drawing.Skia } } - private static bool IsTransparent(SKColor color) - => (color.Red == 255 && color.Green == 255 && color.Blue == 255) || color.Alpha == 0; - /// <summary> /// Convert a <see cref="ImageFormat"/> to a <see cref="SKEncodedImageFormat"/>. /// </summary> @@ -111,65 +108,6 @@ namespace Jellyfin.Drawing.Skia }; } - private static bool IsTransparentRow(SKBitmap bmp, int row) - { - for (var i = 0; i < bmp.Width; ++i) - { - if (!IsTransparent(bmp.GetPixel(i, row))) - { - return false; - } - } - - return true; - } - - private static bool IsTransparentColumn(SKBitmap bmp, int col) - { - for (var i = 0; i < bmp.Height; ++i) - { - if (!IsTransparent(bmp.GetPixel(col, i))) - { - return false; - } - } - - return true; - } - - private SKBitmap CropWhiteSpace(SKBitmap bitmap) - { - var topmost = 0; - while (topmost < bitmap.Height && IsTransparentRow(bitmap, topmost)) - { - topmost++; - } - - int bottommost = bitmap.Height; - while (bottommost >= 0 && IsTransparentRow(bitmap, bottommost - 1)) - { - bottommost--; - } - - var leftmost = 0; - while (leftmost < bitmap.Width && IsTransparentColumn(bitmap, leftmost)) - { - leftmost++; - } - - var rightmost = bitmap.Width; - while (rightmost >= 0 && IsTransparentColumn(bitmap, rightmost - 1)) - { - rightmost--; - } - - var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost); - - using var image = SKImage.FromBitmap(bitmap); - using var subset = image.Subset(newRect); - return SKBitmap.FromImage(subset); - } - /// <inheritdoc /> /// <exception cref="ArgumentNullException">The path is null.</exception> /// <exception cref="FileNotFoundException">The path is not valid.</exception> @@ -312,22 +250,11 @@ namespace Jellyfin.Drawing.Skia return resultBitmap; } - private SKBitmap? GetBitmap(string path, bool cropWhitespace, bool forceAnalyzeBitmap, ImageOrientation? orientation, out SKEncodedOrigin origin) - { - if (cropWhitespace) - { - using var bitmap = Decode(path, forceAnalyzeBitmap, orientation, out origin); - return bitmap == null ? null : CropWhiteSpace(bitmap); - } - - return Decode(path, forceAnalyzeBitmap, orientation, out origin); - } - - private SKBitmap? GetBitmap(string path, bool cropWhitespace, bool autoOrient, ImageOrientation? orientation) + private SKBitmap? GetBitmap(string path, bool autoOrient, ImageOrientation? orientation) { if (autoOrient) { - var bitmap = GetBitmap(path, cropWhitespace, true, orientation, out var origin); + var bitmap = Decode(path, true, orientation, out var origin); if (bitmap != null && origin != SKEncodedOrigin.TopLeft) { @@ -340,7 +267,7 @@ namespace Jellyfin.Drawing.Skia return bitmap; } - return GetBitmap(path, cropWhitespace, false, orientation, out _); + return Decode(path, false, orientation, out _); } private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin) @@ -466,7 +393,7 @@ namespace Jellyfin.Drawing.Skia var blur = options.Blur ?? 0; var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0); - using var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation); + using var bitmap = GetBitmap(inputPath, autoOrient, orientation); if (bitmap == null) { throw new InvalidDataException($"Skia unable to read image {inputPath}"); @@ -474,9 +401,7 @@ namespace Jellyfin.Drawing.Skia var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height); - if (!options.CropWhiteSpace - && options.HasDefaultOptions(inputPath, originalImageSize) - && !autoOrient) + if (options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient) { // Just spit out the original file if all the options are default return inputPath; diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 22105b7d79..22de9a43e8 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -24,8 +24,6 @@ namespace MediaBrowser.Controller.Drawing public int ImageIndex { get; set; } - public bool CropWhiteSpace { get; set; } - public int? Width { get; set; } public int? Height { get; set; } @@ -106,7 +104,6 @@ namespace MediaBrowser.Controller.Drawing PercentPlayed.Equals(0) && !UnplayedCount.HasValue && !Blur.HasValue && - !CropWhiteSpace && string.IsNullOrEmpty(BackgroundColor) && string.IsNullOrEmpty(ForegroundLayer); } From d07eef4f2560b5070b211f59cb381d205df1c9c3 Mon Sep 17 00:00:00 2001 From: Bond_009 <bond.009@outlook.com> Date: Sat, 9 Jan 2021 15:00:59 +0100 Subject: [PATCH 0936/1930] Add tests for NFO parsers --- .../Entities/PersonInfo.cs | 2 +- .../Providers/IProviderManager.cs | 17 +- .../Parsers/BaseItemXmlParser.cs | 3 +- .../Parsers/BaseNfoParser.cs | 121 ++++++++- .../Parsers/MovieNfoParser.cs | 2 +- MediaBrowser.sln | 9 +- .../LiveTv/HdHomerunHostTests.cs | 1 - .../Jellyfin.XbmcMetadata.Tests.csproj | 40 +++ .../Parsers/MovieNfoParserTests.cs | 80 ++++++ .../Test Data/Justice League.nfo | 230 ++++++++++++++++++ 10 files changed, 487 insertions(+), 18 deletions(-) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo diff --git a/MediaBrowser.Controller/Entities/PersonInfo.cs b/MediaBrowser.Controller/Entities/PersonInfo.cs index 4ff9b0955c..4a5e93f794 100644 --- a/MediaBrowser.Controller/Entities/PersonInfo.cs +++ b/MediaBrowser.Controller/Entities/PersonInfo.cs @@ -42,7 +42,7 @@ namespace MediaBrowser.Controller.Entities /// <value>The sort order.</value> public int? SortOrder { get; set; } - public string ImageUrl { get; set; } + public string? ImageUrl { get; set; } public Dictionary<string, string> ProviderIds { get; set; } diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 0a4967223f..271f7fdadb 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -6,9 +6,7 @@ using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using Jellyfin.Data.Entities; using Jellyfin.Data.Events; -using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Configuration; @@ -22,6 +20,12 @@ namespace MediaBrowser.Controller.Providers /// </summary> public interface IProviderManager { + event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted; + + event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted; + + event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress; + /// <summary> /// Queues the refresh. /// </summary> @@ -132,12 +136,13 @@ namespace MediaBrowser.Controller.Providers /// </summary> /// <param name="item">The item.</param> /// <param name="updateType">Type of the update.</param> - /// <returns>Task.</returns> void SaveMetadata(BaseItem item, ItemUpdateType updateType); /// <summary> /// Saves the metadata. /// </summary> + /// <param name="item">The item.</param> + /// <param name="updateType">Type of the update.</param> void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable<string> savers); /// <summary> @@ -179,12 +184,6 @@ namespace MediaBrowser.Controller.Providers void OnRefreshComplete(BaseItem item); double? GetRefreshProgress(Guid id); - - event EventHandler<GenericEventArgs<BaseItem>> RefreshStarted; - - event EventHandler<GenericEventArgs<BaseItem>> RefreshCompleted; - - event EventHandler<GenericEventArgs<Tuple<BaseItem, double>>> RefreshProgress; } public enum RefreshPriority diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 5d3ab30d39..b0afb834b1 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -344,8 +344,7 @@ namespace MediaBrowser.LocalMetadata.Parsers { var val = reader.ReadElementContentAsString(); - var hasAspectRatio = item as IHasAspectRatio; - if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null) + if (!string.IsNullOrWhiteSpace(val) && item is IHasAspectRatio hasAspectRatio) { hasAspectRatio.AspectRatio = val; } diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index c287113c5c..a675173a92 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -635,7 +635,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850) + if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850) { item.PremiereDate = date.ToUniversalTime(); item.ProductionYear = date.Year; @@ -653,7 +653,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850) + if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850) { item.EndDate = date.ToUniversalTime(); } @@ -797,6 +797,22 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "subtitle": + { + if (reader.IsEmptyElement) + { + reader.Read(); + continue; + } + + using (var subtree = reader.ReadSubtree()) + { + FetchFromSubtitleNode(subtree, item); + } + + break; + } + default: reader.Skip(); break; @@ -854,6 +870,90 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "aspect": + { + var val = reader.ReadElementContentAsString(); + + if (item is Video video) + { + video.AspectRatio = val; + } + + break; + } + + case "width": + { + var val = reader.ReadElementContentAsInt(); + + if (item is Video video) + { + video.Width = val; + } + + break; + } + + case "height": + { + var val = reader.ReadElementContentAsInt(); + + if (item is Video video) + { + video.Height = val; + } + + break; + } + + case "durationinseconds": + { + var val = reader.ReadElementContentAsInt(); + + if (item is Video video) + { + video.RunTimeTicks = new TimeSpan(0, 0, val).Ticks; + } + + break; + } + + default: + reader.Skip(); + break; + } + } + else + { + reader.Read(); + } + } + } + + private void FetchFromSubtitleNode(XmlReader reader, T item) + { + reader.MoveToContent(); + reader.Read(); + + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) + { + if (reader.NodeType == XmlNodeType.Element) + { + switch (reader.Name) + { + case "language": + { + _ = reader.ReadElementContentAsString(); + + if (item is Video video) + { + video.HasSubtitles = true; + } + + break; + } + default: reader.Skip(); break; @@ -877,6 +977,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers var type = PersonType.Actor; // If type is not specified assume actor var role = string.Empty; int? sortOrder = null; + string? imageUrl = null; reader.MoveToContent(); reader.Read(); @@ -904,6 +1005,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "order": case "sortorder": { var val = reader.ReadElementContentAsString(); @@ -919,6 +1021,18 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "thumb": + { + var val = reader.ReadElementContentAsString(); + + if (!string.IsNullOrWhiteSpace(val)) + { + imageUrl = val; + } + + break; + } + default: reader.Skip(); break; @@ -935,7 +1049,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers Name = name.Trim(), Role = role, Type = type, - SortOrder = sortOrder + SortOrder = sortOrder, + ImageUrl = imageUrl }; } diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 15a2fb63ea..33b0ae887f 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -75,7 +75,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val) && movie != null) { // TODO Handle this better later - if (val.IndexOf('<', StringComparison.Ordinal) == -1) + if (!val.Contains('<', StringComparison.Ordinal)) { movie.CollectionName = val; } diff --git a/MediaBrowser.sln b/MediaBrowser.sln index c654e8ef36..4e6687cceb 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -1,4 +1,4 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -72,6 +72,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -194,6 +196,10 @@ Global {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.Build.0 = Debug|Any CPU {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.ActiveCfg = Release|Any CPU {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.Build.0 = Release|Any CPU + {30922383-D513-4F4D-B890-A940B57FA353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {30922383-D513-4F4D-B890-A940B57FA353}.Debug|Any CPU.Build.0 = Debug|Any CPU + {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.ActiveCfg = Release|Any CPU + {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -207,6 +213,7 @@ Global {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {30922383-D513-4F4D-B890-A940B57FA353} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs index fb7cf6a471..75939526dc 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -1,5 +1,4 @@ using System; -using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj new file mode 100644 index 0000000000..c258fd8ed0 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -0,0 +1,40 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net5.0</TargetFramework> + <IsPackable>false</IsPackable> + <TreatWarningsAsErrors>true</TreatWarningsAsErrors> + <Nullable>enable</Nullable> + </PropertyGroup> + + <ItemGroup> + <None Include="Test Data\**\*.*"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> + </ItemGroup> + + <ItemGroup> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" /> + <PackageReference Include="Moq" Version="4.15.2" /> + <PackageReference Include="xunit" Version="2.4.1" /> + <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> + <PackageReference Include="coverlet.collector" Version="1.3.0" /> + </ItemGroup> + + <!-- Code Analyzers --> + <ItemGroup Condition=" '$(Configuration)' == 'Debug' "> + <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" /> + <PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" /> + <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="All" /> + <PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="../../MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj" /> + </ItemGroup> + + <PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> + <CodeAnalysisRuleSet>../jellyfin-tests.ruleset</CodeAnalysisRuleSet> + </PropertyGroup> + +</Project> diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs new file mode 100644 index 0000000000..7d6b70f939 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -0,0 +1,80 @@ +using System; +using System.Linq; +using System.Threading; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.XbmcMetadata.Parsers; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.XbmcMetadata.Parsers.Tests +{ + public class MovieNfoParserTests + { + [Fact] + public void Fetch_Valid_Succes() + { + var providerManager = new Mock<IProviderManager>(); + providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny<IHasProviderIds>())) + .Returns(Enumerable.Empty<ExternalIdInfo>()); + var config = new Mock<IConfigurationManager>(); + config.Setup(x => x.GetConfiguration(It.IsAny<string>())) + .Returns(new XbmcMetadataOptions()); + var parser = new MovieNfoParser(new NullLogger<MovieNfoParser>(), config.Object, providerManager.Object); + + var result = new MetadataResult<Video>() + { + Item = new Video() + }; + parser.Fetch(result, "Test Data/Justice League.nfo", CancellationToken.None); + var item = result.Item; + + Assert.Equal("Justice League", item.OriginalTitle); + Assert.Equal("Justice for all.", item.Tagline); + Assert.Equal("tt0974015", item.ProviderIds["imdb"]); + + Assert.Equal(4, item.Genres.Length); + Assert.Contains("Action", item.Genres); + Assert.Contains("Adventure", item.Genres); + Assert.Contains("Fantasy", item.Genres); + Assert.Contains("Sci-Fi", item.Genres); + + Assert.Equal(new DateTime(2017, 11, 15), item.PremiereDate); + Assert.Single(item.Studios); + Assert.Contains("DC Comics", item.Studios); + + Assert.Equal("1.777778", item.AspectRatio); + Assert.Equal(1920, item.Width); + Assert.Equal(1080, item.Height); + Assert.Equal(new TimeSpan(0, 0, 6268).Ticks, item.RunTimeTicks); + Assert.True(item.HasSubtitles); + + Assert.Equal(18, result.People.Count); + + var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray(); + Assert.Equal(2, writers.Length); + var writerNames = writers.Select(x => x.Name); + Assert.Contains("Jerry Siegel", writerNames); + Assert.Contains("Joe Shuster", writerNames); + + var directors = result.People.Where(x => x.Type == PersonType.Director).ToArray(); + Assert.Single(directors); + Assert.Equal("Zack Snyder", directors[0].Name); + + var actors = result.People.Where(x => x.Type == PersonType.Actor).ToArray(); + Assert.Equal(15, actors.Length); + + // Only test one actor + var aquaman = actors.FirstOrDefault(x => x.Role.Equals("Aquaman", StringComparison.Ordinal)); + Assert.NotNull(aquaman); + Assert.Equal("Jason Momoa", aquaman!.Name); + Assert.Equal(5, aquaman!.SortOrder); + Assert.Equal("https://m.media-amazon.com/images/M/MV5BMTI5MTU5NjM1MV5BMl5BanBnXkFtZTcwODc4MDk0Mw@@._V1_SX1024_SY1024_.jpg", aquaman!.ImageUrl); + } + } +} diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo new file mode 100644 index 0000000000..f838af8d04 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo @@ -0,0 +1,230 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> +<movie> + <title>Justice League + Justice League + + + 6.400000 + 335583 + + + 4.500000 + 52 + + + 6.200000 + 7788 + + + 7.6 + 71 + + + 6.2 + 119873 + + + 0 + 0 + Fueled by his restored faith in humanity and inspired by Superman's selfless act, Bruce Wayne enlists the help of his new-found ally, Diana Prince, to face an even greater enemy. + Fueled by his restored faith in humanity and inspired by Superman's selfless act, Bruce Wayne enlists the help of his newfound ally, Diana Prince, to face an even greater enemy. Together, Batman and Wonder Woman work quickly to find and recruit a team of meta-humans to stand against this newly awakened threat. But despite the formation of this unprecedented league of heroes-Batman, Wonder Woman, Aquaman, Cyborg and The Flash-it may already be too late to save the planet from an assault of catastrophic proportions. + Justice for all. + 120 + https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg + https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg + https://assets.fanart.tv/fanart/movies/468551/hdmovielogo/justice-league-collection-5ba855ed4239a.png + https://assets.fanart.tv/fanart/movies/468551/hdmovieclearart/justice-league-collection-5c24eae8d4d71.png + https://assets.fanart.tv/fanart/movies/468551/moviethumb/justice-league-collection-5c24ebc7d0d2b.jpg + http://image.tmdb.org/t/p/original/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg + http://image.tmdb.org/t/p/original/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg + http://image.tmdb.org/t/p/original/cigoYpXWgYYgsIsEPwMneVYpuwo.jpg + http://image.tmdb.org/t/p/original/2ZOCiOdAOVSKsFjC1Vl2ZlANrPj.jpg + http://image.tmdb.org/t/p/original/7iO1C4c5igXsB6AyxnqsCPv6fiq.jpg + http://image.tmdb.org/t/p/original/vyxOJuk6cxrRcGzuMRbDTpwji1w.jpg + http://image.tmdb.org/t/p/original/9rtrRGeRnL0JKtu9IMBWsmlmmZz.jpg + http://image.tmdb.org/t/p/original/eRoXqOzciHkSPs1Z8pGnJMZo0Zb.jpg + http://image.tmdb.org/t/p/original/aQkEdqaXVxYObMLeoBSAUcgkxLs.jpg + http://image.tmdb.org/t/p/original/4lo1fTexk2eNIeQx3Tp74kN7ASE.jpg + http://image.tmdb.org/t/p/original/fF94rvT1kJpVzIE2aSYgYj9B3pc.jpg + http://image.tmdb.org/t/p/original/uwegp70cWe16EtwsSjbL6ShPenG.jpg + http://image.tmdb.org/t/p/original/exLtrlI7JjKcfQVTccI7XdQRFMz.jpg + http://image.tmdb.org/t/p/original/paLcue01KpfQftorfjKqqD4qvlL.jpg + http://image.tmdb.org/t/p/original/yVDIfiKIsCbdFcgLXW34bAsnQvy.jpg + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57b476a831d74.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57947e28cf10b.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5863d5c0cf0c9.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5a801747e5545.png + https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5cd75683df92b.png + https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-586017e95adbd.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5934d45bc6592.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-5aa9289a379fa.jpg + https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585fb155c3743.jpg + https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585edbda91d82.jpg + https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5b86588882c12.jpg + https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-5bbb9babe600c.jpg + https://assets.fanart.tv/fanart/movies/141052/hdmovieclearart/justice-league-5865c23193041.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-58690967b9765.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a953ca4db6a6.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a0b913c233be.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png + https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-59dc595362ef1.png + + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-58fa1f1932897.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a14f5fd8dd16.jpg + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a119394ea362.jpg + + Australia:M + 0 + + tt0974015 + tt0974015 + Action + Adventure + Fantasy + Sci-Fi + USA + Canada + UK + + Justice League Collection + Based on the DC Comics superhero team + + Jerry Siegel + Joe Shuster + Zack Snyder + 2017-11-15 + 2017 + + + + DC Comics + + + + + + + + eng + + + + + Ben Affleck + Batman + 0 + https://m.media-amazon.com/images/M/MV5BMTI4MzIxMTk0Nl5BMl5BanBnXkFtZTcwOTU5NjA0Mg@@._V1_SX1024_SY1024_.jpg + + + Henry Cavill + Superman + 1 + https://m.media-amazon.com/images/M/MV5BMTUxNTExMzUzOF5BMl5BanBnXkFtZTgwOTI1MjA3OTE@._V1_SX1024_SY1024_.jpg + + + Amy Adams + Lois Lane + 2 + https://m.media-amazon.com/images/M/MV5BMTg2NTk2MTgxMV5BMl5BanBnXkFtZTgwNjcxMjAzMTI@._V1_SX1024_SY1024_.jpg + + + Gal Gadot + Wonder Woman + 3 + https://m.media-amazon.com/images/M/MV5BMjUzZTJmZDItODRjYS00ZGRhLTg2NWQtOGE0YjJhNWVlMjNjXkEyXkFqcGdeQXVyMTg4NDI0NDM@._V1_SX1024_SY1024_.jpg + + + Ezra Miller + The Flash + 4 + https://m.media-amazon.com/images/M/MV5BMjEwMjQ3ODgxOV5BMl5BanBnXkFtZTgwNzc4NjE4NTE@._V1_SX1024_SY1024_.jpg + + + Jason Momoa + Aquaman + 5 + https://m.media-amazon.com/images/M/MV5BMTI5MTU5NjM1MV5BMl5BanBnXkFtZTcwODc4MDk0Mw@@._V1_SX1024_SY1024_.jpg + + + Ray Fisher + Cyborg + 6 + https://m.media-amazon.com/images/M/MV5BYzdhMzkyYTgtMjQzMC00ODhmLWExZmItNTU4MDVlMzY2NzgwXkEyXkFqcGdeQXVyNzA5NjQ5MDk@._V1_SX1024_SY1024_.jpg + + + Jeremy Irons + Alfred + 7 + https://m.media-amazon.com/images/M/MV5BMTY5Mzg2NDY5OV5BMl5BanBnXkFtZTcwMDQwNzA0Mg@@._V1_SX1024_SY1024_.jpg + + + Diane Lane + Martha Kent + 8 + https://m.media-amazon.com/images/M/MV5BMzM5ODM1ZWMtZjcyYy00MzgzLWJmMGQtZWY5OGQyNTRiODIxXkEyXkFqcGdeQXVyOTE0NjgwMjY@._V1_SX1024_SY1024_.jpg + + + Connie Nielsen + Queen Hippolyta + 9 + https://m.media-amazon.com/images/M/MV5BYzZiYTQ4YTAtMzRkMi00ZDZlLWFkZWItNGI2ZTIyODRiYTc4XkEyXkFqcGdeQXVyMjUzMjc2MjE@._V1_SX1024_SY1024_.jpg + + + J.K. Simmons + Commissioner Gordon + 10 + https://m.media-amazon.com/images/M/MV5BMzg2NTI5NzQ1MV5BMl5BanBnXkFtZTgwNjI1NDEwMDI@._V1_SX1024_SY1024_.jpg + + + Ciarán Hinds + Steppenwolf + 11 + https://m.media-amazon.com/images/M/MV5BMTIyNjM0MzU0NF5BMl5BanBnXkFtZTcwOTIxMzg1MQ@@._V1_SX1024_SY1024_.jpg + + + Amber Heard + Mera + 12 + https://m.media-amazon.com/images/M/MV5BMjA4NDkyODA3M15BMl5BanBnXkFtZTgwMzUzMjYzNzM@._V1_SX1024_SY1024_.jpg + + + Joe Morton + Silas Stone + 13 + https://m.media-amazon.com/images/M/MV5BMTQ1MjYwMTQ2MF5BMl5BanBnXkFtZTgwNzI4MTA0NDE@._V1_SX1024_SY1024_.jpg + + + Lisa Loven Kongsli + Menalippe + 14 + https://m.media-amazon.com/images/M/MV5BOTFjOTFhNTgtZjk3Ny00MTNjLWE3MWUtMWI3ZWM5NDljZjQwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_SX1024_SY1024_.jpg + + + 0.000000 + 0.000000 + + Justice League + 2019-08-06 09:01:18 + From 3a9ce6d36694718a190d22019d94295695daaec4 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 9 Jan 2021 15:08:48 +0100 Subject: [PATCH 0937/1930] Fix release build --- MediaBrowser.Controller/Entities/PersonInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/Entities/PersonInfo.cs b/MediaBrowser.Controller/Entities/PersonInfo.cs index 4a5e93f794..4ff9b0955c 100644 --- a/MediaBrowser.Controller/Entities/PersonInfo.cs +++ b/MediaBrowser.Controller/Entities/PersonInfo.cs @@ -42,7 +42,7 @@ namespace MediaBrowser.Controller.Entities /// The sort order. public int? SortOrder { get; set; } - public string? ImageUrl { get; set; } + public string ImageUrl { get; set; } public Dictionary ProviderIds { get; set; } From be511ca162648b722b2b4b2f543d947d63f2c57e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 9 Jan 2021 15:14:26 +0100 Subject: [PATCH 0938/1930] Fix release build ... again --- MediaBrowser.Controller/Providers/IProviderManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 271f7fdadb..2f5b1d4a32 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -143,6 +143,7 @@ namespace MediaBrowser.Controller.Providers /// /// The item. /// Type of the update. + /// The metadata savers. void SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable savers); /// From 262c6ae249b91d3fb986994a369cb83aafeb1ce8 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 9 Jan 2021 15:33:39 +0100 Subject: [PATCH 0939/1930] Remove ',' hack --- MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 2a64bb243a..2954868fcd 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -938,10 +938,10 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - if (float.TryParse(val.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue)) + if (float.TryParse(val, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue)) { // if ratingName contains tomato --> assume critic rating - if (ratingName != null && ratingName.Contains("tomato", StringComparison.InvariantCultureIgnoreCase)) + if (ratingName != null && ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase)) { item.CriticRating = ratingValue; } From 585821954da6971209c0baab424551d91fcf7fd8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 9 Jan 2021 20:14:50 +0100 Subject: [PATCH 0940/1930] Add tests for series nfo --- .../Parsers/BaseNfoParser.cs | 44 +++-- .../Parsers/MovieNfoParserTests.cs | 35 +++- .../Parsers/SeriesNfoParserTests.cs | 91 +++++++++ .../Test Data/American Gods.nfo | 185 ++++++++++++++++++ 4 files changed, 332 insertions(+), 23 deletions(-) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/American Gods.nfo diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index a675173a92..3e12c57576 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -63,14 +63,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// metadataFile is null or empty. public void Fetch(MetadataResult item, string metadataFile, CancellationToken cancellationToken) { - if (item == null) + if (item.Item == null) { - throw new ArgumentNullException(nameof(item)); + throw new ArgumentException("Item can't be null.", nameof(item)); } if (string.IsNullOrEmpty(metadataFile)) { - throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile)); + throw new ArgumentException("The metadata filepath was empty.", nameof(metadataFile)); } _validProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -270,17 +270,13 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var added)) - { - item.DateCreated = added.ToUniversalTime(); - } - else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added)) + if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var added)) { item.DateCreated = added.ToUniversalTime(); } else { - Logger.LogWarning("Invalid Added value found: " + val); + Logger.LogWarning("Invalid Added value found: {Value}", val); } } @@ -384,16 +380,8 @@ namespace MediaBrowser.XbmcMetadata.Parsers } case "tagline": - { - var val = reader.ReadElementContentAsString(); - - if (!string.IsNullOrWhiteSpace(val)) - { - item.Tagline = val; - } - - break; - } + item.Tagline = reader.ReadElementContentAsString(); + break; case "country": { @@ -710,6 +698,24 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "uniqueid": + { + if (reader.IsEmptyElement) + { + reader.Read(); + break; + } + + var provider = reader.GetAttribute("type"); + var id = reader.ReadElementContentAsString(); + if (!string.IsNullOrWhiteSpace(provider) && !string.IsNullOrWhiteSpace(id)) + { + item.SetProviderId(provider, id); + } + + break; + } + default: string readerName = reader.Name; if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue)) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 7d6b70f939..7651653a1b 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -16,8 +16,9 @@ namespace Jellyfin.XbmcMetadata.Parsers.Tests { public class MovieNfoParserTests { - [Fact] - public void Fetch_Valid_Succes() + private readonly MovieNfoParser _parser; + + public MovieNfoParserTests() { var providerManager = new Mock(); providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny())) @@ -25,13 +26,18 @@ namespace Jellyfin.XbmcMetadata.Parsers.Tests var config = new Mock(); config.Setup(x => x.GetConfiguration(It.IsAny())) .Returns(new XbmcMetadataOptions()); - var parser = new MovieNfoParser(new NullLogger(), config.Object, providerManager.Object); + _parser = new MovieNfoParser(new NullLogger(), config.Object, providerManager.Object); + } + [Fact] + public void Fetch_Valid_Succes() + { var result = new MetadataResult public bool IsIP4Enabled { get; set; } + /// + /// Gets or sets a value indicating whether the system has IP4 is enabled. + /// + public bool SystemIP4Enabled { get; set; } + + /// + /// Gets or sets a value indicating whether the system has IP6 is enabled. + /// + public bool SystemIP6Enabled { get; set; } + /// public Collection RemoteAddressFilter { get; private set; } @@ -185,6 +195,15 @@ namespace Jellyfin.Networking.Manager return _macAddresses; } + /// + /// REMOVE after debugging. + /// + /// Message. + public void Log(string msg) + { + _logger.LogInformation(msg); + } + /// public bool IsGatewayInterface(IPObject? addressObj) { @@ -1047,47 +1066,55 @@ namespace Jellyfin.Networking.Manager // populate interface address list foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) { - if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + if (info.Address.AddressFamily == AddressFamily.InterNetwork) { - IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) + SystemIP4Enabled = true; + if (IsIP4Enabled) { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv4Properties().Index - }; + IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv4Properties().Index + }; - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } - - _interfaceAddresses.AddItem(nw); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } - else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + else if (info.Address.AddressFamily == AddressFamily.InterNetworkV6) { - IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) + SystemIP6Enabled = true; + if (IsIP6Enabled) { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv6Properties().Index - }; + IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) + { + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv6Properties().Index + }; - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; + } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } - - _interfaceAddresses.AddItem(nw); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } } } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index bbfc4fbd4c..4f6329f824 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -1,9 +1,12 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net; +using System.Net.Sockets; using System.Reflection; +using System.Text; using Emby.Server.Implementations; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.DefaultAuthorizationPolicy; @@ -20,6 +23,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; +using Jellyfin.Networking.Configuration; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -169,36 +173,124 @@ namespace Jellyfin.Server.Extensions .AddScheme(AuthenticationSchemes.CustomAuthentication, null); } + /// + /// Sets up the proxy configuration based on the addresses in . + /// + /// The instance. + /// The containing the config settings. + /// The string array to parse. + /// The instance. + public static void ParseList(INetworkManager networkManager, NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) + { + for (var i = 0; i < userList.Length; i++) + { + if (IPNetAddress.TryParse(userList[i], out var addr)) + { + if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) + || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + { + continue; + } + + if (networkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) + { + // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. + // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . + addr.Address = addr.Address.MapToIPv6(); + } + + if (addr.PrefixLength == 32) + { + options.KnownProxies.Add(addr.Address); + } + else + { + options.KnownNetworks.Add(new IPNetwork(addr.Address, addr.PrefixLength)); + } + } + else if (IPHost.TryParse(userList[i], out var host)) + { + foreach (var address in host.GetAddresses()) + { + if ((!config.EnableIPV4 && host.AddressFamily == AddressFamily.InterNetwork) + || (!config.EnableIPV6 && host.AddressFamily == AddressFamily.InterNetworkV6)) + { + continue; + } + + var hostAddr = address; + if (networkManager.SystemIP6Enabled && address.AddressFamily == AddressFamily.InterNetwork) + { + // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. + // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . + hostAddr = address.MapToIPv6(); + } + + options.KnownProxies.Add(hostAddr); + } + } + } + } + + private static string EnumToString(IEnumerable x) + { + var sb = new StringBuilder(); + foreach (var item in x) + { + if (item is IPAddress ipItem) + { + sb.Append(ipItem.ToString()); + } + else if (item is IPNetwork ipNetwork) + { + sb.Append(ipNetwork.Prefix.ToString()); + sb.Append('/'); + sb.Append(ipNetwork.PrefixLength.ToString(CultureInfo.InvariantCulture)); + sb.Append(','); + } + } + + return sb.ToString(); + } + /// /// Extension method for adding the jellyfin API to the service collection. /// /// The service collection. /// An IEnumerable containing all plugin assemblies with API controllers. - /// A list of all known proxies to trust for X-Forwarded-For. + /// The . + /// The instance. /// The MVC builder. - public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable pluginAssemblies, IReadOnlyList knownProxies) + public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable pluginAssemblies, NetworkConfiguration config, INetworkManager networkManager) { IMvcBuilder mvcBuilder = serviceCollection - .AddCors() - .AddTransient() - .Configure(options => + .AddCors() + .AddTransient() + .Configure(options => { + // https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs + // Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues. + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; - if (knownProxies.Count == 0) + if (config.KnownProxies.Length == 0) { - options.KnownNetworks.Clear(); options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); } else { - for (var i = 0; i < knownProxies.Count; i++) - { - if (IPHost.TryParse(knownProxies[i], out var host)) - { - options.KnownProxies.Add(host.Address); - } - } + ParseList(networkManager, config, config.KnownProxies, options); + networkManager.Log("KnownProxies: " + EnumToString(options.KnownProxies)); + networkManager.Log("KnownNetworks: " + EnumToString(options.KnownNetworks)); } + + // Only set forward limit if we have some known proxies or some known networks. + if (options.KnownProxies.Count != 0 || options.KnownNetworks.Count != 0) + { + options.ForwardLimit = null; + } + + networkManager.Log("Forward Limit : " + options.ForwardLimit?.ToString(CultureInfo.CurrentCulture) ?? "None"); }) .AddMvc(opts => { diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 3395d2413f..05228ccaab 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -26,18 +26,22 @@ namespace Jellyfin.Server { private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IServerApplicationHost _serverApplicationHost; + private readonly INetworkManager _networkManager; /// /// Initializes a new instance of the class. /// /// The server configuration manager. /// The server application host. + /// The network manager. public Startup( IServerConfigurationManager serverConfigurationManager, - IServerApplicationHost serverApplicationHost) + IServerApplicationHost serverApplicationHost, + INetworkManager networkManager) { _serverConfigurationManager = serverConfigurationManager; _serverApplicationHost = serverApplicationHost; + _networkManager = networkManager; } /// @@ -52,7 +56,7 @@ namespace Jellyfin.Server { options.HttpsPort = _serverApplicationHost.HttpsPort; }); - services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration().KnownProxies); + services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration(), _networkManager); services.AddJellyfinApiSwagger(); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index b6c390d239..455fbe27a6 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -44,6 +44,16 @@ namespace MediaBrowser.Common.Net /// bool IsIP4Enabled { get; set; } + /// + /// Gets or sets a value indicating whether the system has IP4 is enabled. + /// + public bool SystemIP4Enabled { get; set; } + + /// + /// Gets or sets a value indicating whether the system has IP6 is enabled. + /// + public bool SystemIP6Enabled { get; set; } + /// /// Calculates the list of interfaces to use for Kestrel. /// @@ -229,5 +239,11 @@ namespace MediaBrowser.Common.Net /// Optional filter for the list. /// Returns a filtered list of LAN addresses. Collection GetFilteredLANSubnets(Collection? filter = null); + + /// + /// REMOVE after debugging. + /// + /// Message. + void Log(string msg); } } diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs new file mode 100644 index 0000000000..3a9f0a0790 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading.Tasks; +using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Manager; +using Jellyfin.Server.Extensions; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests +{ + public class ParseNetworkTests + { + private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) + { + var configManager = new Mock + { + CallBase = true + }; + configManager.Setup(x => x.GetConfiguration(It.IsAny())).Returns(conf); + return (IConfigurationManager)configManager.Object; + } + + private static NetworkManager CreateNetworkManager() + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + }; + + return new NetworkManager(GetMockConfig(conf), new NullLogger()); + } + + /// + /// Order of the result has always got to be hosts, then networks. + /// + /// IP4 enabled. + /// IP6 enabled. + /// List to parse. + /// What it should match. + [Theory] + [InlineData(true, true, "192.168.0.0/16,www.yahoo.co.uk", "::ffff:212.82.100.150,::ffff:192.168.0.0/16")] + [InlineData(true, false, "192.168.0.0/16,www.yahoo.co.uk", "212.82.100.150,192.168.0.0/16")] + [InlineData(true, true, "192.168.t,127.0.0.1,1234.1232.12.1234", "::ffff:127.0.0.1")] + [InlineData(true, false, "192.168.x,127.0.0.1,1234.1232.12.1234", "127.0.0.1")] + [InlineData(true, true, "::1", "::1/128")] + public void TestNetworks(bool ip4, bool ip6, string hostList, string match) + { + using var nm = CreateNetworkManager(); + nm.SystemIP6Enabled = ip6; + + var settings = new NetworkConfiguration(); + settings.EnableIPV4 = ip4; + settings.EnableIPV6 = ip6; + + var result = match + ','; + ForwardedHeadersOptions options = new ForwardedHeadersOptions(); + + // Need this here as ::1 and 127.0.0.1 are in them by default. + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + + ApiServiceCollectionExtensions.ParseList(nm, settings, hostList.Split(","), options); + + var sb = new StringBuilder(); + foreach (var item in options.KnownProxies) + { + sb.Append(item.ToString()); + sb.Append(','); + } + + foreach (var item in options.KnownNetworks) + { + sb.Append(item.Prefix.ToString()); + sb.Append('/'); + sb.Append(item.PrefixLength.ToString(CultureInfo.InvariantCulture)); + sb.Append(','); + } + + if (!string.Equals(sb.ToString(), result, StringComparison.OrdinalIgnoreCase)) + { + throw new Exception("Not matched: " + sb.ToString() + " does not match " + result); + } + } + } +} From 2979c8dd377bf0948be00082b97416b38c21de56 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 13:23:10 +0000 Subject: [PATCH 0946/1930] Fixed test on Mac --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 2 +- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 4f6329f824..2d03c129e2 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -274,8 +274,8 @@ namespace Jellyfin.Server.Extensions options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; if (config.KnownProxies.Length == 0) { - options.KnownProxies.Clear(); options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); } else { diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index 3a9f0a0790..f4ea45cc2b 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -48,8 +48,8 @@ namespace Jellyfin.Api.Tests /// List to parse. /// What it should match. [Theory] - [InlineData(true, true, "192.168.0.0/16,www.yahoo.co.uk", "::ffff:212.82.100.150,::ffff:192.168.0.0/16")] - [InlineData(true, false, "192.168.0.0/16,www.yahoo.co.uk", "212.82.100.150,192.168.0.0/16")] + // [InlineData(true, true, "192.168.0.0/16,www.yahoo.co.uk", "::ffff:212.82.100.150,::ffff:192.168.0.0/16")] <- fails on Max. www.yahoo.co.uk resolves to a different ip address. + // [InlineData(true, false, "192.168.0.0/16,www.yahoo.co.uk", "212.82.100.150,192.168.0.0/16")] [InlineData(true, true, "192.168.t,127.0.0.1,1234.1232.12.1234", "::ffff:127.0.0.1")] [InlineData(true, false, "192.168.x,127.0.0.1,1234.1232.12.1234", "127.0.0.1")] [InlineData(true, true, "::1", "::1/128")] From 1ea2b200c0b38f9d9a058f5e4b6e27815a016860 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 12 Jan 2021 15:28:02 +0100 Subject: [PATCH 0947/1930] JsonSerializer deserialize from bytes where possible This is faster and uses way less memory ``` BenchmarkDotNet=v0.12.1, OS=fedora 32 Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.100 [Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT | Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------- |---------:|--------:|--------:|--------:|------:|------:|----------:| | Bytes | 158.4 us | 2.56 us | 2.14 us | 16.8457 | - | - | 52.08 KB | | String | 172.8 us | 0.78 us | 0.70 us | 41.5039 | - | - | 127.82 KB | | Custom | 155.5 us | 2.95 us | 2.76 us | 10.0098 | - | - | 31.27 KB | ``` --- .../Channels/ChannelManager.cs | 10 +++++----- .../LiveTv/EmbyTV/ItemDataProvider.cs | 6 +++--- .../Plugins/PluginManager.cs | 6 ++---- .../ScheduledTasks/ScheduledTaskWorker.cs | 20 +++++++++---------- .../Routines/MigrateDisplayPreferencesDb.cs | 2 +- 5 files changed, 21 insertions(+), 23 deletions(-) diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 2d5b19fa69..8c5fa09f69 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -336,19 +336,19 @@ namespace Emby.Server.Implementations.Channels return GetChannel(GetInternalChannelId(channel.Name)) ?? GetChannel(channel, CancellationToken.None).Result; } - private List GetSavedMediaSources(BaseItem item) + private MediaSourceInfo[] GetSavedMediaSources(BaseItem item) { var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json"); try { - var jsonString = File.ReadAllText(path, Encoding.UTF8); - return JsonSerializer.Deserialize>(jsonString, _jsonOptions) - ?? new List(); + var bytes = File.ReadAllBytes(path); + return JsonSerializer.Deserialize(bytes, _jsonOptions) + ?? Array.Empty(); } catch { - return new List(); + return Array.Empty(); } } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index c80ecd6b3c..57424f0435 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -47,11 +47,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV try { - var jsonString = File.ReadAllText(_dataPath, Encoding.UTF8); - _items = JsonSerializer.Deserialize(jsonString, _jsonOptions); + var bytes = File.ReadAllBytes(_dataPath); + _items = JsonSerializer.Deserialize(bytes, _jsonOptions); return; } - catch (Exception ex) + catch (JsonException ex) { Logger.LogError(ex, "Error deserializing {Path}", _dataPath); } diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 1ab01252d0..e7fcc1f585 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -514,12 +514,10 @@ namespace Emby.Server.Implementations.Plugins { try { - var data = File.ReadAllText(metafile, Encoding.UTF8); + var data = File.ReadAllBytes(metafile); manifest = JsonSerializer.Deserialize(data, _jsonOptions); } -#pragma warning disable CA1031 // Do not catch general exception types - catch (Exception ex) -#pragma warning restore CA1031 // Do not catch general exception types + catch (JsonException ex) { _logger.LogError(ex, "Error deserializing {Path}.", dir); } diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 29440b64a0..1d93b63a87 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -143,21 +143,21 @@ namespace Emby.Server.Implementations.ScheduledTasks { if (File.Exists(path)) { - try + var bytes = File.ReadAllBytes(path); + if (bytes.Length > 0) { - var jsonString = File.ReadAllText(path, Encoding.UTF8); - if (!string.IsNullOrWhiteSpace(jsonString)) + try { - _lastExecutionResult = JsonSerializer.Deserialize(jsonString, _jsonOptions); + _lastExecutionResult = JsonSerializer.Deserialize(bytes, _jsonOptions); } - else + catch (JsonException ex) { - _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path); + _logger.LogError(ex, "Error deserializing {File}", path); } } - catch (Exception ex) + else { - _logger.LogError(ex, "Error deserializing {File}", path); + _logger.LogDebug("Scheduled Task history file {Path} is empty. Skipping deserialization.", path); } } @@ -541,8 +541,8 @@ namespace Emby.Server.Implementations.ScheduledTasks TaskTriggerInfo[] list = null; if (File.Exists(path)) { - var jsonString = File.ReadAllText(path, Encoding.UTF8); - list = JsonSerializer.Deserialize(jsonString, _jsonOptions); + var bytes = File.ReadAllBytes(path); + list = JsonSerializer.Deserialize(bytes, _jsonOptions); } // Return defaults if file doesn't exist. diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index f4040748d7..07829c6969 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -90,7 +90,7 @@ namespace Jellyfin.Server.Migrations.Routines var results = connection.Query("SELECT * FROM userdisplaypreferences"); foreach (var result in results) { - var dto = JsonSerializer.Deserialize(result[3].ToString(), _jsonOptions); + var dto = JsonSerializer.Deserialize(result[3].ToBlob(), _jsonOptions); if (dto == null) { continue; From a9b497720dcb27b2c8465ab61f7f77e77c75ab04 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 12 Jan 2021 15:37:18 +0100 Subject: [PATCH 0948/1930] Use JsonSerializer.SerializeToUtf8Bytes when doing a round trip This test uses a very small object (CountryInfo), using a bigger object would increase the difference in allocated memory. ``` BenchmarkDotNet=v0.12.1, OS=fedora 32 Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=5.0.100 [Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT DefaultJob : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT | Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |---------------- |-----------:|---------:|---------:|-------:|------:|------:|----------:| | RoundTripBytes | 932.0 ns | 5.09 ns | 4.25 ns | 0.1173 | - | - | 368 B | | RoundTripString | 1,114.8 ns | 22.19 ns | 23.74 ns | 0.1469 | - | - | 464 B | ``` --- Emby.Server.Implementations/Library/MediaSourceManager.cs | 2 +- Emby.Server.Implementations/LiveTv/LiveTvManager.cs | 4 ++-- MediaBrowser.Controller/Entities/CollectionFolder.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 660ec106bd..c63eb70179 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -515,7 +515,7 @@ namespace Emby.Server.Implementations.Library } // TODO: @bond Fix - var json = JsonSerializer.Serialize(mediaSource, _jsonOptions); + var json = JsonSerializer.SerializeToUtf8Bytes(mediaSource, _jsonOptions); _logger.LogInformation("Live stream opened: " + json); var clone = JsonSerializer.Deserialize(json, _jsonOptions); diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 7842be7164..63a3146aa9 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2239,7 +2239,7 @@ namespace Emby.Server.Implementations.LiveTv public async Task SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true) { - info = JsonSerializer.Deserialize(JsonSerializer.Serialize(info)); + info = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(info)); var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); @@ -2283,7 +2283,7 @@ namespace Emby.Server.Implementations.LiveTv { // Hack to make the object a pure ListingsProviderInfo instead of an AddListingProvider // ServerConfiguration.SaveConfiguration crashes during xml serialization for AddListingProvider - info = JsonSerializer.Deserialize(JsonSerializer.Serialize(info)); + info = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(info)); var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase)); diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index c3b6af76ea..65fd1654c3 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -123,7 +123,7 @@ namespace MediaBrowser.Controller.Entities { LibraryOptions[path] = options; - var clone = JsonSerializer.Deserialize(JsonSerializer.Serialize(options, _jsonOptions), _jsonOptions); + var clone = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions); foreach (var mediaPath in clone.PathInfos) { if (!string.IsNullOrEmpty(mediaPath.Path)) From 1752423e529f62dfd5a297b11382ab01890e0767 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 12 Jan 2021 15:51:32 +0100 Subject: [PATCH 0949/1930] Open FileStream with FileMode.Create instead of FileMode.OpenOrCreate > The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (such as "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method"). Ref: https://docs.microsoft.com/en-us/dotnet/api/system.io.file.openwrite?view=net-5.0#remarks --- .../ScheduledTasks/ScheduledTaskWorker.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 29440b64a0..d3cf3bf3f4 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -177,7 +177,7 @@ namespace Emby.Server.Implementations.ScheduledTasks lock (_lastExecutionResultSyncLock) { - using FileStream createStream = File.OpenWrite(path); + using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); JsonSerializer.SerializeAsync(createStream, value, _jsonOptions); } } @@ -577,9 +577,8 @@ namespace Emby.Server.Implementations.ScheduledTasks var path = GetConfigurationFilePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); - - var json = JsonSerializer.Serialize(triggers, _jsonOptions); - File.WriteAllText(path, json, Encoding.UTF8); + using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); + JsonSerializer.SerializeAsync(createStream, triggers, _jsonOptions); } /// From 1fdd2d6e0527a7b112ed6d79d8854f6fbe6fdaca Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 12 Jan 2021 16:03:13 +0100 Subject: [PATCH 0950/1930] Handle IO errors in LoadManifest --- .../Plugins/PluginManager.cs | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index e7fcc1f585..c4598f2815 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -512,30 +512,36 @@ namespace Emby.Server.Implementations.Plugins var metafile = Path.Combine(dir, "meta.json"); if (File.Exists(metafile)) { + // Only path where this stays null is when File.ReadAllBytes throws an IOException + byte[] data = null!; try { - var data = File.ReadAllBytes(metafile); + data = File.ReadAllBytes(metafile); manifest = JsonSerializer.Deserialize(data, _jsonOptions); } + catch (IOException ex) + { + _logger.LogError(ex, "Error reading file {Path}.", dir); + } catch (JsonException ex) { - _logger.LogError(ex, "Error deserializing {Path}.", dir); + _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data!)); } - } - if (manifest != null) - { - if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) + if (manifest != null) { - targetAbi = _minimumVersion; - } + if (!Version.TryParse(manifest.TargetAbi, out var targetAbi)) + { + targetAbi = _minimumVersion; + } - if (!Version.TryParse(manifest.Version, out version)) - { - manifest.Version = _minimumVersion.ToString(); - } + if (!Version.TryParse(manifest.Version, out version)) + { + manifest.Version = _minimumVersion.ToString(); + } - return new LocalPlugin(dir, _appVersion >= targetAbi, manifest); + return new LocalPlugin(dir, _appVersion >= targetAbi, manifest); + } } // No metafile, so lets see if the folder is versioned. From eeff9f52c66dc6ed7ab95226f8daa7cb00b7d529 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 12 Jan 2021 16:27:38 +0100 Subject: [PATCH 0951/1930] Fix Omdb caching --- .../Plugins/Omdb/OmdbProvider.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index 3da999ad06..e3301ff329 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -272,6 +272,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb return path; } } + else + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + } var url = GetOmdbUrl( string.Format( @@ -280,8 +284,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb imdbParam)); var rootObject = await GetDeserializedOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - await using FileStream jsonFileStream = File.OpenWrite(path); + await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); return path; @@ -308,6 +311,10 @@ namespace MediaBrowser.Providers.Plugins.Omdb return path; } } + else + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + } var url = GetOmdbUrl( string.Format( @@ -317,8 +324,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb seasonId)); var rootObject = await GetDeserializedOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - await using FileStream jsonFileStream = File.OpenWrite(path); + await using FileStream jsonFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false); return path; From 08e83cfa54a9c5ca9b33ad71731825dcb1f79442 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 18:52:48 +0000 Subject: [PATCH 0952/1930] Remove additional debug logging. --- Jellyfin.Networking/Manager/NetworkManager.cs | 9 ------- .../ApiServiceCollectionExtensions.cs | 25 ------------------- MediaBrowser.Common/Net/INetworkManager.cs | 6 ----- 3 files changed, 40 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index e2fe440608..c9f900660b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -195,15 +195,6 @@ namespace Jellyfin.Networking.Manager return _macAddresses; } - /// - /// REMOVE after debugging. - /// - /// Message. - public void Log(string msg) - { - _logger.LogInformation(msg); - } - /// public bool IsGatewayInterface(IPObject? addressObj) { diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 2d03c129e2..dae57b2273 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -232,27 +232,6 @@ namespace Jellyfin.Server.Extensions } } - private static string EnumToString(IEnumerable x) - { - var sb = new StringBuilder(); - foreach (var item in x) - { - if (item is IPAddress ipItem) - { - sb.Append(ipItem.ToString()); - } - else if (item is IPNetwork ipNetwork) - { - sb.Append(ipNetwork.Prefix.ToString()); - sb.Append('/'); - sb.Append(ipNetwork.PrefixLength.ToString(CultureInfo.InvariantCulture)); - sb.Append(','); - } - } - - return sb.ToString(); - } - /// /// Extension method for adding the jellyfin API to the service collection. /// @@ -280,8 +259,6 @@ namespace Jellyfin.Server.Extensions else { ParseList(networkManager, config, config.KnownProxies, options); - networkManager.Log("KnownProxies: " + EnumToString(options.KnownProxies)); - networkManager.Log("KnownNetworks: " + EnumToString(options.KnownNetworks)); } // Only set forward limit if we have some known proxies or some known networks. @@ -289,8 +266,6 @@ namespace Jellyfin.Server.Extensions { options.ForwardLimit = null; } - - networkManager.Log("Forward Limit : " + options.ForwardLimit?.ToString(CultureInfo.CurrentCulture) ?? "None"); }) .AddMvc(opts => { diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 455fbe27a6..eb7e9ee615 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -239,11 +239,5 @@ namespace MediaBrowser.Common.Net /// Optional filter for the list. /// Returns a filtered list of LAN addresses. Collection GetFilteredLANSubnets(Collection? filter = null); - - /// - /// REMOVE after debugging. - /// - /// Message. - void Log(string msg); } } From 94cc5b9d8b885a32adedfad67da4f36fbaf69914 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 20:41:40 +0000 Subject: [PATCH 0953/1930] Update MediaBrowser.Common/Net/INetworkManager.cs Co-authored-by: Cody Robibero --- MediaBrowser.Common/Net/INetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index eb7e9ee615..5862328b42 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -52,7 +52,7 @@ namespace MediaBrowser.Common.Net /// /// Gets or sets a value indicating whether the system has IP6 is enabled. /// - public bool SystemIP6Enabled { get; set; } + bool SystemIP6Enabled { get; set; } /// /// Calculates the list of interfaces to use for Kestrel. From dfd7ff573200509def414a030152054f4d67c835 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 20:41:48 +0000 Subject: [PATCH 0954/1930] Update MediaBrowser.Common/Net/INetworkManager.cs Co-authored-by: Cody Robibero --- MediaBrowser.Common/Net/INetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 5862328b42..7ee76107bc 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Common.Net /// /// Gets or sets a value indicating whether the system has IP4 is enabled. /// - public bool SystemIP4Enabled { get; set; } + bool SystemIP4Enabled { get; set; } /// /// Gets or sets a value indicating whether the system has IP6 is enabled. From d66bc3fb3e3256353c2643e372905b74a55774d4 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 20:43:25 +0000 Subject: [PATCH 0955/1930] Fixed indentation --- .../Extensions/ApiServiceCollectionExtensions.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index dae57b2273..86b98db0a7 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -243,9 +243,9 @@ namespace Jellyfin.Server.Extensions public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable pluginAssemblies, NetworkConfiguration config, INetworkManager networkManager) { IMvcBuilder mvcBuilder = serviceCollection - .AddCors() - .AddTransient() - .Configure(options => + .AddCors() + .AddTransient() + .Configure(options => { // https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs // Enable debug logging on Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersMiddleware to help investigate issues. From 580b90aa4c5250c5259fff96d0b1a1ca11e56d6a Mon Sep 17 00:00:00 2001 From: Oriol Serra Date: Tue, 12 Jan 2021 20:24:55 +0000 Subject: [PATCH 0956/1930] Translated using Weblate (Catalan) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ca/ --- Emby.Server.Implementations/Localization/Core/ca.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ca.json b/Emby.Server.Implementations/Localization/Core/ca.json index b7852eccb3..1439d9b8ed 100644 --- a/Emby.Server.Implementations/Localization/Core/ca.json +++ b/Emby.Server.Implementations/Localization/Core/ca.json @@ -113,5 +113,10 @@ "TasksChannelsCategory": "Canals d'internet", "TasksApplicationCategory": "Aplicació", "TasksLibraryCategory": "Biblioteca", - "TasksMaintenanceCategory": "Manteniment" + "TasksMaintenanceCategory": "Manteniment", + "TaskCleanActivityLogDescription": "Eliminat entrades del registre d'activitats mes antigues que l'antiguitat configurada.", + "TaskCleanActivityLog": "Buidar Registre d'Activitat", + "Undefined": "Indefinit", + "Forced": "Forçat", + "Default": "Defecto" } From f7aae0e876b806cf04d7e750aeb8b22ba6b038e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B6=99=E6=98=A0=E7=BF=94?= Date: Tue, 12 Jan 2021 19:09:04 +0000 Subject: [PATCH 0957/1930] Translated using Weblate (Chinese (Traditional)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant/ --- Emby.Server.Implementations/Localization/Core/zh-TW.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index 6494c0b544..affb0e099b 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -1,6 +1,6 @@ { "Albums": "專輯", - "AppDeviceValues": "軟體:{0},裝置:{1}", + "AppDeviceValues": "App:{0},裝置:{1}", "Application": "應用程式", "Artists": "演出者", "AuthenticationSucceededWithUserName": "{0} 成功授權", From c6aa6ceed97f6172d35d8be8feb9afc61a0e829d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 12 Jan 2021 22:10:23 +0000 Subject: [PATCH 0958/1930] Removal of IPluginConfigurationPage --- .../Controllers/DashboardController.cs | 49 +++---------------- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 17 ------- .../Plugins/IPluginConfigurationPage.cs | 30 ------------ 3 files changed, 7 insertions(+), 89 deletions(-) diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index b77d79209a..8cb93cc80b 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -62,32 +62,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableInMainMenu, [FromQuery] ConfigurationPageType? pageType) { - const string unavailableMessage = "The server is still loading. Please try again momentarily."; - - var pages = _appHost.GetExports().ToList(); - - if (pages == null) - { - return NotFound(unavailableMessage); - } - - // Don't allow a failing plugin to fail them all - var configPages = pages.Select(p => - { - try - { - return new ConfigurationPageInfo(p); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name); - return null; - } - }) - .Where(i => i != null) - .ToList(); - - configPages.AddRange(_pluginManager.Plugins.SelectMany(GetConfigPages)); + var configPages = _pluginManager.Plugins.SelectMany(GetConfigPages).ToList(); if (pageType.HasValue) { @@ -121,24 +96,14 @@ namespace Jellyfin.Api.Controllers var isJs = false; var isTemplate = false; - var page = _appHost.GetExports().FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)); - if (page != null) + var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, name, StringComparison.OrdinalIgnoreCase)); + if (altPage != null) { - plugin = page.Plugin; - stream = page.GetHtmlStream(); - } + plugin = altPage.Item2; + stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath); - if (plugin == null) - { - var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, name, StringComparison.OrdinalIgnoreCase)); - if (altPage != null) - { - plugin = altPage.Item2; - stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath); - - isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase); - isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html", StringComparison.Ordinal); - } + isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase); + isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html", StringComparison.Ordinal); } if (plugin != null && stream != null) diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index f56ef59765..0aa568fe74 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -10,23 +10,6 @@ namespace Jellyfin.Api.Models /// public class ConfigurationPageInfo { - /// - /// Initializes a new instance of the class. - /// - /// Instance of interface. - public ConfigurationPageInfo(IPluginConfigurationPage page) - { - Name = page.Name; - - ConfigurationPageType = page.ConfigurationPageType; - - if (page.Plugin != null) - { - DisplayName = page.Plugin.Name; - PluginId = page.Plugin.Id; - } - } - /// /// Initializes a new instance of the class. /// diff --git a/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs b/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs index 93eab42cc7..38e953be5e 100644 --- a/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs +++ b/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs @@ -3,36 +3,6 @@ using MediaBrowser.Common.Plugins; namespace MediaBrowser.Controller.Plugins { - /// - /// Interface IConfigurationPage. - /// - public interface IPluginConfigurationPage - { - /// - /// Gets the name. - /// - /// The name. - string Name { get; } - - /// - /// Gets the type of the configuration page. - /// - /// The type of the configuration page. - ConfigurationPageType ConfigurationPageType { get; } - - /// - /// Gets the plugin. - /// - /// The plugin. - IPlugin Plugin { get; } - - /// - /// Gets the HTML stream. - /// - /// Stream. - Stream GetHtmlStream(); - } - /// /// Enum ConfigurationPageType. /// From 9a5ceb34d169431fba8cf90dca79e0a448e88bde Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 13 Jan 2021 01:11:12 +0100 Subject: [PATCH 0959/1930] Improve WebSocket Deserialization --- .../HttpServer/WebSocketConnection.cs | 52 ++++++-------- .../HttpServer/WebSocketConnectionTests.cs | 69 +++++++++++++++++++ ...llyfin.Server.Implementations.Tests.csproj | 11 +-- .../LiveTv/HdHomerunHostTests.cs | 12 +--- .../Test Data/HttpServer/ForceKeepAlive.json | 1 + .../Test Data/HttpServer/Partial.json | 1 + .../Test Data/HttpServer/ValidPartial.json | 1 + .../{ => Test Data}/LiveTv/discover.json | 0 .../{ => Test Data}/LiveTv/lineup.json | 0 9 files changed, 102 insertions(+), 45 deletions(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json rename tests/Jellyfin.Server.Implementations.Tests/{ => Test Data}/LiveTv/discover.json (100%) rename tests/Jellyfin.Server.Implementations.Tests/{ => Test Data}/LiveTv/lineup.json (100%) diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index fed2addf80..7e0c2c1da2 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -5,6 +5,7 @@ using System.Buffers; using System.IO.Pipelines; using System.Net; using System.Net.WebSockets; +using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -138,7 +139,7 @@ namespace Emby.Server.Implementations.HttpServer writer.Advance(bytesRead); // Make the data available to the PipeReader - FlushResult flushResult = await writer.FlushAsync().ConfigureAwait(false); + FlushResult flushResult = await writer.FlushAsync(cancellationToken).ConfigureAwait(false); if (flushResult.IsCompleted) { // The PipeReader stopped reading @@ -181,32 +182,16 @@ namespace Emby.Server.Implementations.HttpServer } WebSocketMessage? stub; + long bytesConsumed = 0; try { - - if (buffer.IsSingleSegment) - { - stub = JsonSerializer.Deserialize>(buffer.FirstSpan, _jsonOptions); - } - else - { - var buf = ArrayPool.Shared.Rent(Convert.ToInt32(buffer.Length)); - try - { - buffer.CopyTo(buf); - stub = JsonSerializer.Deserialize>(buf, _jsonOptions); - } - finally - { - ArrayPool.Shared.Return(buf); - } - } + stub = DeserializeWebSocketMessage(buffer, out bytesConsumed); } catch (JsonException ex) { // Tell the PipeReader how much of the buffer we have consumed reader.AdvanceTo(buffer.End); - _logger.LogError(ex, "Error processing web socket message"); + _logger.LogError(ex, "Error processing web socket message: {Data}", Encoding.UTF8.GetString(buffer)); return; } @@ -217,27 +202,34 @@ namespace Emby.Server.Implementations.HttpServer } // Tell the PipeReader how much of the buffer we have consumed - reader.AdvanceTo(buffer.End); + reader.AdvanceTo(buffer.GetPosition(bytesConsumed)); _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub); - var info = new WebSocketMessageInfo - { - MessageType = stub.MessageType, - Data = stub.Data?.ToString(), // Data can be null - Connection = this - }; - - if (info.MessageType == SessionMessageType.KeepAlive) + if (stub.MessageType == SessionMessageType.KeepAlive) { await SendKeepAliveResponse().ConfigureAwait(false); } else { - await OnReceive(info).ConfigureAwait(false); + await OnReceive( + new WebSocketMessageInfo + { + MessageType = stub.MessageType, + Data = stub.Data?.ToString(), // Data can be null + Connection = this + }).ConfigureAwait(false); } } + internal WebSocketMessage? DeserializeWebSocketMessage(ReadOnlySequence bytes, out long bytesConsumed) + { + var jsonReader = new Utf8JsonReader(bytes); + var ret = JsonSerializer.Deserialize>(ref jsonReader, _jsonOptions); + bytesConsumed = jsonReader.BytesConsumed; + return ret; + } + private Task SendKeepAliveResponse() { LastKeepAliveDate = DateTime.UtcNow; diff --git a/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs b/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs new file mode 100644 index 0000000000..1ce2096ea6 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/HttpServer/WebSocketConnectionTests.cs @@ -0,0 +1,69 @@ +using System; +using System.Buffers; +using System.IO; +using System.Text.Json; +using Emby.Server.Implementations.HttpServer; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.HttpServer +{ + public class WebSocketConnectionTests + { + [Fact] + public void DeserializeWebSocketMessage_SingleSegment_Success() + { + var con = new WebSocketConnection(new NullLogger(), null!, null!, null!); + var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json"); + con.DeserializeWebSocketMessage(new ReadOnlySequence(bytes), out var bytesConsumed); + Assert.Equal(109, bytesConsumed); + } + + [Fact] + public void DeserializeWebSocketMessage_MultipleSegments_Success() + { + const int SplitPos = 64; + var con = new WebSocketConnection(new NullLogger(), null!, null!, null!); + var bytes = File.ReadAllBytes("Test Data/HttpServer/ForceKeepAlive.json"); + var seg1 = new BufferSegment(new Memory(bytes, 0, SplitPos)); + var seg2 = seg1.Append(new Memory(bytes, SplitPos, bytes.Length - SplitPos)); + con.DeserializeWebSocketMessage(new ReadOnlySequence(seg1, 0, seg2, seg2.Memory.Length - 1), out var bytesConsumed); + Assert.Equal(109, bytesConsumed); + } + + [Fact] + public void DeserializeWebSocketMessage_ValidPartial_Success() + { + var con = new WebSocketConnection(new NullLogger(), null!, null!, null!); + var bytes = File.ReadAllBytes("Test Data/HttpServer/ValidPartial.json"); + con.DeserializeWebSocketMessage(new ReadOnlySequence(bytes), out var bytesConsumed); + Assert.Equal(109, bytesConsumed); + } + + [Fact] + public void DeserializeWebSocketMessage_Partial_ThrowJsonException() + { + var con = new WebSocketConnection(new NullLogger(), null!, null!, null!); + var bytes = File.ReadAllBytes("Test Data/HttpServer/Partial.json"); + Assert.Throws(() => con.DeserializeWebSocketMessage(new ReadOnlySequence(bytes), out var bytesConsumed)); + } + + internal class BufferSegment : ReadOnlySequenceSegment + { + public BufferSegment(Memory memory) + { + Memory = memory; + } + + public BufferSegment Append(Memory memory) + { + var segment = new BufferSegment(memory) + { + RunningIndex = RunningIndex + Memory.Length + }; + Next = segment; + return segment; + } + } + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 5c41705142..7894570391 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -13,6 +13,12 @@ Jellyfin.Server.Implementations.Tests + + + PreserveNewest + + + @@ -35,11 +41,6 @@ - - - - - ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs index 75939526dc..8847239d90 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -21,24 +22,15 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv public HdHomerunHostTests() { - const string BaseResourcePath = "Jellyfin.Server.Implementations.Tests.LiveTv."; - var messageHandler = new Mock(); messageHandler.Protected() .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) .Returns( (m, _) => { - var resource = BaseResourcePath + m.RequestUri?.Segments[^1]; - var stream = typeof(HdHomerunHostTests).Assembly.GetManifestResourceStream(resource); - if (stream == null) - { - throw new NullReferenceException("Resource doesn't exist: " + resource); - } - return Task.FromResult(new HttpResponseMessage() { - Content = new StreamContent(stream) + Content = new StreamContent(File.OpenRead("Test Data/LiveTv/" + m.RequestUri?.Segments[^1])) }); }); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json new file mode 100644 index 0000000000..0472a3cd0c --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ForceKeepAlive.json @@ -0,0 +1 @@ +{"MessageType":"ForceKeepAlive","MessageId":"00000000-0000-0000-0000-000000000000","ServerId":null,"Data":60} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json new file mode 100644 index 0000000000..72f810725a --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/Partial.json @@ -0,0 +1 @@ +{"MessageType":"KeepAlive","MessageId":"d29ef449-6965-4000 diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json new file mode 100644 index 0000000000..62d9099c8b --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/HttpServer/ValidPartial.json @@ -0,0 +1 @@ +{"MessageType":"ForceKeepAlive","MessageId":"00000000-0000-0000-0000-000000000000","ServerId":null,"Data":60}{"MessageType":"KeepAlive","MessageId":"d29ef449-6965-4000 diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/discover.json similarity index 100% rename from tests/Jellyfin.Server.Implementations.Tests/LiveTv/discover.json rename to tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/discover.json diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/lineup.json similarity index 100% rename from tests/Jellyfin.Server.Implementations.Tests/LiveTv/lineup.json rename to tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/lineup.json From eb82879a4fde4f011bc94811617e139a93aa7ef3 Mon Sep 17 00:00:00 2001 From: Deniz Date: Wed, 13 Jan 2021 07:20:56 +0000 Subject: [PATCH 0960/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 885663eed8..2521243645 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -117,5 +117,6 @@ "TaskCleanActivityLog": "İşlem Günlüğünü Temizle", "TaskCleanActivityLogDescription": "Belirtilen sureden daha eski etkinlik log kayıtları silindi.", "Undefined": "Bilinmeyen", - "Default": "Varsayılan" + "Default": "Varsayılan", + "Forced": "Zorla" } From 9a730241b1f2bee8601d4d2e4883908868c2b4a8 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 13 Jan 2021 15:14:04 +0000 Subject: [PATCH 0961/1930] Changed to address. --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 86b98db0a7..6690ad1c9f 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -212,8 +212,8 @@ namespace Jellyfin.Server.Extensions { foreach (var address in host.GetAddresses()) { - if ((!config.EnableIPV4 && host.AddressFamily == AddressFamily.InterNetwork) - || (!config.EnableIPV6 && host.AddressFamily == AddressFamily.InterNetworkV6)) + if ((!config.EnableIPV4 && address.AddressFamily == AddressFamily.InterNetwork) + || (!config.EnableIPV6 && address.AddressFamily == AddressFamily.InterNetworkV6)) { continue; } From 4bc8a1e77beacb607ac221cc8d37f30e16dd4984 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 13 Jan 2021 15:29:57 +0000 Subject: [PATCH 0962/1930] updated --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 6690ad1c9f..bd72b1e27d 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; using Emby.Server.Implementations; using Jellyfin.Api.Auth; @@ -42,6 +43,8 @@ using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; +[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] + namespace Jellyfin.Server.Extensions { /// @@ -180,7 +183,7 @@ namespace Jellyfin.Server.Extensions /// The containing the config settings. /// The string array to parse. /// The instance. - public static void ParseList(INetworkManager networkManager, NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) + internal static void ParseList(INetworkManager networkManager, NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) { for (var i = 0; i < userList.Length; i++) { From 549160b9b934c067a881a1204c6177d9eb4df5bf Mon Sep 17 00:00:00 2001 From: Alexander Brissman Date: Wed, 13 Jan 2021 18:47:51 +0000 Subject: [PATCH 0963/1930] =?UTF-8?q?Translated=20using=20Weblate=20(Norwe?= =?UTF-8?q?gian=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Transl?= =?UTF-8?q?ate-URL:=20https://translate.jellyfin.org/projects/jellyfin/jel?= =?UTF-8?q?lyfin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Emby.Server.Implementations/Localization/Core/nb.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index 3b016fe62a..d5bca9f6c9 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -117,5 +117,6 @@ "TaskCleanActivityLog": "Tøm aktivitetslogg", "Undefined": "Udefinert", "Forced": "Tvungen", - "Default": "Standard" + "Default": "Standard", + "TaskCleanActivityLogDescription": "Sletter oppføringer i aktivitetsloggen som er eldre enn den konfigurerte alderen." } From bced1eab54180c1dd60d884dd03adb5207a4a20b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 13 Jan 2021 21:16:04 +0000 Subject: [PATCH 0964/1930] Assert.True --- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index f4ea45cc2b..ca7b8a965b 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -1,15 +1,10 @@ using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Net; using System.Text; -using System.Threading.Tasks; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using Jellyfin.Server.Extensions; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -86,10 +81,7 @@ namespace Jellyfin.Api.Tests sb.Append(','); } - if (!string.Equals(sb.ToString(), result, StringComparison.OrdinalIgnoreCase)) - { - throw new Exception("Not matched: " + sb.ToString() + " does not match " + result); - } + Assert.True(string.Equals(sb.ToString(), result, StringComparison.OrdinalIgnoreCase), "Not matched: " + sb.ToString() + " does not match " + result); } } } From 8ef37f6b0ec65256bd5b3741c049701e6f3b3202 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 15 Jan 2021 10:26:00 +0000 Subject: [PATCH 0965/1930] Rename IPluginConfigurationPage.cs to ConfigurationPageType.cs.cs Renamed file. --- .../{IPluginConfigurationPage.cs => ConfigurationPageType.cs.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MediaBrowser.Controller/Plugins/{IPluginConfigurationPage.cs => ConfigurationPageType.cs.cs} (100%) diff --git a/MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs b/MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs similarity index 100% rename from MediaBrowser.Controller/Plugins/IPluginConfigurationPage.cs rename to MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs From a4e838fbf594020e9e0663e27d4aab878393c3f3 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 15 Jan 2021 10:36:44 +0000 Subject: [PATCH 0966/1930] Remoed configurationPageType --- .../Controllers/DashboardController.cs | 9 +------- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 6 ------ .../Plugins/ConfigurationPageType.cs.cs | 21 ------------------- 3 files changed, 1 insertion(+), 35 deletions(-) delete mode 100644 MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index 8cb93cc80b..ff7895373b 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -51,7 +51,6 @@ namespace Jellyfin.Api.Controllers /// Gets the configuration pages. /// /// Whether to enable in the main menu. - /// The . /// ConfigurationPages returned. /// Server still loading. /// An with infos about the plugins. @@ -59,16 +58,10 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult> GetConfigurationPages( - [FromQuery] bool? enableInMainMenu, - [FromQuery] ConfigurationPageType? pageType) + [FromQuery] bool? enableInMainMenu) { var configPages = _pluginManager.Plugins.SelectMany(GetConfigPages).ToList(); - if (pageType.HasValue) - { - configPages = configPages.Where(p => p!.ConfigurationPageType == pageType).ToList(); - } - if (enableInMainMenu.HasValue) { configPages = configPages.Where(p => p!.EnableInMainMenu == enableInMainMenu.Value).ToList(); diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index 0aa568fe74..a7bbe42fe5 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -51,12 +51,6 @@ namespace Jellyfin.Api.Models /// public string? DisplayName { get; set; } - /// - /// Gets or sets the type of the configuration page. - /// - /// The type of the configuration page. - public ConfigurationPageType ConfigurationPageType { get; set; } - /// /// Gets or sets the plugin id. /// diff --git a/MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs b/MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs deleted file mode 100644 index 38e953be5e..0000000000 --- a/MediaBrowser.Controller/Plugins/ConfigurationPageType.cs.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.IO; -using MediaBrowser.Common.Plugins; - -namespace MediaBrowser.Controller.Plugins -{ - /// - /// Enum ConfigurationPageType. - /// - public enum ConfigurationPageType - { - /// - /// The plugin configuration. - /// - PluginConfiguration, - - /// - /// The none. - /// - None - } -} From 16d092a8a715463f7884f53341c064accd4da952 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 15 Jan 2021 12:17:50 +0000 Subject: [PATCH 0967/1930] Fixed encoding issue --- Emby.Dlna/PlayTo/TransportCommands.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 0865968ad1..42027b5af7 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Security; using System.Xml.Linq; using Emby.Dlna.Common; using Emby.Dlna.Ssdp; @@ -175,12 +176,12 @@ namespace Emby.Dlna.PlayTo if (state != null) { var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ?? - (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : value); + (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : SecurityElement.Escape(value)); return string.Format(CultureInfo.InvariantCulture, "<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}", argument.Name, state.DataType ?? "string", sendValue); } - return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}", argument.Name, value); + return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}", argument.Name, SecurityElement.Escape(value)); } } } From 620648fe81cd924c906326ea7afa236f937ff844 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 15 Jan 2021 18:55:52 +0000 Subject: [PATCH 0968/1930] Fixed for no data. --- Emby.Dlna/Didl/DidlBuilder.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index abaf522bca..02bfa6053e 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -113,6 +113,8 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); // writer.WriteEndDocument(); + + writer.Flush(); } return builder.ToString(); From 3d754fa5bfcd1b5376124f08b88e51bda5ff7e81 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 15 Jan 2021 15:06:11 -0700 Subject: [PATCH 0969/1930] Revert "Don't return first episodes in next up" --- .../TV/TVSeriesManager.cs | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index f0734340be..a8b1064cb7 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -143,10 +143,28 @@ namespace Emby.Server.Implementations.TV var allNextUp = seriesKeys .Select(i => GetNextUp(i, currentUser, dtoOptions)); + // allNextUp = allNextUp.OrderByDescending(i => i.Item1); + + // If viewing all next up for all series, remove first episodes + // But if that returns empty, keep those first episodes (avoid completely empty view) + var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId); + var anyFound = false; + return allNextUp .Where(i => { - return i.Item1 != DateTime.MinValue; + if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue) + { + anyFound = true; + return true; + } + + if (!anyFound && i.Item1 == DateTime.MinValue) + { + return true; + } + + return false; }) .Select(i => i.Item2()) .Where(i => i != null); From 3b9567d58364c1eac0e99169ba8aef8d3bd6777f Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 15 Jan 2021 15:08:48 -0700 Subject: [PATCH 0970/1930] Add query parameter to disable returning first episode as next up --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 5 +++++ Jellyfin.Api/Controllers/TvShowsController.cs | 7 +++++-- MediaBrowser.Model/Querying/NextUpQuery.cs | 6 ++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index a8b1064cb7..168c8fea06 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -153,6 +153,11 @@ namespace Emby.Server.Implementations.TV return allNextUp .Where(i => { + if (request.DisableFirstEpisode) + { + return i.Item1 != DateTime.MinValue; + } + if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue) { anyFound = true; diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index ca18901e5d..223f588593 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -67,6 +67,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The image types to include in the output. /// Optional. Include user data. /// Whether to enable the total records count. Defaults to true. + /// Whether to disable sending the first episode in a series as next up. /// A with the next up episodes. [HttpGet("NextUp")] [ProducesResponseType(StatusCodes.Status200OK)] @@ -81,7 +82,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, - [FromQuery] bool enableTotalRecordCount = true) + [FromQuery] bool enableTotalRecordCount = true, + [FromQuery] bool disableFirstEpisode = false) { var options = new DtoOptions { Fields = fields } .AddClientFields(Request) @@ -95,7 +97,8 @@ namespace Jellyfin.Api.Controllers SeriesId = seriesId, StartIndex = startIndex, UserId = userId ?? Guid.Empty, - EnableTotalRecordCount = enableTotalRecordCount + EnableTotalRecordCount = enableTotalRecordCount, + DisableFirstEpisode = disableFirstEpisode }, options); diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index 4ad336d333..001d0623cc 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -64,10 +64,16 @@ namespace MediaBrowser.Model.Querying public bool EnableTotalRecordCount { get; set; } + /// + /// Gets or sets a value indicating whether do disable sending first episode as next up. + /// + public bool DisableFirstEpisode { get; set; } + public NextUpQuery() { EnableImageTypes = Array.Empty(); EnableTotalRecordCount = true; + DisableFirstEpisode = false; } } } From a087ab389a1530a4bfb7efb3a29cec07aa06b10d Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 16 Jan 2021 10:17:33 -0700 Subject: [PATCH 0971/1930] dotnet 5.0.2 --- .github/workflows/codeql-analysis.yml | 2 +- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- Jellyfin.Data/Jellyfin.Data.csproj | 4 ++-- .../Jellyfin.Server.Implementations.csproj | 4 ++-- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++-- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- deployment/Dockerfile.debian.amd64 | 2 +- deployment/Dockerfile.debian.arm64 | 2 +- deployment/Dockerfile.debian.armhf | 2 +- deployment/Dockerfile.linux.amd64 | 2 +- deployment/Dockerfile.linux.amd64-musl | 2 +- deployment/Dockerfile.linux.arm64 | 2 +- deployment/Dockerfile.linux.armhf | 2 +- deployment/Dockerfile.macos | 2 +- deployment/Dockerfile.portable | 2 +- deployment/Dockerfile.ubuntu.amd64 | 2 +- deployment/Dockerfile.ubuntu.arm64 | 2 +- deployment/Dockerfile.ubuntu.armhf | 2 +- deployment/Dockerfile.windows.amd64 | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 20 files changed, 23 insertions(+), 23 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 5388948189..3e456f9093 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -24,7 +24,7 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: '5.0.100' + dotnet-version: '5.0.x' - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index f01f50cea7..8437369b2f 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,7 +15,7 @@ - + diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 4fb5594d4d..b95879de46 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -41,8 +41,8 @@ - - + + diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 9e4a2065fe..05052e5c06 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -26,11 +26,11 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 5940cf9389..3ebcc3279d 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -40,8 +40,8 @@ - - + + diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index c271a9cf85..e5166672f9 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -35,7 +35,7 @@ - + diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index d2f98ca827..f5cf232d65 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index ffc94e0889..d9414a6104 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index b25f59329a..7f2275aaa3 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 2e993c25df..54d75dcbe9 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl index 08b4ffa528..e4c7242191 100644 --- a/deployment/Dockerfile.linux.amd64-musl +++ b/deployment/Dockerfile.linux.amd64-musl @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 index b8499c9172..6338025981 100644 --- a/deployment/Dockerfile.linux.arm64 +++ b/deployment/Dockerfile.linux.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf index 80c4d14693..ec0b015cc8 100644 --- a/deployment/Dockerfile.linux.armhf +++ b/deployment/Dockerfile.linux.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index f2bbe7f243..25f15be183 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index 603becedf1..cd71ce9d49 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index a6c7cc5d43..ea539b3609 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index 3a80058166..f2f5368f7a 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 22b9e7ea8b..ba597801b5 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index b1ca610533..c731268416 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a0487784-534a-4912-a4dd-017382083865/be16057043a8f7b6f08c902dc48dd677/dotnet-sdk-5.0.101-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 07972bb424..b8940c994b 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -16,7 +16,7 @@ - + From 688e7c6a2d7748cdcad64c557d3e5a01b0a1590f Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 17 Jan 2021 12:45:11 +0000 Subject: [PATCH 0972/1930] Moved internalVisibleToAttribute to .csj --- .../Extensions/ApiServiceCollectionExtensions.cs | 2 -- Jellyfin.Server/Jellyfin.Server.csproj | 6 ++++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index bd72b1e27d..73a2265dec 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -43,8 +43,6 @@ using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; -[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] - namespace Jellyfin.Server.Extensions { /// diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 5940cf9389..cfec2d82fe 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -36,6 +36,12 @@ ../jellyfin.ruleset + + + <_Parameter1>Jellyfin.Api.Tests + + + From b9f0f4f53bdacc6abb7f449cdf7149525cd6119c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 17 Jan 2021 13:35:30 +0000 Subject: [PATCH 0973/1930] reverted --- .../ApiServiceCollectionExtensions.cs | 2 + Jellyfin.Server/Jellyfin.Server.csproj | 12 ++--- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 50 ++++++++++--------- 3 files changed, 34 insertions(+), 30 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 73a2265dec..bd72b1e27d 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -43,6 +43,8 @@ using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; +[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] + namespace Jellyfin.Server.Extensions { /// diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index cfec2d82fe..f91f2db02b 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -36,12 +36,6 @@ ../jellyfin.ruleset - - - <_Parameter1>Jellyfin.Api.Tests - - - @@ -79,4 +73,10 @@ + + + <_Parameter1>Jellyfin.Api.Tests + + + diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index ca7b8a965b..6ee66d2a8f 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -14,27 +14,6 @@ namespace Jellyfin.Api.Tests { public class ParseNetworkTests { - private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) - { - var configManager = new Mock - { - CallBase = true - }; - configManager.Setup(x => x.GetConfiguration(It.IsAny())).Returns(conf); - return (IConfigurationManager)configManager.Object; - } - - private static NetworkManager CreateNetworkManager() - { - var conf = new NetworkConfiguration() - { - EnableIPV6 = true, - EnableIPV4 = true, - }; - - return new NetworkManager(GetMockConfig(conf), new NullLogger()); - } - /// /// Order of the result has always got to be hosts, then networks. /// @@ -53,9 +32,11 @@ namespace Jellyfin.Api.Tests using var nm = CreateNetworkManager(); nm.SystemIP6Enabled = ip6; - var settings = new NetworkConfiguration(); - settings.EnableIPV4 = ip4; - settings.EnableIPV6 = ip6; + var settings = new NetworkConfiguration + { + EnableIPV4 = ip4, + EnableIPV6 = ip6 + }; var result = match + ','; ForwardedHeadersOptions options = new ForwardedHeadersOptions(); @@ -83,5 +64,26 @@ namespace Jellyfin.Api.Tests Assert.True(string.Equals(sb.ToString(), result, StringComparison.OrdinalIgnoreCase), "Not matched: " + sb.ToString() + " does not match " + result); } + + private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) + { + var configManager = new Mock + { + CallBase = true + }; + configManager.Setup(x => x.GetConfiguration(It.IsAny())).Returns(conf); + return (IConfigurationManager)configManager.Object; + } + + private static NetworkManager CreateNetworkManager() + { + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + }; + + return new NetworkManager(GetMockConfig(conf), new NullLogger()); + } } } From d8d9d90469f3b8ff8a4ad10bf7bb84ed9b2efee1 Mon Sep 17 00:00:00 2001 From: Sinan Date: Sun, 17 Jan 2021 15:53:31 +0000 Subject: [PATCH 0974/1930] Translated using Weblate (Turkish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/tr/ --- Emby.Server.Implementations/Localization/Core/tr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/tr.json b/Emby.Server.Implementations/Localization/Core/tr.json index 2521243645..c6b904045b 100644 --- a/Emby.Server.Implementations/Localization/Core/tr.json +++ b/Emby.Server.Implementations/Localization/Core/tr.json @@ -12,7 +12,7 @@ "DeviceOfflineWithName": "{0} bağlantısı kesildi", "DeviceOnlineWithName": "{0} bağlı", "FailedLoginAttemptWithUserName": "{0} adresinden giriş başarısız oldu", - "Favorites": "Favorilerim", + "Favorites": "Favoriler", "Folders": "Klasörler", "Genres": "Türler", "HeaderAlbumArtists": "Albüm Sanatçıları", From 4e21b49994ba031e0716568c38681c3c5b83bbc0 Mon Sep 17 00:00:00 2001 From: senritsu Date: Sun, 17 Jan 2021 20:24:23 +0100 Subject: [PATCH 0975/1930] adjust episode path expression to allow digits in series names The previous expression was too greedy to consume digits, because the hyphen was optional. This lead to incorrect episode numbers for certain series with digits in their names, in those cases each episode was recognized as the same episode number (the digit from the series name). The rule, which matches most standard anime filenames, also had a lower priority than one of the Kodi rules, leading to incorrect recognition for absolute numbered episodes with triple digits and higher (first digit was used as season number, rest of digits as episode number). This also resolves one of the TODO test cases. Additional test cases were added to ensure that both hyphens in different parts of the filename, as well as names without hyphens, still work correctly. All previous test cases still pass. Unfortunately another TODO (EpisodeNumberTests.cs@L76, Uchuu Senkan Yamato 2199) with the same issue (digits in the series name) could not be trivially fixed in the same change, due to the significantly different formatting. Attempts to resolve this case did not work out for now. --- Emby.Naming/Common/NamingOptions.cs | 13 +++++++------ .../Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs | 6 +++++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 035d1b2280..ba4446ff11 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -282,7 +282,13 @@ namespace Emby.Naming.Common SupportsAbsoluteEpisodeNumbers = true }, - // Case Closed (1996-2007)/Case Closed - 317.mkv + // Not a Kodi rule as well, but below rule also causes false positives for triple-digit episode names + // [bar] Foo - 1 [baz] special case of below expression to prevent false positives with digits in the series name + new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[\s_]*-[\s_]*(?\d+).*$") + { + IsNamed = true + }, + // /server/anything_102.mp4 // /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv // /server/anything_1996.11.14.mp4 @@ -299,11 +305,6 @@ namespace Emby.Naming.Common // *** End Kodi Standard Naming - // [bar] Foo - 1 [baz] - new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[-\s_]+(?[0-9]+).*$") - { - IsNamed = true - }, new EpisodeExpression(@".*(\\|\/)[sS]?(?[0-9]+)[xX](?[0-9]+)[^\\\/]*$") { IsNamed = true diff --git a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs index 5e023bdb06..921c2b1f57 100644 --- a/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs +++ b/tests/Jellyfin.Naming.Tests/TV/EpisodeNumberTests.cs @@ -66,12 +66,16 @@ namespace Jellyfin.Naming.Tests.TV [InlineData("Season 2/2. Infestation.avi", 2)] [InlineData("The Wonder Years/The.Wonder.Years.S04.PDTV.x264-JCH/The Wonder Years s04e07 Christmas Party NTSC PDTV.avi", 7)] [InlineData("Running Man/Running Man S2017E368.mkv", 368)] + [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] // triple digit episode number + [InlineData("Log Horizon 2/[HorribleSubs] Log Horizon 2 - 03 [720p].mkv", 3)] // digit in series name + [InlineData("Season 1/seriesname 05.mkv", 5)] // no hyphen between series name and episode number + [InlineData("[BBT-RMX] Ranma ½ - 154 [50AC421A].mkv", 154)] // hyphens in the pre-name info, triple digit episode number + // TODO: [InlineData("Case Closed (1996-2007)/Case Closed - 317.mkv", 317)] // triple digit episode number // TODO: [InlineData("Season 2/16 12 Some Title.avi", 16)] // TODO: [InlineData("/The.Legend.of.Condor.Heroes.2017.V2.web-dl.1080p.h264.aac-hdctv/The.Legend.of.Condor.Heroes.2017.E07.V2.web-dl.1080p.h264.aac-hdctv.mkv", 7)] // TODO: [InlineData("Season 4/Uchuu.Senkan.Yamato.2199.E03.avi", 3)] // TODO: [InlineData("Season 2/7 12 Angry Men.avi", 7)] // TODO: [InlineData("Season 02/02x03x04x15 - Ep Name.mp4", 2)] - // TODO: [InlineData("Season 2/[HorribleSubs] Hunter X Hunter - 136 [720p].mkv", 136)] public void GetEpisodeNumberFromFileTest(string path, int? expected) { var result = new EpisodePathParser(_namingOptions) From 13012bfa273a98d06771bc11aeca1d62f9f23307 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 16 Jan 2021 20:08:41 +0000 Subject: [PATCH 0976/1930] Fix bug in GetItemId --- Emby.Dlna/PlayTo/PlayToController.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 311fae2400..315be1e8be 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -896,16 +896,16 @@ namespace Emby.Dlna.PlayTo var parts = url.Split('/'); - for (var i = 0; i < parts.Length; i++) + for (var i = 0; i < parts.Length - 1; i++) { var part = parts[i]; if (string.Equals(part, "audio", StringComparison.OrdinalIgnoreCase) || string.Equals(part, "videos", StringComparison.OrdinalIgnoreCase)) { - if (parts.Length > i + 1) + if (Guid.TryParse(parts[i + 1], out var result)) { - return Guid.Parse(parts[i + 1]); + return result; } } } From 828a9b7c75bbe79c8591c785745851e824589d11 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 17 Jan 2021 23:30:56 +0000 Subject: [PATCH 0977/1930] rollback --- Emby.Dlna/PlayTo/TransportCommands.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 42027b5af7..3cf4b810d3 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -176,12 +176,12 @@ namespace Emby.Dlna.PlayTo if (state != null) { var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ?? - (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : SecurityElement.Escape(value)); + (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : value); return string.Format(CultureInfo.InvariantCulture, "<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}", argument.Name, state.DataType ?? "string", sendValue); } - return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}", argument.Name, SecurityElement.Escape(value)); + return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}", argument.Name, value); } } } From 01836e55e4c0a68500452d604a8a22bd919e590d Mon Sep 17 00:00:00 2001 From: Oriol Serra Date: Sun, 17 Jan 2021 21:33:04 +0000 Subject: [PATCH 0978/1930] Translated using Weblate (Catalan) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ca/ --- .../Localization/Core/ca.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ca.json b/Emby.Server.Implementations/Localization/Core/ca.json index 1439d9b8ed..fd8437b6d9 100644 --- a/Emby.Server.Implementations/Localization/Core/ca.json +++ b/Emby.Server.Implementations/Localization/Core/ca.json @@ -18,10 +18,10 @@ "HeaderAlbumArtists": "Artistes del Àlbum", "HeaderContinueWatching": "Continua Veient", "HeaderFavoriteAlbums": "Àlbums Preferits", - "HeaderFavoriteArtists": "Artistes Preferits", - "HeaderFavoriteEpisodes": "Episodis Preferits", - "HeaderFavoriteShows": "Programes Preferits", - "HeaderFavoriteSongs": "Cançons Preferides", + "HeaderFavoriteArtists": "Artistes Predilectes", + "HeaderFavoriteEpisodes": "Episodis Predilectes", + "HeaderFavoriteShows": "Programes Predilectes", + "HeaderFavoriteSongs": "Cançons Predilectes", "HeaderLiveTV": "TV en Directe", "HeaderNextUp": "A continuació", "HeaderRecordingGroups": "Grups d'Enregistrament", @@ -36,7 +36,7 @@ "MessageApplicationUpdatedTo": "El Servidor de Jellyfin ha estat actualitzat a {0}", "MessageNamedServerConfigurationUpdatedWithValue": "La secció {0} de la configuració del servidor ha estat actualitzada", "MessageServerConfigurationUpdated": "S'ha actualitzat la configuració del servidor", - "MixedContent": "Contingut mesclat", + "MixedContent": "Contingut barrejat", "Movies": "Pel·lícules", "Music": "Música", "MusicVideos": "Vídeos musicals", @@ -76,7 +76,7 @@ "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Els subtítols no s'han pogut baixar de {0} per {1}", "Sync": "Sincronitzar", - "System": "System", + "System": "Sistema", "TvShows": "Espectacles de TV", "User": "User", "UserCreatedWithName": "S'ha creat l'usuari {0}", From 0cb80d3815b9977db1b83bb43d7cc53e604c950b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Jan 2021 12:01:03 +0000 Subject: [PATCH 0979/1930] Bump coverlet.collector from 3.0.0 to 3.0.1 Bumps [coverlet.collector](https://github.com/coverlet-coverage/coverlet) from 3.0.0 to 3.0.1. - [Release notes](https://github.com/coverlet-coverage/coverlet/releases) - [Commits](https://github.com/coverlet-coverage/coverlet/commits) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 07972bb424..7241ad0ee6 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index fdeeda5a31..7ff4d0e87c 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index 84655db24b..af412eed3b 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index c5b01f4db4..21389b926d 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index ed788bab8e..9a1cfcfa41 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index f3b00dcab4..31e41b12f9 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index 8d9c20de1f..ca65398580 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 5c41705142..b242e1dfd6 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -20,7 +20,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index f02ac03f7c..1fadd2126d 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -18,7 +18,7 @@ - + From 4e13b41eedae4e4b0260aee670facbb3c18d5d80 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Jan 2021 12:01:04 +0000 Subject: [PATCH 0980/1930] Bump sharpcompress from 0.26.0 to 0.27.1 Bumps [sharpcompress](https://github.com/adamhathcock/sharpcompress) from 0.26.0 to 0.27.1. - [Release notes](https://github.com/adamhathcock/sharpcompress/releases) - [Commits](https://github.com/adamhathcock/sharpcompress/compare/0.26...0.27.1) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 67f23f055e..08047ba475 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -29,7 +29,7 @@ - + From e81b7c8f4f054aaf5c1f25ea9c9d6986fbd501c3 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 18 Jan 2021 12:17:18 +0000 Subject: [PATCH 0981/1930] reverted --- Emby.Dlna/Didl/DidlBuilder.cs | 3 +-- Emby.Dlna/PlayTo/TransportCommands.cs | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 02bfa6053e..8b50d47fbd 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -96,6 +96,7 @@ namespace Emby.Dlna.Didl using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8)) { + // If this using are changed to single lines, then write.Flush needs to be appended before the return. using (var writer = XmlWriter.Create(builder, settings)) { // writer.WriteStartDocument(); @@ -113,8 +114,6 @@ namespace Emby.Dlna.Didl writer.WriteFullEndElement(); // writer.WriteEndDocument(); - - writer.Flush(); } return builder.ToString(); diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 3cf4b810d3..0865968ad1 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Security; using System.Xml.Linq; using Emby.Dlna.Common; using Emby.Dlna.Ssdp; From 49e3b70722abe8982da015f3a57d9a23b984ea59 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 18 Jan 2021 13:03:37 +0000 Subject: [PATCH 0982/1930] Moved InternalsVisibleTo --- .../Extensions/ApiServiceCollectionExtensions.cs | 2 -- Jellyfin.Server/Jellyfin.Server.csproj | 6 ------ Jellyfin.Server/Properties/AssemblyInfo.cs | 3 +++ 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index bd72b1e27d..73a2265dec 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -43,8 +43,6 @@ using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using AuthenticationSchemes = Jellyfin.Api.Constants.AuthenticationSchemes; -[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] - namespace Jellyfin.Server.Extensions { /// diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index f91f2db02b..5940cf9389 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -73,10 +73,4 @@ - - - <_Parameter1>Jellyfin.Api.Tests - - - diff --git a/Jellyfin.Server/Properties/AssemblyInfo.cs b/Jellyfin.Server/Properties/AssemblyInfo.cs index 5de1e653d9..7abf298b12 100644 --- a/Jellyfin.Server/Properties/AssemblyInfo.cs +++ b/Jellyfin.Server/Properties/AssemblyInfo.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Resources; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -19,3 +20,5 @@ using System.Runtime.InteropServices; // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] + +[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] From 1455c2aa101ea80ba772b648f869c73cac655830 Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 18 Jan 2021 06:47:18 -0700 Subject: [PATCH 0983/1930] Remove commented code --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 168c8fea06..839b62448b 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -143,8 +143,6 @@ namespace Emby.Server.Implementations.TV var allNextUp = seriesKeys .Select(i => GetNextUp(i, currentUser, dtoOptions)); - // allNextUp = allNextUp.OrderByDescending(i => i.Item1); - // If viewing all next up for all series, remove first episodes // But if that returns empty, keep those first episodes (avoid completely empty view) var alwaysEnableFirstEpisode = !string.IsNullOrEmpty(request.SeriesId); From 6abee2dd221b81a4651745ef959fbf590c82c280 Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 18 Jan 2021 19:42:50 -0700 Subject: [PATCH 0984/1930] fix delete log task --- .../ScheduledTasks/Tasks/DeleteLogFileTask.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs index 184d155d44..fedb5deb01 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/DeleteLogFileTask.cs @@ -80,10 +80,11 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks // Delete log files more than n days old var minDateModified = DateTime.UtcNow.AddDays(-_configurationManager.CommonConfiguration.LogFileRetentionDays); - // Only delete the .txt log files, the *.log files created by serilog get managed by itself - var filesToDelete = _fileSystem.GetFiles(_configurationManager.CommonApplicationPaths.LogDirectoryPath, new[] { ".txt" }, true, true) - .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified) - .ToList(); + // Only delete files that serilog doesn't manage (anything that doesn't start with 'log_' + var filesToDelete = _fileSystem.GetFiles(_configurationManager.CommonApplicationPaths.LogDirectoryPath, true) + .Where(f => !f.Name.StartsWith("log_", StringComparison.Ordinal) + && _fileSystem.GetLastWriteTimeUtc(f) < minDateModified) + .ToList(); var index = 0; From 8b2b3b77a548bf5e46e1cb6931ecaaf81a8ca751 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 10:29:17 +0000 Subject: [PATCH 0985/1930] Removed duplication --- .../ApiServiceCollectionExtensions.cs | 62 ++++++++----------- 1 file changed, 26 insertions(+), 36 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 73a2265dec..9b4e53fc09 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -174,6 +174,30 @@ namespace Jellyfin.Server.Extensions .AddScheme(AuthenticationSchemes.CustomAuthentication, null); } + private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength, bool systemIP6Enabled) + { + if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + { + return; + } + + if (systemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) + { + // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. + // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . + addr = addr.MapToIPv6(); + } + + if (prefixLength == 32) + { + options.KnownProxies.Add(addr); + } + else + { + options.KnownNetworks.Add(new IPNetwork(addr, prefixLength)); + } + } + /// /// Sets up the proxy configuration based on the addresses in . /// @@ -187,47 +211,13 @@ namespace Jellyfin.Server.Extensions { if (IPNetAddress.TryParse(userList[i], out var addr)) { - if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) - || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) - { - continue; - } - - if (networkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) - { - // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. - // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . - addr.Address = addr.Address.MapToIPv6(); - } - - if (addr.PrefixLength == 32) - { - options.KnownProxies.Add(addr.Address); - } - else - { - options.KnownNetworks.Add(new IPNetwork(addr.Address, addr.PrefixLength)); - } + AddIpAddress(config, options, addr.Address, addr.PrefixLength, networkManager.SystemIP6Enabled); } else if (IPHost.TryParse(userList[i], out var host)) { foreach (var address in host.GetAddresses()) { - if ((!config.EnableIPV4 && address.AddressFamily == AddressFamily.InterNetwork) - || (!config.EnableIPV6 && address.AddressFamily == AddressFamily.InterNetworkV6)) - { - continue; - } - - var hostAddr = address; - if (networkManager.SystemIP6Enabled && address.AddressFamily == AddressFamily.InterNetwork) - { - // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. - // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . - hostAddr = address.MapToIPv6(); - } - - options.KnownProxies.Add(hostAddr); + AddIpAddress(config, options, addr.Address, addr.PrefixLength, networkManager.SystemIP6Enabled); } } } From 6a7623da02045bb8600bc2aad3047a4debda03f1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 10:36:37 +0000 Subject: [PATCH 0986/1930] Simplified Code --- Jellyfin.Networking/Manager/NetworkManager.cs | 20 ++-- .../ApiServiceCollectionExtensions.cs | 103 +++++++++--------- Jellyfin.Server/Startup.cs | 8 +- MediaBrowser.Common/Net/INetworkManager.cs | 10 -- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 4 +- 5 files changed, 65 insertions(+), 80 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index c9f900660b..34b1f0daaf 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -129,6 +129,16 @@ namespace Jellyfin.Networking.Manager /// public static string MockNetworkSettings { get; set; } = string.Empty; + /// + /// Gets or sets a value indicating whether the system has IP4 is enabled. + /// + public static bool SystemIP4Enabled { get; set; } + + /// + /// Gets or sets a value indicating whether the system has IP6 is enabled. + /// + public static bool SystemIP6Enabled { get; set; } + /// /// Gets or sets a value indicating whether IP6 is enabled. /// @@ -139,16 +149,6 @@ namespace Jellyfin.Networking.Manager /// public bool IsIP4Enabled { get; set; } - /// - /// Gets or sets a value indicating whether the system has IP4 is enabled. - /// - public bool SystemIP4Enabled { get; set; } - - /// - /// Gets or sets a value indicating whether the system has IP6 is enabled. - /// - public bool SystemIP6Enabled { get; set; } - /// public Collection RemoteAddressFilter { get; private set; } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 9b4e53fc09..0a7ae9a410 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -25,6 +25,7 @@ using Jellyfin.Api.Controllers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Manager; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -174,64 +175,14 @@ namespace Jellyfin.Server.Extensions .AddScheme(AuthenticationSchemes.CustomAuthentication, null); } - private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength, bool systemIP6Enabled) - { - if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) - { - return; - } - - if (systemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) - { - // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. - // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . - addr = addr.MapToIPv6(); - } - - if (prefixLength == 32) - { - options.KnownProxies.Add(addr); - } - else - { - options.KnownNetworks.Add(new IPNetwork(addr, prefixLength)); - } - } - - /// - /// Sets up the proxy configuration based on the addresses in . - /// - /// The instance. - /// The containing the config settings. - /// The string array to parse. - /// The instance. - internal static void ParseList(INetworkManager networkManager, NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) - { - for (var i = 0; i < userList.Length; i++) - { - if (IPNetAddress.TryParse(userList[i], out var addr)) - { - AddIpAddress(config, options, addr.Address, addr.PrefixLength, networkManager.SystemIP6Enabled); - } - else if (IPHost.TryParse(userList[i], out var host)) - { - foreach (var address in host.GetAddresses()) - { - AddIpAddress(config, options, addr.Address, addr.PrefixLength, networkManager.SystemIP6Enabled); - } - } - } - } - /// /// Extension method for adding the jellyfin API to the service collection. /// /// The service collection. /// An IEnumerable containing all plugin assemblies with API controllers. /// The . - /// The instance. /// The MVC builder. - public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable pluginAssemblies, NetworkConfiguration config, INetworkManager networkManager) + public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable pluginAssemblies, NetworkConfiguration config) { IMvcBuilder mvcBuilder = serviceCollection .AddCors() @@ -249,7 +200,7 @@ namespace Jellyfin.Server.Extensions } else { - ParseList(networkManager, config, config.KnownProxies, options); + ParseList(config, config.KnownProxies, options); } // Only set forward limit if we have some known proxies or some known networks. @@ -370,6 +321,54 @@ namespace Jellyfin.Server.Extensions }); } + /// + /// Sets up the proxy configuration based on the addresses in . + /// + /// The containing the config settings. + /// The string array to parse. + /// The instance. + internal static void ParseList(NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) + { + for (var i = 0; i < userList.Length; i++) + { + if (IPNetAddress.TryParse(userList[i], out var addr)) + { + AddIpAddress(config, options, addr.Address, addr.PrefixLength); + } + else if (IPHost.TryParse(userList[i], out var host)) + { + foreach (var address in host.GetAddresses()) + { + AddIpAddress(config, options, addr.Address, addr.PrefixLength); + } + } + } + } + + private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) + { + if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + { + return; + } + + if (NetworkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) + { + // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. + // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . + addr = addr.MapToIPv6(); + } + + if (prefixLength == 32) + { + options.KnownProxies.Add(addr); + } + else + { + options.KnownNetworks.Add(new IPNetwork(addr, prefixLength)); + } + } + private static void AddSwaggerTypeMappings(this SwaggerGenOptions options) { /* diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 05228ccaab..e56e61092b 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -26,22 +26,18 @@ namespace Jellyfin.Server { private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IServerApplicationHost _serverApplicationHost; - private readonly INetworkManager _networkManager; /// /// Initializes a new instance of the class. /// /// The server configuration manager. /// The server application host. - /// The network manager. public Startup( IServerConfigurationManager serverConfigurationManager, - IServerApplicationHost serverApplicationHost, - INetworkManager networkManager) + IServerApplicationHost serverApplicationHost) { _serverConfigurationManager = serverConfigurationManager; _serverApplicationHost = serverApplicationHost; - _networkManager = networkManager; } /// @@ -56,7 +52,7 @@ namespace Jellyfin.Server { options.HttpsPort = _serverApplicationHost.HttpsPort; }); - services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration(), _networkManager); + services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration()); services.AddJellyfinApiSwagger(); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 7ee76107bc..b6c390d239 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -44,16 +44,6 @@ namespace MediaBrowser.Common.Net /// bool IsIP4Enabled { get; set; } - /// - /// Gets or sets a value indicating whether the system has IP4 is enabled. - /// - bool SystemIP4Enabled { get; set; } - - /// - /// Gets or sets a value indicating whether the system has IP6 is enabled. - /// - bool SystemIP6Enabled { get; set; } - /// /// Calculates the list of interfaces to use for Kestrel. /// diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index 6ee66d2a8f..a76b8b2439 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -30,7 +30,7 @@ namespace Jellyfin.Api.Tests public void TestNetworks(bool ip4, bool ip6, string hostList, string match) { using var nm = CreateNetworkManager(); - nm.SystemIP6Enabled = ip6; + NetworkManager.SystemIP6Enabled = ip6; var settings = new NetworkConfiguration { @@ -45,7 +45,7 @@ namespace Jellyfin.Api.Tests options.KnownProxies.Clear(); options.KnownNetworks.Clear(); - ApiServiceCollectionExtensions.ParseList(nm, settings, hostList.Split(","), options); + ApiServiceCollectionExtensions.ParseList(settings, hostList.Split(","), options); var sb = new StringBuilder(); foreach (var item in options.KnownProxies) From dd089fd27ab20755b7cac1e71fa328dddbfe2c68 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 10:50:17 +0000 Subject: [PATCH 0987/1930] Changed test --- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index a76b8b2439..6717137d9d 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -50,19 +50,19 @@ namespace Jellyfin.Api.Tests var sb = new StringBuilder(); foreach (var item in options.KnownProxies) { - sb.Append(item.ToString()); + sb.Append(item); sb.Append(','); } foreach (var item in options.KnownNetworks) { - sb.Append(item.Prefix.ToString()); + sb.Append(item.Prefix); sb.Append('/'); sb.Append(item.PrefixLength.ToString(CultureInfo.InvariantCulture)); sb.Append(','); } - Assert.True(string.Equals(sb.ToString(), result, StringComparison.OrdinalIgnoreCase), "Not matched: " + sb.ToString() + " does not match " + result); + Assert.Equal(sb.ToString(), result); } private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) @@ -72,7 +72,7 @@ namespace Jellyfin.Api.Tests CallBase = true }; configManager.Setup(x => x.GetConfiguration(It.IsAny())).Returns(conf); - return (IConfigurationManager)configManager.Object; + return configManager.Object; } private static NetworkManager CreateNetworkManager() From 821473557c7747e4029cddc4f562ae3f207508d7 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 11:31:40 +0000 Subject: [PATCH 0988/1930] Changed mapping logic --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 0a7ae9a410..0e68c523fc 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -352,7 +352,8 @@ namespace Jellyfin.Server.Extensions return; } - if (NetworkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork) + // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address. + if (NetworkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6) { // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . From 82d365045a0c7bf9acfa8c62433b5ec68d7b34a5 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 12:50:11 +0000 Subject: [PATCH 0989/1930] Removed systemIp6 functionality. --- Jellyfin.Networking/Manager/NetworkManager.cs | 12 ------------ .../Extensions/ApiServiceCollectionExtensions.cs | 2 +- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 1 - 3 files changed, 1 insertion(+), 14 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 34b1f0daaf..349a30ed3e 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -129,16 +129,6 @@ namespace Jellyfin.Networking.Manager /// public static string MockNetworkSettings { get; set; } = string.Empty; - /// - /// Gets or sets a value indicating whether the system has IP4 is enabled. - /// - public static bool SystemIP4Enabled { get; set; } - - /// - /// Gets or sets a value indicating whether the system has IP6 is enabled. - /// - public static bool SystemIP6Enabled { get; set; } - /// /// Gets or sets a value indicating whether IP6 is enabled. /// @@ -1059,7 +1049,6 @@ namespace Jellyfin.Networking.Manager { if (info.Address.AddressFamily == AddressFamily.InterNetwork) { - SystemIP4Enabled = true; if (IsIP4Enabled) { IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) @@ -1084,7 +1073,6 @@ namespace Jellyfin.Networking.Manager } else if (info.Address.AddressFamily == AddressFamily.InterNetworkV6) { - SystemIP6Enabled = true; if (IsIP6Enabled) { IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 0e68c523fc..f8626b6e0e 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -353,7 +353,7 @@ namespace Jellyfin.Server.Extensions } // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address. - if (NetworkManager.SystemIP6Enabled && addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6) + if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6) { // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format. // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 . diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index 6717137d9d..039c393770 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -30,7 +30,6 @@ namespace Jellyfin.Api.Tests public void TestNetworks(bool ip4, bool ip6, string hostList, string match) { using var nm = CreateNetworkManager(); - NetworkManager.SystemIP6Enabled = ip6; var settings = new NetworkConfiguration { From 9db8a4d88dd276c907cb44eddd3633f8ec83989a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 13:56:16 +0000 Subject: [PATCH 0990/1930] reverted --- Jellyfin.Networking/Manager/NetworkManager.cs | 70 +++++++++---------- 1 file changed, 32 insertions(+), 38 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 349a30ed3e..60b899519e 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1047,53 +1047,47 @@ namespace Jellyfin.Networking.Manager // populate interface address list foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) { - if (info.Address.AddressFamily == AddressFamily.InterNetwork) + if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { - if (IsIP4Enabled) + IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) { - IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv4Properties().Index - }; + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv4Properties().Index + }; - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } - else if (info.Address.AddressFamily == AddressFamily.InterNetworkV6) + else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) { - if (IsIP6Enabled) + IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) { - IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv6Properties().Index - }; + // Keep the number of gateways on this interface, along with its index. + Tag = ipProperties.GetIPv6Properties().Index + }; - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + int tag = nw.Tag; + if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) + { + // -ve Tags signify the interface has a gateway. + nw.Tag *= -1; } + + _interfaceAddresses.AddItem(nw); + + // Store interface name so we can use the name in Collections. + _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; + _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; } } } From ab632b96fe64e9803bde8387b80aca2deeb478bf Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 19:29:51 +0000 Subject: [PATCH 0991/1930] renamed. --- .../Extensions/ApiServiceCollectionExtensions.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index f8626b6e0e..4f65a31e07 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -200,7 +200,7 @@ namespace Jellyfin.Server.Extensions } else { - ParseList(config, config.KnownProxies, options); + AddProxyAddresses(config, config.KnownProxies, options); } // Only set forward limit if we have some known proxies or some known networks. @@ -322,20 +322,20 @@ namespace Jellyfin.Server.Extensions } /// - /// Sets up the proxy configuration based on the addresses in . + /// Sets up the proxy configuration based on the addresses in . /// /// The containing the config settings. - /// The string array to parse. + /// The string array to parse. /// The instance. - internal static void ParseList(NetworkConfiguration config, string[] userList, ForwardedHeadersOptions options) + internal static void AddProxyAddresses(NetworkConfiguration config, string[] allowedProxies, ForwardedHeadersOptions options) { - for (var i = 0; i < userList.Length; i++) + for (var i = 0; i < allowedProxies.Length; i++) { - if (IPNetAddress.TryParse(userList[i], out var addr)) + if (IPNetAddress.TryParse(allowedProxies[i], out var addr)) { AddIpAddress(config, options, addr.Address, addr.PrefixLength); } - else if (IPHost.TryParse(userList[i], out var host)) + else if (IPHost.TryParse(allowedProxies[i], out var host)) { foreach (var address in host.GetAddresses()) { From 25eaf21a8f79ca49bfc0b29f521c5429093e7e50 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 19:32:46 +0000 Subject: [PATCH 0992/1930] renamed func in test --- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index 039c393770..6c3fd0ee10 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -44,7 +44,7 @@ namespace Jellyfin.Api.Tests options.KnownProxies.Clear(); options.KnownNetworks.Clear(); - ApiServiceCollectionExtensions.ParseList(settings, hostList.Split(","), options); + ApiServiceCollectionExtensions.AddProxyAddresses(settings, hostList.Split(","), options); var sb = new StringBuilder(); foreach (var item in options.KnownProxies) From 89046e1d97f5d01dfbacab64bc7713d6487f3de9 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 19 Jan 2021 21:15:40 +0000 Subject: [PATCH 0993/1930] Bug fixes --- Emby.Server.Implementations/Plugins/PluginManager.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 1ab01252d0..9f597f3ef3 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -374,7 +374,7 @@ namespace Emby.Server.Implementations.Plugins private LocalPlugin? GetPluginByAssembly(Assembly assembly) { // Find which plugin it is by the path. - return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(assembly.Location), StringComparison.Ordinal)); + return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal)); } /// @@ -421,15 +421,17 @@ namespace Emby.Server.Implementations.Plugins { plugin.Instance = instance; var manifest = plugin.Manifest; - var pluginStr = plugin.Instance.Version.ToString(); + var pluginStr = instance.Version.ToString(); bool changed = false; - if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)) + if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal) + || manifest.Id != instance.Id) { // If a plugin without a manifest failed to load due to an external issue (eg config), // this updates the manifest to the actual plugin values. manifest.Version = pluginStr; manifest.Name = plugin.Instance.Name; manifest.Description = plugin.Instance.Description; + manifest.Id = plugin.Instance.Id; changed = true; } @@ -559,7 +561,7 @@ namespace Emby.Server.Implementations.Plugins // Auto-create a plugin manifest, so we can disable it, if it fails to load. manifest = new PluginManifest { - Status = PluginStatus.Restart, + Status = PluginStatus.Active, Name = metafile, AutoUpdate = false, Id = metafile.GetMD5(), From b3059238e3c9f8c2c5f8b2370a0dbd2562edc8f4 Mon Sep 17 00:00:00 2001 From: AdmiralAnimE Date: Wed, 20 Jan 2021 06:50:47 +0000 Subject: [PATCH 0994/1930] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index 1fed832768..a036d9f12e 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -8,7 +8,7 @@ "CameraImageUploadedFrom": "Нова снимка от камера беше качена от {0}", "Channels": "Канали", "ChapterNameValue": "Глава {0}", - "Collections": "Колекции", + "Collections": "Поредици", "DeviceOfflineWithName": "{0} се разкачи", "DeviceOnlineWithName": "{0} е свързан", "FailedLoginAttemptWithUserName": "Неуспешен опит за влизане от {0}", From 27cbd14377a40ff0efa385baf2e0fdf5b112ac0c Mon Sep 17 00:00:00 2001 From: AdmiralAnimE Date: Wed, 20 Jan 2021 11:02:46 +0000 Subject: [PATCH 0995/1930] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index a036d9f12e..7ff30df710 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -113,5 +113,8 @@ "TasksChannelsCategory": "Интернет Канали", "TasksApplicationCategory": "Приложение", "TasksLibraryCategory": "Библиотека", - "TasksMaintenanceCategory": "Поддръжка" + "TasksMaintenanceCategory": "Поддръжка", + "Undefined": "Неопределено", + "Forced": "Принудително", + "Default": "По подразбиране" } From 07613f0821bc38cddee44bf75cbf5920ac53a5f6 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 15:50:38 +0000 Subject: [PATCH 0996/1930] Translated using Weblate (German) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/de/ --- Emby.Server.Implementations/Localization/Core/de.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/de.json b/Emby.Server.Implementations/Localization/Core/de.json index 4a505d0b3c..9d82b58784 100644 --- a/Emby.Server.Implementations/Localization/Core/de.json +++ b/Emby.Server.Implementations/Localization/Core/de.json @@ -3,7 +3,7 @@ "AppDeviceValues": "App: {0}, Gerät: {1}", "Application": "Anwendung", "Artists": "Interpreten", - "AuthenticationSucceededWithUserName": "{0} hat sich erfolgreich angemeldet", + "AuthenticationSucceededWithUserName": "{0} wurde angemeldet", "Books": "Bücher", "CameraImageUploadedFrom": "Ein neues Kamerafoto wurde von {0} hochgeladen", "Channels": "Kanäle", From 0279af5f6b75b116355de56b1d7e5ee3add2491e Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 19:46:44 +0100 Subject: [PATCH 0997/1930] Move existing tests to correct namespace --- .../Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs | 2 +- .../Parsers/MusicArtistNfoParserTests.cs | 2 +- .../Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 7651653a1b..e1f50876fb 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; -namespace Jellyfin.XbmcMetadata.Parsers.Tests +namespace Jellyfin.XbmcMetadata.Tests.Parsers { public class MovieNfoParserTests { diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs index a8c6e5afd8..2a4d376c6b 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs @@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; -namespace Jellyfin.XbmcMetadata.Parsers.Tests +namespace Jellyfin.XbmcMetadata.Tests.Parsers { public class MusicArtistNfoParserTests { diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs index 37ca0fd059..3bbfb66e3e 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs @@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; -namespace Jellyfin.XbmcMetadata.Parsers.Tests +namespace Jellyfin.XbmcMetadata.Tests.Parsers { public class SeriesNfoParserTests { From dbd70bd3947788281d2a225c0d6f2f8161953427 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 19:47:31 +0100 Subject: [PATCH 0998/1930] Add episode nfo parser test --- .../Parsers/EpisodeNfoParser.cs | 12 ++ .../Savers/EpisodeNfoSaver.cs | 5 +- .../Parsers/EpisodeNfoProviderTests.cs | 103 ++++++++++++++++ .../Test Data/The Bone Orchard.nfo | 111 ++++++++++++++++++ 4 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index bce4cf0093..dffea3fe67 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -208,6 +208,18 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "showtitle": + { + var showtitle = reader.ReadElementContentAsString(); + + if (!string.IsNullOrWhiteSpace(showtitle)) + { + item.SeriesName = showtitle; + } + + break; + } + default: base.FetchDataFromXmlNode(reader, itemResult); break; diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs index ac2fbb8d24..5d3d17893a 100644 --- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs @@ -56,6 +56,8 @@ namespace MediaBrowser.XbmcMetadata.Savers { var episode = (Episode)item; + writer.WriteElementString("showtitle", episode.SeriesName); + if (episode.IndexNumber.HasValue) { writer.WriteElementString("episode", episode.IndexNumber.Value.ToString(_usCulture)); @@ -122,7 +124,8 @@ namespace MediaBrowser.XbmcMetadata.Savers "airsbefore_episode", "airsbefore_season", "displayseason", - "displayepisode" + "displayepisode", + "showtitle" }); return list; diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs new file mode 100644 index 0000000000..67b4b969a3 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs @@ -0,0 +1,103 @@ +using System; +using System.Linq; +using System.Threading; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.XbmcMetadata.Parsers; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +#pragma warning disable CA5369 + +namespace Jellyfin.XbmcMetadata.Tests.Parsers +{ + public class EpisodeNfoProviderTests + { + private readonly EpisodeNfoParser _parser; + + public EpisodeNfoProviderTests() + { + var providerManager = new Mock(); + providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny())) + .Returns(Enumerable.Empty()); + var config = new Mock(); + config.Setup(x => x.GetConfiguration(It.IsAny())) + .Returns(new XbmcMetadataOptions()); + _parser = new EpisodeNfoParser(new NullLogger(), config.Object, providerManager.Object); + } + + [Fact] + public void Fetch_Valid_Succes() + { + var result = new MetadataResult() + { + Item = new Episode() + }; + + _parser.Fetch(result, "Test Data/The Bone Orchard.nfo", CancellationToken.None); + + var item = result.Item; + Assert.Equal("The Bone Orchard", item.Name); + Assert.Equal("American Gods", item.SeriesName); + Assert.Equal(1, item.IndexNumber); + Assert.Equal(1, item.ParentIndexNumber); + Assert.Equal("When Shadow Moon is released from prison early after the death of his wife, he meets Mr. Wednesday and is recruited as his bodyguard. Shadow discovers that this may be more than he bargained for.", item.Overview); + Assert.Equal(0, item.RunTimeTicks); + Assert.Equal("16", item.OfficialRating); + Assert.Contains("Drama", item.Genres); + Assert.Contains("Mystery", item.Genres); + Assert.Contains("Sci-Fi & Fantasy", item.Genres); + Assert.Equal(new DateTime(2017, 4, 30), item.PremiereDate); + Assert.Equal(2017, item.ProductionYear); + Assert.Single(item.Studios); + Assert.Contains("Starz", item.Studios); + + // Credits + var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray(); + Assert.Equal(2, writers.Length); + Assert.Contains("Bryan Fuller", writers.Select(x => x.Name)); + Assert.Contains("Michael Green", writers.Select(x => x.Name)); + + // Direcotrs + var directors = result.People.Where(x => x.Type == PersonType.Director).ToArray(); + Assert.Single(directors); + Assert.Contains("David Slade", directors.Select(x => x.Name)); + + // Actors + var actors = result.People.Where(x => x.Type == PersonType.Actor).ToArray(); + Assert.Equal(11, actors.Length); + // Only test one actor + var shadow = actors.FirstOrDefault(x => x.Role.Equals("Shadow Moon", StringComparison.Ordinal)); + Assert.NotNull(shadow); + Assert.Equal("Ricky Whittle", shadow!.Name); + Assert.Equal(0, shadow!.SortOrder); + Assert.Equal("http://image.tmdb.org/t/p/original/cjeDbVfBp6Qvb3C74Dfy7BKDTQN.jpg", shadow!.ImageUrl); + + Assert.Equal(new DateTime(2017, 10, 7, 14, 25, 47), item.DateCreated); + } + + [Fact] + public void Fetch_WithNullItem_ThrowsArgumentException() + { + var result = new MetadataResult(); + + Assert.Throws(() => _parser.Fetch(result, "Test Data/The Bone Orchard.nfo", CancellationToken.None)); + } + + [Fact] + public void Fetch_NullResult_ThrowsArgumentException() + { + var result = new MetadataResult() + { + Item = new Episode() + }; + + Assert.Throws(() => _parser.Fetch(result, string.Empty, CancellationToken.None)); + } + } +} diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo new file mode 100644 index 0000000000..e77c02a349 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Bone Orchard.nfo @@ -0,0 +1,111 @@ + + + The Bone Orchard + American Gods + + + 7.532000 + 31 + + + 0 + 0 + 1 + 1 + -1 + -1 + + When Shadow Moon is released from prison early after the death of his wife, he meets Mr. Wednesday and is recruited as his bodyguard. Shadow discovers that this may be more than he bargained for. + + 0 + http://image.tmdb.org/t/p/original/uvry4weK00pFLn7fxQ9M4m3Da2A.jpg + 16 + 0 + + 1276153 + 1276153 + Drama + Mystery + Sci-Fi & Fantasy + Bryan Fuller + Michael Green + David Slade + 2017-04-30 + 2017 + + + 2017-04-30 + Starz + + + Jonathan Tucker + 'Low Key' Lyesmith + 10 + http://image.tmdb.org/t/p/original/jvJpYDbwmUTACw7Yn7PKOP6CdlJ.jpg + + + Demore Barnes + Mr. Ibis + 11 + http://image.tmdb.org/t/p/original/4rEVzSIFPgiN14xYQnjKcKQ7tYE.jpg + + + Betty Gilpin + Audrey + 12 + http://image.tmdb.org/t/p/original/xFeqyem5i4Kf0nFjBZ4Oi9NM26k.jpg + + + Beth Grant + Jack + 13 + http://image.tmdb.org/t/p/original/zAT9GvzJE0ytL3C36L461cgKI9p.jpg + + + Joel Murray + Paunch + 14 + http://image.tmdb.org/t/p/original/t5syYfCgxbTC7XPrNeXhhhQULUf.jpg + + + Ricky Whittle + Shadow Moon + 0 + http://image.tmdb.org/t/p/original/cjeDbVfBp6Qvb3C74Dfy7BKDTQN.jpg + + + Ian McShane + Mr. Wednesday + 1 + http://image.tmdb.org/t/p/original/pY9ud4BJwHekNiO4MMItPbgkdAy.jpg + + + Emily Browning + Laura Moon + 2 + http://image.tmdb.org/t/p/original/fa1Kyj02wxwcdS6EHb2i27TNXvU.jpg + + + Pablo Schreiber + Mad Sweeney + 3 + http://image.tmdb.org/t/p/original/uo8YljeePz3pbj7gvWXdB4gOOW4.jpg + + + Bruce Langley + Technical Boy + 4 + http://image.tmdb.org/t/p/original/f4EOWUmznLqboq8Ce7jnlkHVK3Y.jpg + + + Yetide Badaki + Bilquis + 5 + http://image.tmdb.org/t/p/original/qfzkREHuI1JvMxBteIAjKX8qMEr.jpg + + + 0.000000 + 0.000000 + + 2017-10-07 14:25:47 + From ccea02fbb2a946e600c1feb53ab50cc6e5fd45f2 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 20:02:03 +0100 Subject: [PATCH 0999/1930] Add season nfo parser test --- .../Parsers/SeasonNfoProviderTests.cs | 83 ++++++++++++++++++ .../Test Data/Season 01.nfo | 86 +++++++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs new file mode 100644 index 0000000000..68b7239d22 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs @@ -0,0 +1,83 @@ +#pragma warning disable CA5369 + +using System; +using System.Linq; +using System.Threading; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.XbmcMetadata.Parsers; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.XbmcMetadata.Tests.Parsers +{ + public class SeasonNfoProviderTests + { + private readonly SeasonNfoParser _parser; + + public SeasonNfoProviderTests() + { + var providerManager = new Mock(); + providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny())) + .Returns(Enumerable.Empty()); + var config = new Mock(); + config.Setup(x => x.GetConfiguration(It.IsAny())) + .Returns(new XbmcMetadataOptions()); + _parser = new SeasonNfoParser(new NullLogger(), config.Object, providerManager.Object); + } + + [Fact] + public void Fetch_Valid_Succes() + { + var result = new MetadataResult() + { + Item = new Season() + }; + + _parser.Fetch(result, "Test Data/Season 01.nfo", CancellationToken.None); + var item = result.Item; + + Assert.Equal("Season 1", item.Name); + Assert.Equal(1, item.IndexNumber); + Assert.False(item.IsLocked); + Assert.Equal(2019, item.ProductionYear); + Assert.Equal(new DateTime(2019, 11, 08), item.PremiereDate); + Assert.Equal(new DateTime(2020, 06, 14, 17, 26, 51), item.DateCreated); + + Assert.Equal(10, result.People.Count); + + Assert.True(result.People.All(x => x.Type == PersonType.Actor)); + + // Only test one actor + var nini = result.People.FirstOrDefault(x => x.Role.Equals("Nini", StringComparison.Ordinal)); + Assert.NotNull(nini); + Assert.Equal("Olivia Rodrigo", nini!.Name); + Assert.Equal(0, nini!.SortOrder); + Assert.Equal("/config/metadata/People/O/Olivia Rodrigo/poster.jpg", nini!.ImageUrl); + } + + [Fact] + public void Fetch_WithNullItem_ThrowsArgumentException() + { + var result = new MetadataResult(); + + Assert.Throws(() => _parser.Fetch(result, "Test Data/Season 01.nfo", CancellationToken.None)); + } + + [Fact] + public void Fetch_NullResult_ThrowsArgumentException() + { + var result = new MetadataResult() + { + Item = new Season() + }; + + Assert.Throws(() => _parser.Fetch(result, string.Empty, CancellationToken.None)); + } + } +} diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo new file mode 100644 index 0000000000..91f0392f4d --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Season 01.nfo @@ -0,0 +1,86 @@ + + + + + false + 2020-06-14 17:26:51 + Season 1 + 2019 + 359728 + 2019-11-08 + 2019-11-08 + + /media/Serien/High School Musical The Musical The Series (2019)/Season 1/Season 1.jpeg + + + Olivia Rodrigo + Nini + Actor + 0 + /config/metadata/People/O/Olivia Rodrigo/poster.jpg + + + Kate Reinders + Miss Jenn + Actor + 1 + /config/metadata/People/K/Kate Reinders/poster.jpg + + + Sofia Wylie + Gina + Actor + 2 + /config/metadata/People/S/Sofia Wylie/poster.jpg + + + Matt Cornett + E.J. + Actor + 3 + /config/metadata/People/M/Matt Cornett/poster.jpg + + + Dara Reneé + Kourtney + Actor + 4 + /config/metadata/People/D/Dara Reneé/poster.jpg + + + Julia Lester + Ashlyn + Actor + 5 + /config/metadata/People/J/Julia Lester/poster.jpg + + + Joshua Bassett + Ricky + Actor + 6 + /config/metadata/People/J/Joshua Bassett/poster.jpg + + + Frankie A. Rodriguez + Carlos + Actor + 7 + /config/metadata/People/F/Frankie A. Rodriguez/poster.jpg + + + Larry Saperstein + Big Red + Actor + 8 + /config/metadata/People/L/Larry Saperstein/poster.jpg + + + Mark St. Cyr + Mr. Mazzara + Actor + 9 + /config/metadata/People/M/Mark St. Cyr/poster.jpg + + 1 + From d71dce50ca1114c19576beeb2d3bbfcbbe341c62 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 20:02:35 +0100 Subject: [PATCH 1000/1930] Add music album nfo parser test --- .../Parsers/MusicAlbumNfoProviderTests.cs | 72 +++++++++++++++++++ .../Test Data/The Best of 1980-1990.nfo | 29 ++++++++ 2 files changed, 101 insertions(+) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs new file mode 100644 index 0000000000..bdffea560c --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs @@ -0,0 +1,72 @@ +#pragma warning disable CA5369 + +using System; +using System.Linq; +using System.Threading; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Providers; +using MediaBrowser.XbmcMetadata.Parsers; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.XbmcMetadata.Tests.Parsers +{ + public class MusicAlbumNfoProviderTests + { + private readonly BaseNfoParser _parser; + + public MusicAlbumNfoProviderTests() + { + var providerManager = new Mock(); + providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny())) + .Returns(Enumerable.Empty()); + var config = new Mock(); + config.Setup(x => x.GetConfiguration(It.IsAny())) + .Returns(new XbmcMetadataOptions()); + _parser = new BaseNfoParser(new NullLogger>(), config.Object, providerManager.Object); + } + + [Fact] + public void Fetch_Valid_Succes() + { + var result = new MetadataResult() + { + Item = new MusicAlbum() + }; + + _parser.Fetch(result, "Test Data/The Best of 1980-1990.nfo", CancellationToken.None); + var item = result.Item; + + Assert.Equal("The Best of 1980-1990", item.Name); + Assert.Equal(1989, item.ProductionYear); + Assert.Contains("Pop", item.Genres); + Assert.Single(item.Genres); + Assert.Contains("Rock/Pop", item.Tags); + Assert.Equal("The Best of 1980-1990 is the first greatest hits compilation by Irish rock band U2, released in November 1998. It mostly contains the group's hit singles from the eighties but also mixes in some live staples as well as one new recording, Sweetest Thing. In April 1999, a companion video (featuring music videos and live footage) was released. The album was followed by another compilation, The Best of 1990-2000, in 2002.\nA limited edition version containing a special B-sides disc was released on the same date as the single-disc version. At the time of release, the official word was that the 2-disc album would be available the first week the album went on sale, then pulled from the stores. While this threat never materialized, it did result in the 2-disc version being in very high demand. Both versions charted in the Billboard 200.\nThe boy on the cover is Peter Rowan, brother of Bono's friend Guggi (real name Derek Rowan) of the Virgin Prunes. He also appears on the covers of the early EP Three, two of the band's first three albums (Boy and War), and Early Demos.", item.Overview); + } + + [Fact] + public void Fetch_WithNullItem_ThrowsArgumentException() + { + var result = new MetadataResult(); + + Assert.Throws(() => _parser.Fetch(result, "Test Data/The Best of 1980-1990.nfo", CancellationToken.None)); + } + + [Fact] + public void Fetch_NullResult_ThrowsArgumentException() + { + var result = new MetadataResult() + { + Item = new MusicAlbum() + }; + + Assert.Throws(() => _parser.Fetch(result, string.Empty, CancellationToken.None)); + } + } +} diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo new file mode 100644 index 0000000000..4ab8400d31 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/The Best of 1980-1990.nfo @@ -0,0 +1,29 @@ + + + The Best of 1980-1990 + 59b5a40b-e2fd-3f18-a218-e8c9aae12ab5 + 6c301dbd-6ccb-3403-a6c4-6a22240a0297 + false + U2 + Pop + + Political + false + The Best of 1980-1990 is the first greatest hits compilation by Irish rock band U2, released in November 1998. It mostly contains the group's hit singles from the eighties but also mixes in some live staples as well as one new recording, Sweetest Thing. In April 1999, a companion video (featuring music videos and live footage) was released. The album was followed by another compilation, The Best of 1990-2000, in 2002. A limited edition version containing a special B-sides disc was released on the same date as the single-disc version. At the time of release, the official word was that the 2-disc album would be available the first week the album went on sale, then pulled from the stores. While this threat never materialized, it did result in the 2-disc version being in very high demand. Both versions charted in the Billboard 200. The boy on the cover is Peter Rowan, brother of Bono's friend Guggi (real name Derek Rowan) of the Virgin Prunes. He also appears on the covers of the early EP Three, two of the band's first three albums (Boy and War), and Early Demos. + album / compilation + + + https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-4e43a22cab023.jpg + https://assets.fanart.tv/fanart/music/a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432/albumcover/the-best-of-1980-1990-5bc4301068645.jpg + https://www.theaudiodb.com/images/media/album/thumb/the-best-of-1980-1990-4e43a22cab023.jpg + C:\KODI\Test- Music\U2\Best Of 1980-1990, The\ + -1.000000 + -1 + -1 + 1989 + + U2 + a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432 + + album + From cf9a03790b4b5c77411b03a73df112f060c0ed02 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 20 Jan 2021 20:32:45 +0100 Subject: [PATCH 1001/1930] Check rating name for "audience" --- MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 2954868fcd..2e1fa43751 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -941,7 +941,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (float.TryParse(val, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue)) { // if ratingName contains tomato --> assume critic rating - if (ratingName != null && ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase)) + if (ratingName != null && + ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase) && + !ratingName.Contains("audience", StringComparison.OrdinalIgnoreCase)) { item.CriticRating = ratingValue; } From 215554bb4111cabae8ba1deacb534b947732b5e3 Mon Sep 17 00:00:00 2001 From: ImSoSx Date: Wed, 20 Jan 2021 21:36:05 +0000 Subject: [PATCH 1002/1930] Translated using Weblate (Spanish (Latin America)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es_419/ --- Emby.Server.Implementations/Localization/Core/es_419.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es_419.json b/Emby.Server.Implementations/Localization/Core/es_419.json index 03c6d5f5d3..6d2a5c7ac0 100644 --- a/Emby.Server.Implementations/Localization/Core/es_419.json +++ b/Emby.Server.Implementations/Localization/Core/es_419.json @@ -116,5 +116,6 @@ "TaskCleanActivityLogDescription": "Elimina las entradas del registro de actividad anteriores al periodo configurado.", "TaskCleanActivityLog": "Limpiar Registro de Actividades", "Undefined": "Sin definir", - "Forced": "Forzado" + "Forced": "Forzado", + "Default": "Por Defecto" } From 59ff2c5b4b26a435751f1bbdecd8dc309f14e7da Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 20 Jan 2021 16:24:15 -0700 Subject: [PATCH 1003/1930] Add ability to mark query parameter as obsolete. --- .../Attributes/ParameterObsoleteAttribute.cs | 12 ++++++ .../Controllers/MediaInfoController.cs | 29 ++++++++------- .../Controllers/PlaylistsController.cs | 10 +++-- .../ApiServiceCollectionExtensions.cs | 5 +-- .../Filters/ParameterObsoleteFilter.cs | 37 +++++++++++++++++++ 5 files changed, 71 insertions(+), 22 deletions(-) create mode 100644 Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs create mode 100644 Jellyfin.Server/Filters/ParameterObsoleteFilter.cs diff --git a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs new file mode 100644 index 0000000000..260e29d60f --- /dev/null +++ b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace Jellyfin.Api.Attributes +{ + /// + /// Attribute to mark a parameter as obsolete. + /// + [AttributeUsage(AttributeTargets.Parameter)] + public class ParameterObsoleteAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index baa2e06361..e330f02b61 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -83,6 +83,7 @@ namespace Jellyfin.Api.Controllers /// /// /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence. + /// Query parameters are obsolete. /// /// The item id. /// The user id. @@ -106,20 +107,20 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public async Task> GetPostedPlaybackInfo( [FromRoute, Required] Guid itemId, - [FromQuery] Guid? userId, - [FromQuery] int? maxStreamingBitrate, - [FromQuery] long? startTimeTicks, - [FromQuery] int? audioStreamIndex, - [FromQuery] int? subtitleStreamIndex, - [FromQuery] int? maxAudioChannels, - [FromQuery] string? mediaSourceId, - [FromQuery] string? liveStreamId, - [FromQuery] bool? autoOpenLiveStream, - [FromQuery] bool? enableDirectPlay, - [FromQuery] bool? enableDirectStream, - [FromQuery] bool? enableTranscoding, - [FromQuery] bool? allowVideoStreamCopy, - [FromQuery] bool? allowAudioStreamCopy, + [FromQuery, ParameterObsolete] Guid? userId, + [FromQuery, ParameterObsolete] int? maxStreamingBitrate, + [FromQuery, ParameterObsolete] long? startTimeTicks, + [FromQuery, ParameterObsolete] int? audioStreamIndex, + [FromQuery, ParameterObsolete] int? subtitleStreamIndex, + [FromQuery, ParameterObsolete] int? maxAudioChannels, + [FromQuery, ParameterObsolete] string? mediaSourceId, + [FromQuery, ParameterObsolete] string? liveStreamId, + [FromQuery, ParameterObsolete] bool? autoOpenLiveStream, + [FromQuery, ParameterObsolete] bool? enableDirectPlay, + [FromQuery, ParameterObsolete] bool? enableDirectStream, + [FromQuery, ParameterObsolete] bool? enableTranscoding, + [FromQuery, ParameterObsolete] bool? allowVideoStreamCopy, + [FromQuery, ParameterObsolete] bool? allowAudioStreamCopy, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] PlaybackInfoDto? playbackInfoDto) { var authInfo = _authContext.GetAuthorizationInfo(Request); diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index fcdad4bc72..a55e4ad2ff 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; +using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; @@ -57,6 +58,7 @@ namespace Jellyfin.Api.Controllers /// /// /// For backwards compatibility parameters can be sent via Query or Body, with Query having higher precedence. + /// Query parameters are obsolete. /// /// The playlist name. /// The item ids. @@ -70,10 +72,10 @@ namespace Jellyfin.Api.Controllers [HttpPost] [ProducesResponseType(StatusCodes.Status200OK)] public async Task> CreatePlaylist( - [FromQuery] string? name, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] IReadOnlyList ids, - [FromQuery] Guid? userId, - [FromQuery] string? mediaType, + [FromQuery, ParameterObsolete] string? name, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder)), ParameterObsolete] IReadOnlyList ids, + [FromQuery, ParameterObsolete] Guid? userId, + [FromQuery, ParameterObsolete] string? mediaType, [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] CreatePlaylistDto? createPlaylistRequest) { if (ids.Count == 0) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 4f65a31e07..77fb64674d 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; using Emby.Server.Implementations; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.DefaultAuthorizationPolicy; @@ -25,7 +22,6 @@ using Jellyfin.Api.Controllers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using Jellyfin.Networking.Configuration; -using Jellyfin.Networking.Manager; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using Jellyfin.Server.Formatters; @@ -317,6 +313,7 @@ namespace Jellyfin.Server.Extensions c.OperationFilter(); c.OperationFilter(); + c.OperationFilter(); c.DocumentFilter(); }); } diff --git a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs new file mode 100644 index 0000000000..7e81070c50 --- /dev/null +++ b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs @@ -0,0 +1,37 @@ +using System; +using System.Linq; +using Jellyfin.Api.Attributes; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Jellyfin.Server.Filters +{ + /// + /// Mark parameter as deprecated if it has the . + /// + public class ParameterObsoleteFilter : IOperationFilter + { + /// + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + foreach (var parameterDescription in context.ApiDescription.ParameterDescriptions) + { + if (parameterDescription + .CustomAttributes() + .OfType() + .Any()) + { + foreach (var parameter in operation.Parameters) + { + if (parameter.Name.Equals(parameterDescription.Name, StringComparison.Ordinal)) + { + parameter.Deprecated = true; + break; + } + } + } + } + } + } +} \ No newline at end of file From df402df908e3c0aae6ac276dbcef6438a00d148c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 21 Jan 2021 12:43:54 +0000 Subject: [PATCH 1004/1930] fix return --- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index fbd08a97c7..92483ae9a5 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -209,6 +209,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _ffmpegPath = path; EncoderLocation = location; + return true; } else { From 91a9af95c2c5b7edb897494379a55c4621e8e6f5 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Thu, 21 Jan 2021 07:01:51 -0700 Subject: [PATCH 1005/1930] Apply suggestions from code review Co-authored-by: dkanada --- Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs | 2 +- Jellyfin.Server/Filters/ParameterObsoleteFilter.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs index 260e29d60f..56c9772b6d 100644 --- a/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs +++ b/Jellyfin.Api/Attributes/ParameterObsoleteAttribute.cs @@ -9,4 +9,4 @@ namespace Jellyfin.Api.Attributes public class ParameterObsoleteAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs index 7e81070c50..e54044d0e9 100644 --- a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs +++ b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs @@ -34,4 +34,4 @@ namespace Jellyfin.Server.Filters } } } -} \ No newline at end of file +} From 956ca0e5aa74fc78aa630e73a764861121ef920a Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 21 Jan 2021 15:45:54 +0100 Subject: [PATCH 1006/1930] 100% branch coverage for Jellyfin.Naming --- Emby.Naming/AudioBook/AudioBookInfo.cs | 8 +- Emby.Naming/Video/VideoListResolver.cs | 13 ++- Emby.Naming/Video/VideoResolver.cs | 4 +- .../Video/MultiVersionTests.cs | 79 ++++--------------- .../Video/VideoResolverTests.cs | 9 +-- 5 files changed, 33 insertions(+), 80 deletions(-) diff --git a/Emby.Naming/AudioBook/AudioBookInfo.cs b/Emby.Naming/AudioBook/AudioBookInfo.cs index adf403ab6d..15702ff2ca 100644 --- a/Emby.Naming/AudioBook/AudioBookInfo.cs +++ b/Emby.Naming/AudioBook/AudioBookInfo.cs @@ -15,13 +15,13 @@ namespace Emby.Naming.AudioBook /// List of files composing the actual audiobook. /// List of extra files. /// Alternative version of files. - public AudioBookInfo(string name, int? year, List? files, List? extras, List? alternateVersions) + public AudioBookInfo(string name, int? year, List files, List extras, List alternateVersions) { Name = name; Year = year; - Files = files ?? new List(); - Extras = extras ?? new List(); - AlternateVersions = alternateVersions ?? new List(); + Files = files; + Extras = extras; + AlternateVersions = alternateVersions; } /// diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index fd16774739..09a030d2de 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -185,8 +185,8 @@ namespace Emby.Naming.Video if (!string.IsNullOrEmpty(folderName) && folderName.Length > 1 && videos.All(i => i.Files.Count == 1 - && IsEligibleForMultiVersion(folderName, i.Files[0].Path)) - && HaveSameYear(videos)) + && IsEligibleForMultiVersion(folderName, i.Files[0].Path)) + && HaveSameYear(videos)) { var ordered = videos.OrderBy(i => i.Name).ToList(); @@ -216,10 +216,9 @@ namespace Emby.Naming.Video return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2; } - private bool IsEligibleForMultiVersion(string folderName, string? testFilename) + private bool IsEligibleForMultiVersion(string folderName, string testFilePath) { - testFilename = Path.GetFileNameWithoutExtension(testFilename) ?? string.Empty; - + string testFilename = Path.GetFileNameWithoutExtension(testFilePath); if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) { if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName)) @@ -233,8 +232,8 @@ namespace Emby.Naming.Video } return string.IsNullOrEmpty(testFilename) - || testFilename[0].Equals('-') - || testFilename[0].Equals('_') + || testFilename[0] == '-' + || testFilename[0] == '_' || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index d7165d8d7f..619d1520e4 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -125,7 +125,7 @@ namespace Emby.Naming.Video /// True if is video file. public bool IsVideoFile(string path) { - var extension = Path.GetExtension(path) ?? string.Empty; + var extension = Path.GetExtension(path); return _options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } @@ -136,7 +136,7 @@ namespace Emby.Naming.Video /// True if is video file stub. public bool IsStubFile(string path) { - var extension = Path.GetExtension(path) ?? string.Empty; + var extension = Path.GetExtension(path); return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); } diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index 9df6904ef6..bc5e6fa631 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -9,9 +9,8 @@ namespace Jellyfin.Naming.Tests.Video { public class MultiVersionTests { - private readonly NamingOptions _namingOptions = new NamingOptions(); + private readonly VideoListResolver _videoListResolver = new VideoListResolver(new NamingOptions()); - // FIXME [Fact] public void TestMultiEdition1() { @@ -23,9 +22,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [hsbs].mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -35,7 +32,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result[0].Extras); } - // FIXME [Fact] public void TestMultiEdition2() { @@ -47,9 +43,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/X-Men Days of Future Past/X-Men Days of Future Past [banana].mp4" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -69,9 +63,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/The Phantom of the Opera (1925)/The Phantom of the Opera (1925) - 1929 version.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -81,7 +73,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result[0].AlternateVersions); } - // FIXME [Fact] public void TestLetterFolders() { @@ -96,9 +87,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/M/Movie 7.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -109,7 +98,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Empty(result[0].AlternateVersions); } - // FIXME [Fact] public void TestMultiVersionLimit() { @@ -125,9 +113,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Movie/Movie-8.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -138,7 +124,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Equal(7, result[0].AlternateVersions.Count); } - // FIXME [Fact] public void TestMultiVersionLimit2() { @@ -155,9 +140,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Mo/Movie 9.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -168,7 +151,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Empty(result[0].AlternateVersions); } - // FIXME [Fact] public void TestMultiVersion3() { @@ -181,9 +163,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Movie/Movie 5.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -194,7 +174,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.Empty(result[0].AlternateVersions); } - // FIXME [Fact] public void TestMultiVersion4() { @@ -209,9 +188,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man (2011).mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -237,9 +214,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man[test].mkv", }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -253,7 +228,6 @@ namespace Jellyfin.Naming.Tests.Video Assert.True(result[0].AlternateVersions[4].Is3D); } - // FIXME [Fact] public void TestMultiVersion6() { @@ -269,9 +243,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man [test].mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -294,9 +266,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man - C (2007).mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -319,9 +289,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man_3d.hsbs.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -349,9 +317,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Iron Man/Iron Man (2011).mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -371,9 +337,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/Blade Runner (1982)/Blade Runner (1982) [EE by ADM] [480p HEVC AAC,AAC,AAC].mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -393,9 +357,7 @@ namespace Jellyfin.Naming.Tests.Video @"/movies/X-Men Apocalypse (2016)/X-Men Apocalypse (2016) [2160p] Blu-ray.x265.AAC.mkv" }; - var resolver = GetResolver(); - - var result = resolver.Resolve(files.Select(i => new FileSystemMetadata + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata { IsDirectory = false, FullName = i @@ -409,16 +371,9 @@ namespace Jellyfin.Naming.Tests.Video [Fact] public void TestEmptyList() { - var resolver = GetResolver(); - - var result = resolver.Resolve(new List()).ToList(); + var result = _videoListResolver.Resolve(new List()).ToList(); Assert.Empty(result); } - - private VideoListResolver GetResolver() - { - return new VideoListResolver(_namingOptions); - } } } diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index b6447a7a64..ba5eaf1aff 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -9,7 +9,7 @@ namespace Jellyfin.Naming.Tests.Video { public class VideoResolverTests { - private readonly NamingOptions _namingOptions = new NamingOptions(); + private readonly VideoResolver _videoResolver = new VideoResolver(new NamingOptions()); public static IEnumerable GetResolveFileTestData() { @@ -159,7 +159,7 @@ namespace Jellyfin.Naming.Tests.Video [MemberData(nameof(GetResolveFileTestData))] public void ResolveFile_ValidFileName_Success(VideoFileInfo expectedResult) { - var result = new VideoResolver(_namingOptions).ResolveFile(expectedResult.Path); + var result = _videoResolver.ResolveFile(expectedResult.Path); Assert.NotNull(result); Assert.Equal(result?.Path, expectedResult.Path); @@ -179,7 +179,7 @@ namespace Jellyfin.Naming.Tests.Video [Fact] public void ResolveFile_EmptyPath() { - var result = new VideoResolver(_namingOptions).ResolveFile(string.Empty); + var result = _videoResolver.ResolveFile(string.Empty); Assert.Null(result); } @@ -194,8 +194,7 @@ namespace Jellyfin.Naming.Tests.Video string.Empty }; - var resolver = new VideoResolver(_namingOptions); - var results = paths.Select(path => resolver.ResolveDirectory(path)).ToList(); + var results = paths.Select(path => _videoResolver.ResolveDirectory(path)).ToList(); Assert.Equal(3, results.Count); Assert.NotNull(results[0]); From 17cff101ceb2ddc7232bbbdc9a3da75dab5a1690 Mon Sep 17 00:00:00 2001 From: Rodlan Bernabe Date: Thu, 21 Jan 2021 03:25:00 +0000 Subject: [PATCH 1007/1930] Translated using Weblate (Filipino) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fil/ --- .../Localization/Core/fil.json | 103 +++++++++--------- 1 file changed, 53 insertions(+), 50 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fil.json b/Emby.Server.Implementations/Localization/Core/fil.json index e5ca676a48..f18a1c0303 100644 --- a/Emby.Server.Implementations/Localization/Core/fil.json +++ b/Emby.Server.Implementations/Localization/Core/fil.json @@ -3,101 +3,101 @@ "ValueSpecialEpisodeName": "Espesyal - {0}", "ValueHasBeenAddedToLibrary": "Naidagdag na ang {0} sa iyong librerya ng medya", "UserStoppedPlayingItemWithValues": "Natapos ni {0} ang {1} sa {2}", - "UserStartedPlayingItemWithValues": "Si {0} ay nagplaplay ng {1} sa {2}", - "UserPolicyUpdatedWithName": "Ang user policy ay naiupdate para kay {0}", + "UserStartedPlayingItemWithValues": "Si {0} ay nagpla-play ng {1} sa {2}", + "UserPolicyUpdatedWithName": "Ang user policy ay nai-update para kay {0}", "UserPasswordChangedWithName": "Napalitan na ang password ni {0}", - "UserOnlineFromDevice": "Si {0} ay nakakonekta galing sa {1}", - "UserOfflineFromDevice": "Si {0} ay nadiskonekta galing sa {1}", + "UserOnlineFromDevice": "Si {0} ay naka-konekta galing sa {1}", + "UserOfflineFromDevice": "Si {0} ay na-diskonekta galing sa {1}", "UserLockedOutWithName": "Si {0} ay nalock out", "UserDownloadingItemWithValues": "Nagdadownload si {0} ng {1}", "UserDeletedWithName": "Natanggal na is user {0}", "UserCreatedWithName": "Nagawa na si user {0}", "User": "User", - "TvShows": "Pelikula", + "TvShows": "Mga Palabas sa Telebisyon", "System": "Sistema", "Sync": "Pag-sync", - "SubtitleDownloadFailureFromForItem": "Hindi naidownload ang subtitles {0} para sa {1}", - "StartupEmbyServerIsLoading": "Nagloload ang Jellyfin Server. Sandaling maghintay.", - "Songs": "Kanta", - "Shows": "Pelikula", + "SubtitleDownloadFailureFromForItem": "Hindi nai-download ang subtitles {0} para sa {1}", + "StartupEmbyServerIsLoading": "Naglo-load ang Jellyfin Server. Mangyaring subukan ulit sandali.", + "Songs": "Mga Kanta", + "Shows": "Mga Pelikula", "ServerNameNeedsToBeRestarted": "Kailangan irestart ang {0}", "ScheduledTaskStartedWithName": "Nagsimula na ang {0}", - "ScheduledTaskFailedWithName": "Hindi gumana and {0}", - "ProviderValue": "Ang provider ay {0}", + "ScheduledTaskFailedWithName": "Hindi gumana ang {0}", + "ProviderValue": "Tagapagtustos: {0}", "PluginUpdatedWithName": "Naiupdate na ang {0}", "PluginUninstalledWithName": "Naiuninstall na ang {0}", "PluginInstalledWithName": "Nainstall na ang {0}", "Plugin": "Plugin", - "Playlists": "Playlists", - "Photos": "Larawan", + "Playlists": "Mga Playlist", + "Photos": "Mga Larawan", "NotificationOptionVideoPlaybackStopped": "Huminto na ang pelikula", "NotificationOptionVideoPlayback": "Nagsimula na ang pelikula", - "NotificationOptionUserLockedOut": "Nakalock out ang user", + "NotificationOptionUserLockedOut": "Naka-lock out ang user", "NotificationOptionTaskFailed": "Hindi gumana ang scheduled task", - "NotificationOptionServerRestartRequired": "Kailangan irestart ang server", - "NotificationOptionPluginUpdateInstalled": "Naiupdate na ang plugin", - "NotificationOptionPluginUninstalled": "Naiuninstall na ang plugin", + "NotificationOptionServerRestartRequired": "Kailangan i-restart ang server", + "NotificationOptionPluginUpdateInstalled": "Nai-update na ang plugin", + "NotificationOptionPluginUninstalled": "Nai-uninstall na ang plugin", "NotificationOptionPluginInstalled": "Nainstall na ang plugin", "NotificationOptionPluginError": "Hindi gumagana ang plugin", "NotificationOptionNewLibraryContent": "May bagong content na naidagdag", "NotificationOptionInstallationFailed": "Hindi nainstall ng mabuti", - "NotificationOptionCameraImageUploaded": "Naiupload na ang picture", + "NotificationOptionCameraImageUploaded": "Naiupload na ang litrato", "NotificationOptionAudioPlaybackStopped": "Huminto na ang patugtog", "NotificationOptionAudioPlayback": "Nagsimula na ang patugtog", "NotificationOptionApplicationUpdateInstalled": "Naiupdate na ang aplikasyon", "NotificationOptionApplicationUpdateAvailable": "May bagong update ang aplikasyon", - "NewVersionIsAvailable": "May bagong version ng Jellyfin Server na pwede idownload.", - "NameSeasonUnknown": "Hindi alam ang season", + "NewVersionIsAvailable": "May bagong version ng Jellyfin Server na pwede i-download.", + "NameSeasonUnknown": "Hindi matukoy ang season", "NameSeasonNumber": "Season {0}", "NameInstallFailed": "Hindi nainstall ang {0}", - "MusicVideos": "Music video", - "Music": "Kanta", - "Movies": "Pelikula", + "MusicVideos": "Mga Music video", + "Music": "Mga Kanta", + "Movies": "Mga Pelikula", "MixedContent": "Halo-halong content", "MessageServerConfigurationUpdated": "Naiupdate na ang server configuration", "MessageNamedServerConfigurationUpdatedWithValue": "Naiupdate na ang server configuration section {0}", - "MessageApplicationUpdatedTo": "Ang Jellyfin Server ay naiupdate to {0}", + "MessageApplicationUpdatedTo": "Ang bersyon ng Jellyfin Server ay naiupdate sa {0}", "MessageApplicationUpdated": "Naiupdate na ang Jellyfin Server", "Latest": "Pinakabago", "LabelRunningTimeValue": "Oras: {0}", - "LabelIpAddressValue": "Ang IP Address ay {0}", + "LabelIpAddressValue": "IP address: {0}", "ItemRemovedWithName": "Naitanggal ang {0} sa librerya", "ItemAddedWithName": "Naidagdag ang {0} sa librerya", "Inherit": "Manahin", "HeaderRecordingGroups": "Pagtatalang Grupo", "HeaderNextUp": "Susunod", "HeaderLiveTV": "Live TV", - "HeaderFavoriteSongs": "Paboritong Kanta", - "HeaderFavoriteShows": "Paboritong Pelikula", - "HeaderFavoriteEpisodes": "Paboritong Episodes", - "HeaderFavoriteArtists": "Paboritong Artista", - "HeaderFavoriteAlbums": "Paboritong Albums", - "HeaderContinueWatching": "Ituloy Manood", - "HeaderAlbumArtists": "Artista ng Album", - "Genres": "Kategorya", - "Folders": "Folders", - "Favorites": "Paborito", - "FailedLoginAttemptWithUserName": "maling login galing {0}", - "DeviceOnlineWithName": "nakakonekta si {0}", - "DeviceOfflineWithName": "nadiskonekta si {0}", - "Collections": "Koleksyon", + "HeaderFavoriteSongs": "Mga Paboritong Kanta", + "HeaderFavoriteShows": "Mga Paboritong Pelikula", + "HeaderFavoriteEpisodes": "Mga Paboritong Episode", + "HeaderFavoriteArtists": "Mga Paboritong Artista", + "HeaderFavoriteAlbums": "Mga Paboritong Album", + "HeaderContinueWatching": "Magpatuloy sa Panonood", + "HeaderAlbumArtists": "Mga Artista ng Album", + "Genres": "Mga Kategorya", + "Folders": "Mga Folder", + "Favorites": "Mga Paborito", + "FailedLoginAttemptWithUserName": "Maling login galing kay/sa {0}", + "DeviceOnlineWithName": "Nakakonekta si/ang {0}", + "DeviceOfflineWithName": "Nadiskonekta si/ang {0}", + "Collections": "Mga Koleksyon", "ChapterNameValue": "Kabanata {0}", - "Channels": "Channel", - "CameraImageUploadedFrom": "May bagong larawan na naupload galing {0}", - "Books": "Libro", - "AuthenticationSucceededWithUserName": "{0} na patunayan", - "Artists": "Artista", + "Channels": "Mga Channel", + "CameraImageUploadedFrom": "May bagong larawan na naupload galing sa/kay {0}", + "Books": "Mga Libro", + "AuthenticationSucceededWithUserName": "Napatunayan si/ang {0}", + "Artists": "Mga Artista", "Application": "Aplikasyon", "AppDeviceValues": "Aplikasyon: {0}, Aparato: {1}", - "Albums": "Albums", + "Albums": "Mga Album", "TaskRefreshLibrary": "Suriin and Librerya ng Medya", "TaskRefreshChapterImagesDescription": "Gumawa ng larawan para sa mga pelikula na may kabanata.", "TaskRefreshChapterImages": "Kunin ang mga larawan ng kabanata", - "TaskCleanCacheDescription": "Tanggalin ang mga cache file na hindi na kailangan ng systema.", + "TaskCleanCacheDescription": "Tanggalin ang mga cache file na hindi na kailangan ng sistema.", "TasksChannelsCategory": "Palabas sa internet", "TasksLibraryCategory": "Librerya", "TasksMaintenanceCategory": "Pagpapanatili", - "HomeVideos": "Sariling pelikula", + "HomeVideos": "Sariling video/pelikula", "TaskRefreshPeopleDescription": "Ini-update ang metadata para sa mga aktor at direktor sa iyong librerya ng medya.", "TaskRefreshPeople": "I-refresh ang Tauhan", "TaskDownloadMissingSubtitlesDescription": "Hinahanap sa internet ang mga nawawalang subtiles base sa metadata configuration.", @@ -105,14 +105,17 @@ "TaskRefreshChannelsDescription": "Ni-rerefresh ang impormasyon sa internet channels.", "TaskRefreshChannels": "I-refresh ang Channels", "TaskCleanTranscodeDescription": "Binubura ang transcode files na mas matanda ng isang araw.", - "TaskUpdatePluginsDescription": "Nag download at install ng updates sa plugins na naka configure para sa automatikong pag update.", + "TaskUpdatePluginsDescription": "Nag download at install ng updates sa plugins na naka configure para sa awtomatikong pag-update.", "TaskUpdatePlugins": "I-update ang Plugins", "TaskCleanLogsDescription": "Binubura and files ng talaan na mas mantanda ng {0} araw.", "TaskCleanTranscode": "Linisin and Direktoryo ng Transcode", "TaskCleanLogs": "Linisin and Direktoryo ng Talaan", "TaskRefreshLibraryDescription": "Sinusuri ang iyong librerya ng medya para sa bagong files at irefresh ang metadata.", "TaskCleanCache": "Linisin and Direktoryo ng Cache", - "TasksApplicationCategory": "Application", + "TasksApplicationCategory": "Aplikasyon", "TaskCleanActivityLog": "Linisin ang Tala ng Aktibidad", - "TaskCleanActivityLogDescription": "Tanggalin ang mga tala ng aktibidad na mas matanda sa naka configure na edad." + "TaskCleanActivityLogDescription": "Tanggalin ang mga tala ng aktibidad na mas luma sa nakatakda na edad.", + "Default": "Default", + "Undefined": "Hindi tiyak", + "Forced": "Sapilitan" } From d80daa3bec9a0853d7692e3e7ac763f13f197c20 Mon Sep 17 00:00:00 2001 From: Arian Ar Date: Thu, 21 Jan 2021 21:02:38 +0000 Subject: [PATCH 1008/1930] Translated using Weblate (Persian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fa/ --- Emby.Server.Implementations/Localization/Core/fa.json | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fa.json b/Emby.Server.Implementations/Localization/Core/fa.json index 7eb8e36e7e..e9e4f61b8c 100644 --- a/Emby.Server.Implementations/Localization/Core/fa.json +++ b/Emby.Server.Implementations/Localization/Core/fa.json @@ -49,7 +49,7 @@ "NotificationOptionAudioPlayback": "پخش صدا آغاز شد", "NotificationOptionAudioPlaybackStopped": "پخش صدا متوقف شد", "NotificationOptionCameraImageUploaded": "تصاویر دوربین آپلود شد", - "NotificationOptionInstallationFailed": "نصب شکست خورد", + "NotificationOptionInstallationFailed": "نصب ناموفق", "NotificationOptionNewLibraryContent": "محتوای جدید افزوده شد", "NotificationOptionPluginError": "خرابی افزونه", "NotificationOptionPluginInstalled": "افزونه نصب شد", @@ -115,5 +115,8 @@ "TasksLibraryCategory": "کتابخانه", "TasksMaintenanceCategory": "تعمیر", "Forced": "اجباری", - "Default": "پیشفرض" + "Default": "پیشفرض", + "TaskCleanActivityLogDescription": "ورودی‌های قدیمی‌تر از سن تنظیم شده در سیاهه فعالیت را حذف می‌کند.", + "TaskCleanActivityLog": "پاکسازی سیاهه فعالیت", + "Undefined": "تعریف نشده" } From 84f6d683f2f11c55c321bdddf6c2562dbd4b18a5 Mon Sep 17 00:00:00 2001 From: "Wong To Han, Toby" Date: Fri, 22 Jan 2021 04:03:13 +0000 Subject: [PATCH 1009/1930] Translated using Weblate (Chinese (Hong Kong)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant_HK/ --- Emby.Server.Implementations/Localization/Core/zh-HK.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-HK.json b/Emby.Server.Implementations/Localization/Core/zh-HK.json index 435e294ef2..3dad21dcbc 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-HK.json +++ b/Emby.Server.Implementations/Localization/Core/zh-HK.json @@ -113,5 +113,9 @@ "TaskCleanCache": "清理緩存目錄", "TasksChannelsCategory": "互聯網頻道", "TasksLibraryCategory": "庫", - "TaskRefreshPeople": "刷新人物" + "TaskRefreshPeople": "刷新人物", + "TaskCleanActivityLog": "清理活動記錄", + "Undefined": "未定義", + "Forced": "強制", + "Default": "預設" } From 91abc09e7902e09d3086885c49f668dd30bfd04a Mon Sep 17 00:00:00 2001 From: WWWesten Date: Fri, 22 Jan 2021 18:01:02 +0000 Subject: [PATCH 1010/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- Emby.Server.Implementations/Localization/Core/kk.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index 7ce9822b6d..befe4e14f6 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -94,7 +94,7 @@ "VersionNumber": "Nusqasy {0}", "Default": "Ádepki", "TaskDownloadMissingSubtitles": "Joq sýbtıtrlerdi júktep alý", - "TaskRefreshChannels": "Arnalardy jańartý", + "TaskRefreshChannels": "Arnalardy jańǵyrtý", "TaskCleanTranscode": "Qaıta kodtaý katalogyn tazalaý", "TaskUpdatePlugins": "Plagınderdi jańartý", "TaskRefreshPeople": "Adamdardy jańartý", @@ -110,7 +110,7 @@ "Undefined": "Anyqtalmady", "Forced": "Májbúrli", "TaskDownloadMissingSubtitlesDescription": "Metaderekter teńshelimi negіzіnde joq sýbtıtrlerdі Internetten іzdeıdі.", - "TaskRefreshChannelsDescription": "Internet-arnalar málimetterin jańartady.", + "TaskRefreshChannelsDescription": "Internet-arnalar málimetterin jańǵyrtady.", "TaskCleanTranscodeDescription": "Bіr kúnnen asqan qaıta kodtaý faıldaryn joıady.", "TaskUpdatePluginsDescription": "Avtomatty túrde jańartýǵa teńshelgen plagınder úshin jańartýlardy júktep alady jáne ornatady.", "TaskRefreshPeopleDescription": "Tasyǵyshhanadaǵy aktórler men rejısórler metaderekterіn jańartady.", From 72974121956d50e2bd99edf2768bb2ce909b4b70 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 23 Jan 2021 12:02:22 +0100 Subject: [PATCH 1011/1930] Fix indentation --- .../Parsers/EpisodeNfoParser.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index dffea3fe67..81774b8735 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -210,14 +210,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers case "showtitle": { - var showtitle = reader.ReadElementContentAsString(); + var showtitle = reader.ReadElementContentAsString(); - if (!string.IsNullOrWhiteSpace(showtitle)) - { - item.SeriesName = showtitle; - } + if (!string.IsNullOrWhiteSpace(showtitle)) + { + item.SeriesName = showtitle; + } - break; + break; } default: From 1bc1d1c07b66433c3ae5e30398023adda817ebe9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 23 Jan 2021 13:43:41 +0000 Subject: [PATCH 1012/1930] Bump Moq from 4.15.2 to 4.16.0 Bumps [Moq](https://github.com/moq/moq4) from 4.15.2 to 4.16.0. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.15.2...v4.16.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 7241ad0ee6..c58813617d 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index ca65398580..bb2bae8e8f 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index b242e1dfd6..7f909847ec 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index 1fadd2126d..fe40122a35 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -15,7 +15,7 @@ - + From b2f2126eddacc03fc979f06374301f358ad5e967 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 23 Jan 2021 17:35:06 +0100 Subject: [PATCH 1013/1930] Don't write tagline in in nfo files --- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 1adc5029df..4e48e53be5 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -450,15 +450,7 @@ namespace MediaBrowser.XbmcMetadata.Savers writer.WriteElementString("plot", overview); } - if (item is Video) - { - var outline = (item.Tagline ?? string.Empty) - .StripHtml() - .Replace(""", "'", StringComparison.Ordinal); - - writer.WriteElementString("outline", outline); - } - else + if (!(item is Video)) { writer.WriteElementString("outline", overview); } From 454d82c52ca884649cf62e5a583a601225a844ec Mon Sep 17 00:00:00 2001 From: David Date: Sat, 23 Jan 2021 18:06:26 +0100 Subject: [PATCH 1014/1930] Process actor type in nfo files --- .../Parsers/BaseNfoParser.cs | 39 +++++++++++++++++++ .../Parsers/MovieNfoParserTests.cs | 6 ++- .../Test Data/Justice League.nfo | 5 +++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index f2d0bdc545..a230127167 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -1030,6 +1030,45 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "type": + { + var val = reader.ReadElementContentAsString(); + + if (!string.IsNullOrWhiteSpace(val)) + { + switch (val) + { + case PersonType.Composer: + type = PersonType.Composer; + break; + case PersonType.Conductor: + type = PersonType.Conductor; + break; + case PersonType.Director: + type = PersonType.Director; + break; + case PersonType.Lyricist: + type = PersonType.Lyricist; + break; + case PersonType.Producer: + type = PersonType.Producer; + break; + case PersonType.Writer: + type = PersonType.Writer; + break; + case PersonType.GuestStar: + type = PersonType.GuestStar; + break; + // unknown type --> actor + default: + type = PersonType.Actor; + break; + } + } + + break; + } + case "order": case "sortorder": { diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index e1f50876fb..765464eced 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -60,7 +60,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal(new TimeSpan(0, 0, 6268).Ticks, item.RunTimeTicks); Assert.True(item.HasSubtitles); - Assert.Equal(18, result.People.Count); + Assert.Equal(19, result.People.Count); var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray(); Assert.Equal(2, writers.Length); @@ -82,6 +82,10 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal(5, aquaman!.SortOrder); Assert.Equal("https://m.media-amazon.com/images/M/MV5BMTI5MTU5NjM1MV5BMl5BanBnXkFtZTcwODc4MDk0Mw@@._V1_SX1024_SY1024_.jpg", aquaman!.ImageUrl); + var lyricist = result.People.FirstOrDefault(x => x.Type == PersonType.Lyricist); + Assert.NotNull(lyricist); + Assert.Equal("Test Lyricist", lyricist!.Name); + Assert.Equal(new DateTime(2019, 8, 6, 9, 1, 18), item.DateCreated); } diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo index f838af8d04..6e6da25d30 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo @@ -221,6 +221,11 @@ 14 https://m.media-amazon.com/images/M/MV5BOTFjOTFhNTgtZjk3Ny00MTNjLWE3MWUtMWI3ZWM5NDljZjQwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_SX1024_SY1024_.jpg + + Test Lyricist + Lyricist + 15 + 0.000000 0.000000 From 18e33b6b2d58a2f822b10f126639610ed598f5a5 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 23 Jan 2021 19:05:55 +0100 Subject: [PATCH 1015/1930] Remove check for wrong metadata saving property --- MediaBrowser.XbmcMetadata/EntryPoint.cs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/EntryPoint.cs b/MediaBrowser.XbmcMetadata/EntryPoint.cs index 981b7b9d2f..d02aea5566 100644 --- a/MediaBrowser.XbmcMetadata/EntryPoint.cs +++ b/MediaBrowser.XbmcMetadata/EntryPoint.cs @@ -60,17 +60,7 @@ namespace MediaBrowser.XbmcMetadata private void SaveMetadataForItem(BaseItem item, ItemUpdateType updateReason) { - if (!item.IsFileProtocol) - { - return; - } - - if (!item.SupportsLocalMetadata) - { - return; - } - - if (!item.IsSaveLocalMetadataEnabled()) + if (!item.IsFileProtocol || !item.SupportsLocalMetadata) { return; } From 3838e8ac158f334795c6c8c633936e8bf20a723e Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Sat, 23 Jan 2021 23:36:51 +0100 Subject: [PATCH 1016/1930] Update MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs Co-authored-by: Bond-009 --- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 4e48e53be5..e1be79a060 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -450,7 +450,7 @@ namespace MediaBrowser.XbmcMetadata.Savers writer.WriteElementString("plot", overview); } - if (!(item is Video)) + if (item is not Video) { writer.WriteElementString("outline", overview); } From 4aaf71b87383805df740703f4cf3714adf1f6dfd Mon Sep 17 00:00:00 2001 From: Karandeep Singh Grewal Date: Sat, 23 Jan 2021 18:11:08 +0000 Subject: [PATCH 1017/1930] Translated using Weblate (Hindi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hi/ --- .../Localization/Core/hi.json | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index 4cc2b378b5..b9e5f301d9 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -26,5 +26,30 @@ "AuthenticationSucceededWithUserName": "सफलता से प्रमाणीकृत", "Artists": "कलाकारों", "Application": "एप्लिकेशन", - "AppDeviceValues": "एप: {0}, मशीन: {1}" + "AppDeviceValues": "एप: {0}, मशीन: {1}", + "NotificationOptionPluginUninstalled": "प्लगइन अनइंस्टाल हो गया", + "NotificationOptionPluginInstalled": "प्लगइन इनस्टॉल हो गया", + "NotificationOptionPluginError": "प्लगइन फ़ैल हो गया", + "NotificationOptionInstallationFailed": "इंस्टालेशन फ़ैल हो गया", + "NotificationOptionAudioPlaybackStopped": "संगीत बंद कर दिया गया", + "NotificationOptionAudioPlayback": "संगीत शुरू कर दिया गया", + "NotificationOptionCameraImageUploaded": "कैमरा फोटो अपलोड किया गया", + "NotificationOptionApplicationUpdateInstalled": "एप्लीकेशन अपडेट इनस्टॉल कर दिया है", + "NotificationOptionApplicationUpdateAvailable": "एप्लीकेशन अपडेट उपलभ्द है", + "NewVersionIsAvailable": "जेलीफिन सर्वर का एक नया वर्जन डाउनलोड के लिए उपलब्ध है।", + "NameSeasonUnknown": "अनजान भाग", + "NameSeasonNumber": "भाग {0}", + "NameInstallFailed": "{0} इनस्टॉल करते समय फेल हो गया है", + "MusicVideos": "संगीत वीडियो", + "Music": "संगीत", + "Movies": "फ़िल्म", + "MixedContent": "मिला-जुला कंटेंट", + "MessageServerConfigurationUpdated": "सर्वर कॉन्फ़िगरेशन अपडेट हो गया है", + "MessageNamedServerConfigurationUpdatedWithValue": "सर्वर कॉन्फ़िगरेशन भाग {0} अपडेट हो गया है", + "MessageApplicationUpdatedTo": "जैलीफिन सर्वर {0} में अपडेट हो गया है", + "MessageApplicationUpdated": "जैलीफिन सर्वर अपडेट हो गया है", + "Latest": "सबसे नया", + "LabelIpAddressValue": "आई पी एड्रेस: {0}", + "ItemRemovedWithName": "{0} लाइब्रेरी में से निकाल दिया है", + "HomeVideos": "होम वीडियोस" } From 4adbbb9f5111d2386f1f0a9c5aaa173d041e9c90 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Sun, 24 Jan 2021 00:57:37 +0100 Subject: [PATCH 1018/1930] Catch TypeLoadException during plugin loading --- Emby.Server.Implementations/Plugins/PluginManager.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 9f597f3ef3..42c76bd66a 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -122,6 +122,12 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.Malfunctioned); continue; } + catch (TypeLoadException ex) + { + _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin. This is probably caused by an incompatible plugin version.", file); + ChangePluginState(plugin, PluginStatus.Malfunctioned); + continue; + } _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file); yield return assembly; From 55670b91b26610655cd4c0528e3dd938b852b4fc Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 23 Jan 2021 17:32:13 -0700 Subject: [PATCH 1019/1930] Use ArrayModelBinder for sortBy and sortOrder --- .../Controllers/ChannelsController.cs | 7 ++--- Jellyfin.Api/Controllers/ItemsController.cs | 8 ++--- Jellyfin.Api/Controllers/LiveTvController.cs | 4 +-- .../Controllers/TrailersController.cs | 5 +-- Jellyfin.Api/Controllers/YearsController.cs | 5 +-- Jellyfin.Api/Helpers/RequestHelpers.cs | 31 ++++++------------- .../Models/LiveTvDtos/GetProgramsDto.cs | 7 +++-- 7 files changed, 29 insertions(+), 38 deletions(-) diff --git a/Jellyfin.Api/Controllers/ChannelsController.cs b/Jellyfin.Api/Controllers/ChannelsController.cs index b70c76e807..54bd800951 100644 --- a/Jellyfin.Api/Controllers/ChannelsController.cs +++ b/Jellyfin.Api/Controllers/ChannelsController.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Constants; -using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -121,9 +120,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] Guid? userId, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields) { var user = userId.HasValue && !userId.Equals(Guid.Empty) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index b84136ac6f..7d77474958 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -175,7 +175,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] bool? recursive, [FromQuery] string? searchTerm, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, @@ -184,7 +184,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] bool? isPlayed, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, @@ -608,7 +608,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] bool? recursive, [FromQuery] string? searchTerm, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, @@ -617,7 +617,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] bool? isPlayed, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, diff --git a/Jellyfin.Api/Controllers/LiveTvController.cs b/Jellyfin.Api/Controllers/LiveTvController.cs index 6f2d432277..24ee833ef7 100644 --- a/Jellyfin.Api/Controllers/LiveTvController.cs +++ b/Jellyfin.Api/Controllers/LiveTvController.cs @@ -553,8 +553,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isSports, [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? sortBy, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds, [FromQuery] bool? enableImages, diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 8e9ece14f8..242b8f068e 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -1,6 +1,7 @@ using System; using Jellyfin.Api.Constants; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -144,7 +145,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] bool? recursive, [FromQuery] string? searchTerm, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, @@ -152,7 +153,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] bool? isPlayed, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres, [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings, diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 48c639b08d..7c27752f7f 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -7,6 +7,7 @@ using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -70,13 +71,13 @@ namespace Jellyfin.Api.Controllers public ActionResult> GetYears( [FromQuery] int? startIndex, [FromQuery] int? limit, - [FromQuery] string? sortOrder, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, - [FromQuery] string? sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index efce11f8a7..056ad83daf 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; @@ -8,7 +9,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Dto; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Http; @@ -25,35 +25,22 @@ namespace Jellyfin.Api.Helpers /// Sort By. Comma delimited string. /// Sort Order. Comma delimited string. /// Order By. - public static ValueTuple[] GetOrderBy(string? sortBy, string? requestedSortOrder) + public static ValueTuple[] GetOrderBy(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder) { - var val = sortBy; - - if (string.IsNullOrEmpty(val)) + if (sortBy.Count == 0) { return Array.Empty>(); } - var vals = val.Split(','); - if (string.IsNullOrWhiteSpace(requestedSortOrder)) + var result = new ValueTuple[sortBy.Count]; + for (var i = 0; i < sortBy.Count; i++) { - requestedSortOrder = "Ascending"; - } + var sortOrderIndex = requestedSortOrder.Count > i ? i : 0; - var sortOrders = requestedSortOrder.Split(','); - - var result = new ValueTuple[vals.Length]; - - for (var i = 0; i < vals.Length; i++) - { - var sortOrderIndex = sortOrders.Length > i ? i : 0; - - var sortOrderValue = sortOrders.Length > sortOrderIndex ? sortOrders[sortOrderIndex] : null; - var sortOrder = string.Equals(sortOrderValue, "Descending", StringComparison.OrdinalIgnoreCase) - ? SortOrder.Descending + var sortOrder = requestedSortOrder.Count > sortOrderIndex + ? requestedSortOrder[sortOrderIndex] : SortOrder.Ascending; - - result[i] = new ValueTuple(vals[i], sortOrder); + result[i] = new ValueTuple(sortBy[i], sortOrder); } return result; diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index a47ae926c1..588ce717c8 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; +using Jellyfin.Data.Enums; using MediaBrowser.Common.Json.Converters; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; @@ -106,12 +107,14 @@ namespace Jellyfin.Api.Models.LiveTvDtos /// Gets or sets specify one or more sort orders, comma delimited. Options: Name, StartDate. /// Optional. /// - public string? SortBy { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList SortBy { get; set; } = Array.Empty(); /// /// Gets or sets sort Order - Ascending,Descending. /// - public string? SortOrder { get; set; } + [JsonConverter(typeof(JsonCommaDelimitedArrayConverterFactory))] + public IReadOnlyList SortOrder { get; set; } = Array.Empty(); /// /// Gets or sets the genres to return guide information for. From d24e7f60c754620f88faa294af5bf0309b59c785 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 24 Jan 2021 11:43:05 +0100 Subject: [PATCH 1020/1930] Fix GetOrderBy and add tests --- Jellyfin.Api/Helpers/RequestHelpers.cs | 19 +++--- .../Helpers/RequestHelpersTests.cs | 59 +++++++++++++++++++ 2 files changed, 70 insertions(+), 8 deletions(-) create mode 100644 tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 056ad83daf..59cb8ea2c1 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -25,22 +25,25 @@ namespace Jellyfin.Api.Helpers /// Sort By. Comma delimited string. /// Sort Order. Comma delimited string. /// Order By. - public static ValueTuple[] GetOrderBy(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder) + public static (string, SortOrder)[] GetOrderBy(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder) { if (sortBy.Count == 0) { return Array.Empty>(); } - var result = new ValueTuple[sortBy.Count]; - for (var i = 0; i < sortBy.Count; i++) + var result = new (string, SortOrder)[sortBy.Count]; + var i = 0; + // Add elements which have a SortOrder specified + for (; i < requestedSortOrder.Count; i++) { - var sortOrderIndex = requestedSortOrder.Count > i ? i : 0; + result[i] = (sortBy[i], requestedSortOrder[i]); + } - var sortOrder = requestedSortOrder.Count > sortOrderIndex - ? requestedSortOrder[sortOrderIndex] - : SortOrder.Ascending; - result[i] = new ValueTuple(sortBy[i], sortOrder); + // Add remaining elements with the default SortOrder + for (; i < sortBy.Count; i++) + { + result[i] = (sortBy[i], SortOrder.Ascending); } return result; diff --git a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs new file mode 100644 index 0000000000..944472c689 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using Jellyfin.Api.Helpers; +using Jellyfin.Data.Enums; +using Xunit; + +namespace Jellyfin.Api.Tests.Helpers +{ + public class RequestHelpersTests + { + [Theory] + [MemberData(nameof(GetOrderBy_Success_TestData))] + public void GetOrderBy_Success(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder, (string, SortOrder)[] expected) + { + Assert.Equal(expected, RequestHelpers.GetOrderBy(sortBy, requestedSortOrder)); + } + + public static IEnumerable GetOrderBy_Success_TestData() + { + yield return new object[] + { + Array.Empty(), + Array.Empty(), + Array.Empty<(string, SortOrder)>() + }; + yield return new object[] + { + new string[] + { + "IsFavoriteOrLiked", + "Random" + }, + Array.Empty(), + new (string, SortOrder)[] + { + ("IsFavoriteOrLiked", SortOrder.Ascending), + ("Random", SortOrder.Ascending), + } + }; + yield return new object[] + { + new string[] + { + "SortName", + "ProductionYear" + }, + new SortOrder[] + { + SortOrder.Descending + }, + new (string, SortOrder)[] + { + ("SortName", SortOrder.Descending), + ("ProductionYear", SortOrder.Ascending), + } + }; + } + } +} From 80f3e20394bc249914ddcb430b4f6d63761ebd29 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 24 Jan 2021 13:22:04 +0100 Subject: [PATCH 1021/1930] Change plugin error message --- .../Plugins/PluginManager.cs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 42c76bd66a..9621b34b62 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -112,9 +112,16 @@ namespace Emby.Server.Implementations.Plugins { assembly = Assembly.LoadFrom(file); - // This force loads all reference dll's that the plugin uses in the try..catch block. - // Removing this will cause JF to bomb out if referenced dll's cause issues. - assembly.GetExportedTypes(); + try + { + assembly.GetExportedTypes(); + } + catch (TypeLoadException ex) // Undocumented exception + { + _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin.", file); + ChangePluginState(plugin, PluginStatus.NotSupported); + continue; + } } catch (FileLoadException ex) { @@ -122,12 +129,6 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.Malfunctioned); continue; } - catch (TypeLoadException ex) - { - _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin. This is probably caused by an incompatible plugin version.", file); - ChangePluginState(plugin, PluginStatus.Malfunctioned); - continue; - } _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file); yield return assembly; From 1c2cd7efa09e46c181ea974a355792373c54e45a Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 24 Jan 2021 13:32:29 +0100 Subject: [PATCH 1022/1930] Remove useless abstraction and clean up formatting --- .../Controllers/UniversalAudioController.cs | 37 ++++++++++++++++--- Jellyfin.Api/Helpers/RequestHelpers.cs | 19 ---------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 34c9f32fa4..bacd95baca 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -278,7 +278,7 @@ namespace Jellyfin.Api.Controllers var directPlayProfiles = new DirectPlayProfile[len]; for (int i = 0; i < len; i++) { - var parts = RequestHelpers.Split(containers[i], '|', true); + var parts = containers[i].Split('|', StringSplitOptions.RemoveEmptyEntries); var audioCodecs = parts.Length == 1 ? null : string.Join(',', parts.Skip(1)); @@ -312,25 +312,52 @@ namespace Jellyfin.Api.Controllers if (maxAudioSampleRate.HasValue) { // codec profile - conditions.Add(new ProfileCondition { Condition = ProfileConditionType.LessThanEqual, IsRequired = false, Property = ProfileConditionValue.AudioSampleRate, Value = maxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) }); + conditions.Add( + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + IsRequired = false, + Property = ProfileConditionValue.AudioSampleRate, + Value = maxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) + }); } if (maxAudioBitDepth.HasValue) { // codec profile - conditions.Add(new ProfileCondition { Condition = ProfileConditionType.LessThanEqual, IsRequired = false, Property = ProfileConditionValue.AudioBitDepth, Value = maxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture) }); + conditions.Add( + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + IsRequired = false, + Property = ProfileConditionValue.AudioBitDepth, + Value = maxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture) + }); } if (maxAudioChannels.HasValue) { // codec profile - conditions.Add(new ProfileCondition { Condition = ProfileConditionType.LessThanEqual, IsRequired = false, Property = ProfileConditionValue.AudioChannels, Value = maxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) }); + conditions.Add( + new ProfileCondition + { + Condition = ProfileConditionType.LessThanEqual, + IsRequired = false, + Property = ProfileConditionValue.AudioChannels, + Value = maxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) + }); } if (conditions.Count > 0) { // codec profile - codecProfiles.Add(new CodecProfile { Type = CodecType.Audio, Container = string.Join(',', containers), Conditions = conditions.ToArray() }); + codecProfiles.Add( + new CodecProfile + { + Type = CodecType.Audio, + Container = string.Join(',', containers), + Conditions = conditions.ToArray() + }); } deviceProfile.CodecProfiles = codecProfiles.ToArray(); diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 056ad83daf..5195bf36ec 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -46,25 +46,6 @@ namespace Jellyfin.Api.Helpers return result; } - /// - /// Splits a string at a separating character into an array of substrings. - /// - /// The string to split. - /// The char that separates the substrings. - /// Option to remove empty substrings from the array. - /// An array of the substrings. - internal static string[] Split(string? value, char separator, bool removeEmpty) - { - if (string.IsNullOrWhiteSpace(value)) - { - return Array.Empty(); - } - - return removeEmpty - ? value.Split(separator, StringSplitOptions.RemoveEmptyEntries) - : value.Split(separator); - } - /// /// Checks if the user can update an entry. /// From 677bba742e343271be39d4da6d10eca9720c0403 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 24 Jan 2021 13:34:22 +0100 Subject: [PATCH 1023/1930] Remove try-catch nesting --- .../Plugins/PluginManager.cs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 9621b34b62..de4b71433a 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -112,16 +112,7 @@ namespace Emby.Server.Implementations.Plugins { assembly = Assembly.LoadFrom(file); - try - { - assembly.GetExportedTypes(); - } - catch (TypeLoadException ex) // Undocumented exception - { - _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin.", file); - ChangePluginState(plugin, PluginStatus.NotSupported); - continue; - } + assembly.GetExportedTypes(); } catch (FileLoadException ex) { @@ -129,6 +120,12 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.Malfunctioned); continue; } + catch (TypeLoadException ex) // Undocumented exception + { + _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin.", file); + ChangePluginState(plugin, PluginStatus.NotSupported); + continue; + } _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file); yield return assembly; From 39f9a7981a48d939b1ca2dd742ef9051e7bf9598 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Sun, 24 Jan 2021 13:35:08 +0100 Subject: [PATCH 1024/1930] Update MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs Co-authored-by: Cody Robibero --- .../Parsers/BaseNfoParser.cs | 36 ++++++------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index a230127167..f889327e0e 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -1036,34 +1036,18 @@ namespace MediaBrowser.XbmcMetadata.Parsers if (!string.IsNullOrWhiteSpace(val)) { - switch (val) + type = val switch { - case PersonType.Composer: - type = PersonType.Composer; - break; - case PersonType.Conductor: - type = PersonType.Conductor; - break; - case PersonType.Director: - type = PersonType.Director; - break; - case PersonType.Lyricist: - type = PersonType.Lyricist; - break; - case PersonType.Producer: - type = PersonType.Producer; - break; - case PersonType.Writer: - type = PersonType.Writer; - break; - case PersonType.GuestStar: - type = PersonType.GuestStar; - break; + PersonType.Composer => PersonType.Composer, + PersonType.Conductor => PersonType.Conductor, + PersonType.Director => PersonType.Director, + PersonType.Lyricist => PersonType.Lyricist, + PersonType.Producer => PersonType.Producer, + PersonType.Writer => PersonType.Writer, + PersonType.GuestStar => PersonType.GuestStar, // unknown type --> actor - default: - type = PersonType.Actor; - break; - } + _ => PersonType.Actor + }; } break; From f6b293203aac0dd57c93ca9e77b8441a2c1918fd Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 24 Jan 2021 17:55:25 +0100 Subject: [PATCH 1025/1930] Restore weird behaviour --- Jellyfin.Api/Helpers/RequestHelpers.cs | 6 ++++-- tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 59cb8ea2c1..cd1e31e804 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -40,10 +40,12 @@ namespace Jellyfin.Api.Helpers result[i] = (sortBy[i], requestedSortOrder[i]); } - // Add remaining elements with the default SortOrder + // Add remaining elements with the first specified SortOrder + // or the default one if no SortOrders are specified + var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending; for (; i < sortBy.Count; i++) { - result[i] = (sortBy[i], SortOrder.Ascending); + result[i] = (sortBy[i], order); } return result; diff --git a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs index 944472c689..606041c7f4 100644 --- a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs +++ b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs @@ -51,7 +51,7 @@ namespace Jellyfin.Api.Tests.Helpers new (string, SortOrder)[] { ("SortName", SortOrder.Descending), - ("ProductionYear", SortOrder.Ascending), + ("ProductionYear", SortOrder.Descending), } }; } From 326fa8ce384d4e0c433007e02f3f68b8d5538e55 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Mon, 25 Jan 2021 03:40:34 +0800 Subject: [PATCH 1026/1930] add an enhanced nvdec decoder --- .../MediaEncoding/EncodingHelper.cs | 514 +++++++++--------- .../Configuration/EncodingOptions.cs | 3 + 2 files changed, 262 insertions(+), 255 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index efab87a38e..3b70ed9ddc 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -112,6 +112,11 @@ namespace MediaBrowser.Controller.MediaEncoding return _mediaEncoder.SupportsHwaccel("vaapi"); } + private bool IsCudaSupported(EncodingJobInfo state) + { + return _mediaEncoder.SupportsHwaccel("cuda"); + } + private bool IsTonemappingSupported(EncodingJobInfo state, EncodingOptions options) { var videoStream = state.VideoStream; @@ -458,7 +463,8 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1; var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; + var isCuvidHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); @@ -534,8 +540,17 @@ namespace MediaBrowser.Controller.MediaEncoding } if (state.IsVideoRequest - && (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder) - || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder)) + && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)) + { + if (isNvdecDecoder) + { + arg.Append("-hwaccel_output_format cuda "); + } + } + + if (state.IsVideoRequest + && (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder)) + || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder))) { if (isTonemappingSupported) { @@ -922,18 +937,23 @@ namespace MediaBrowser.Controller.MediaEncoding { var videoStream = state.VideoStream; var isColorDepth10 = IsColorDepth10(state); + var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty; + var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; - if (isColorDepth10 - && _mediaEncoder.SupportsHwaccel("opencl") - && encodingOptions.EnableTonemapping - && !string.IsNullOrEmpty(videoStream.VideoRange) - && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) + if (!isNvdecDecoder) { - param += " -pix_fmt nv12"; - } - else - { - param += " -pix_fmt yuv420p"; + if (isColorDepth10 + && _mediaEncoder.SupportsHwaccel("opencl") + && encodingOptions.EnableTonemapping + && !string.IsNullOrEmpty(videoStream.VideoRange) + && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase)) + { + param += " -pix_fmt nv12"; + } + else + { + param += " -pix_fmt yuv420p"; + } } } @@ -1912,6 +1932,8 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; + var isNvencEncoder = outputVideoCodec.IndexOf("nvenc", StringComparison.OrdinalIgnoreCase) != -1; var isTonemappingSupported = IsTonemappingSupported(state, options); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); @@ -1940,11 +1962,14 @@ namespace MediaBrowser.Controller.MediaEncoding height.Value); } - // For QSV, feed it into hardware encoder now - if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) - || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))) + if (!string.IsNullOrEmpty(videoSizeParam)) { - videoSizeParam += ",hwupload=extra_hw_frames=64"; + // For QSV, feed it into hardware encoder now + if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) + || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))) + { + videoSizeParam += ",hwupload=extra_hw_frames=64"; + } } } @@ -2002,6 +2027,12 @@ namespace MediaBrowser.Controller.MediaEncoding : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv\""; } } + else if (isNvdecDecoder && isNvencEncoder) + { + retStr = !outputSizeParam.IsEmpty + ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=yuv420p|nv12,hwupload_cuda\"" + : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=yuv420p|nv12,hwupload_cuda\""; + } return string.Format( CultureInfo.InvariantCulture, @@ -2133,6 +2164,26 @@ namespace MediaBrowser.Controller.MediaEncoding (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty)); } } + else if ((videoDecoder ?? string.Empty).IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1 + && width.HasValue + && height.HasValue) + { + var outputWidth = width.Value; + var outputHeight = height.Value; + + if (!videoWidth.HasValue + || outputWidth != videoWidth.Value + || !videoHeight.HasValue + || outputHeight != videoHeight.Value) + { + filters.Add( + string.Format( + CultureInfo.InvariantCulture, + "scale_cuda=w={0}:h={1}", + outputWidth, + outputHeight)); + } + } else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1 && width.HasValue && height.HasValue) @@ -2367,17 +2418,20 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1; var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecH264Decoder = videoDecoder.IndexOf("h264_cuvid", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; + var isNvencEncoder = outputVideoCodec.IndexOf("nvenc", StringComparison.OrdinalIgnoreCase) != -1; + var isCuvidH264Decoder = videoDecoder.IndexOf("h264_cuvid", StringComparison.OrdinalIgnoreCase) != -1; + var isCuvidHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1; var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1; var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isColorDepth10 = IsColorDepth10(state); var isTonemappingSupported = IsTonemappingSupported(state, options); - var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecHevcDecoder || isSwDecoder; - var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && isD3d11vaDecoder || isSwDecoder; + var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder); + var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; @@ -2385,6 +2439,8 @@ namespace MediaBrowser.Controller.MediaEncoding var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.RealFrameRate ?? 60) <= 30; var isScalingInAdvance = false; + var isCudaDeintInAdvance = false; + var isHwuploadCudaRequired = false; var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true); var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true); @@ -2428,15 +2484,17 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add("format=p010"); } - if (isNvdecHevcDecoder || isSwDecoder || isD3d11vaDecoder) + if ((isDeinterlaceH264 || isDeinterlaceHevc) && isNvdecDecoder) { - // Upload the HDR10 or HLG data to the OpenCL device, - // use tonemap_opencl filter for tone mapping, - // and then download the SDR data to memory. - filters.Add("hwupload"); + isCudaDeintInAdvance = true; + filters.Add( + string.Format( + CultureInfo.InvariantCulture, + "yadif={0}:-1:0", + doubleRateDeinterlace ? "1" : "0")); } - if (isVaapiDecoder) + if (isVaapiDecoder || isNvdecDecoder) { isScalingInAdvance = true; filters.AddRange( @@ -2452,11 +2510,28 @@ namespace MediaBrowser.Controller.MediaEncoding request.Height, request.MaxWidth, request.MaxHeight)); + } - // hwmap the HDR data to opencl device by cl-va p010 interop. + // hwmap the HDR data to opencl device by cl-va p010 interop. + if (isVaapiDecoder) + { filters.Add("hwmap"); } + // convert cuda device data to p010 host data. + if (isNvdecDecoder) + { + filters.Add("hwdownload,format=p010"); + } + + if (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder || isD3d11vaDecoder) + { + // Upload the HDR10 or HLG data to the OpenCL device, + // use tonemap_opencl filter for tone mapping, + // and then download the SDR data to memory. + filters.Add("hwupload"); + } + filters.Add( string.Format( CultureInfo.InvariantCulture, @@ -2468,21 +2543,15 @@ namespace MediaBrowser.Controller.MediaEncoding options.TonemappingParam, options.TonemappingRange)); - if (isNvdecHevcDecoder || isSwDecoder || isD3d11vaDecoder) + if (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder || isD3d11vaDecoder) { filters.Add("hwdownload"); + filters.Add("format=nv12"); } - if (isSwDecoder || isD3d11vaDecoder) + if (isNvdecDecoder && isNvencEncoder) { - if (isLibX264Encoder - || isLibX265Encoder - || hasGraphicalSubs - || (isNvdecHevcDecoder && isDeinterlaceHevc) - || (!isNvdecHevcDecoder && isDeinterlaceH264 || isDeinterlaceHevc)) - { - filters.Add("format=nv12"); - } + isHwuploadCudaRequired = true; } if (isVaapiDecoder) @@ -2507,7 +2576,7 @@ namespace MediaBrowser.Controller.MediaEncoding } // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first. - else if (IsVaapiSupported(state) && isVaapiDecoder && (isLibX264Encoder || isLibX265Encoder)) + else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)) { var codec = videoStream.Codec.ToLowerInvariant(); @@ -2534,9 +2603,9 @@ namespace MediaBrowser.Controller.MediaEncoding } // Add hardware deinterlace filter before scaling filter. - if (isDeinterlaceH264) + if (isDeinterlaceH264 || isDeinterlaceHevc) { - if (isVaapiH264Encoder) + if (isVaapiEncoder) { filters.Add( string.Format( @@ -2544,6 +2613,14 @@ namespace MediaBrowser.Controller.MediaEncoding "deinterlace_vaapi=rate={0}", doubleRateDeinterlace ? "field" : "frame")); } + else if (isNvdecDecoder && !isCudaDeintInAdvance) + { + filters.Add( + string.Format( + CultureInfo.InvariantCulture, + "yadif_cuda={0}:-1:0", + doubleRateDeinterlace ? "1" : "0")); + } } // Add software deinterlace filter before scaling filter. @@ -2552,7 +2629,8 @@ namespace MediaBrowser.Controller.MediaEncoding && !isVaapiHevcEncoder && !isQsvH264Encoder && !isQsvHevcEncoder - && !isNvdecH264Decoder) + && !isNvdecDecoder + && !isCuvidH264Decoder) { if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase)) { @@ -2590,6 +2668,41 @@ namespace MediaBrowser.Controller.MediaEncoding request.MaxHeight)); } + // Another case is using Nvenc decoder. + if (isNvdecDecoder && !isTonemappingSupported) + { + var codec = videoStream.Codec.ToLowerInvariant(); + + // Assert 10-bit hardware decodable + if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) + || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))) + { + // Download data from GPU to CPU as p010le format. + filters.Add("hwdownload"); + filters.Add("format=p010"); + + // cuda lacks of a pixel format converter. + if (isNvencEncoder) + { + isHwuploadCudaRequired = true; + filters.Add("format=yuv420p"); + } + } + + // Assert 8-bit hardware decodable + else if (!isColorDepth10 && (isLibX264Encoder || isLibX265Encoder || hasSubs)) + { + if (isNvencEncoder) + { + isHwuploadCudaRequired = true; + } + + filters.Add("hwdownload"); + filters.Add("format=nv12"); + } + } + // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642) if (isVaapiH264Encoder || isVaapiHevcEncoder) { @@ -2618,10 +2731,20 @@ namespace MediaBrowser.Controller.MediaEncoding // Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API // Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI - if (isVaapiH264Encoder) + if (isVaapiH264Encoder || isVaapiHevcEncoder) { filters.Add("hwmap"); } + + if (isNvdecDecoder && isNvencEncoder) + { + isHwuploadCudaRequired = true; + } + } + + if (isHwuploadCudaRequired && !hasGraphicalSubs) + { + filters.Add("hwupload_cuda"); } if (filters.Count > 0) @@ -3102,57 +3225,18 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - if (_mediaEncoder.SupportsDecoder("h264_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - // qsv decoder does not support 10-bit input - if ((videoStream.BitDepth ?? 8) > 8) - { - encodingOptions.HardwareDecodingCodecs = Array.Empty(); - return null; - } - - return "-c:v h264_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "h264_qsv", "h264", isColorDepth10); case "hevc": case "h265": - if (_mediaEncoder.SupportsDecoder("hevc_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "hevc_qsv", "hevc", isColorDepth10); case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("mpeg2_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg2_qsv", "mpeg2video", isColorDepth10); case "vc1": - if (_mediaEncoder.SupportsDecoder("vc1_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vc1_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "vc1_qsv", "vc1", isColorDepth10); case "vp8": - if (_mediaEncoder.SupportsDecoder("vp8_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vp8_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp8_qsv", "vp8", isColorDepth10); case "vp9": - if (_mediaEncoder.SupportsDecoder("vp9_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_qsv"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp9_qsv", "vp9", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)) @@ -3161,57 +3245,34 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - if (_mediaEncoder.SupportsDecoder("h264_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "h264", isColorDepth10) + : GetHwDecoderName(encodingOptions, "h264_cuvid", "h264", isColorDepth10); case "hevc": case "h265": - if (_mediaEncoder.SupportsDecoder("hevc_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10) + : GetHwDecoderName(encodingOptions, "hevc_cuvid", "hevc", isColorDepth10); case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("mpeg2_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10) + : GetHwDecoderName(encodingOptions, "mpeg2_cuvid", "mpeg2video", isColorDepth10); case "vc1": - if (_mediaEncoder.SupportsDecoder("vc1_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vc1_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10) + : GetHwDecoderName(encodingOptions, "vc1_cuvid", "vc1", isColorDepth10); case "mpeg4": - if (_mediaEncoder.SupportsDecoder("mpeg4_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg4_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10) + : GetHwDecoderName(encodingOptions, "mpeg4_cuvid", "mpeg4", isColorDepth10); case "vp8": - if (_mediaEncoder.SupportsDecoder("vp8_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vp8_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10) + : GetHwDecoderName(encodingOptions, "vp8_cuvid", "vp8", isColorDepth10); case "vp9": - if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_cuvid"; - } - - break; + return encodingOptions.EnableEnhancedNvdecDecoder + ? GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10) + : GetHwDecoderName(encodingOptions, "vp9_cuvid", "vp9", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase)) @@ -3220,50 +3281,18 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - if (_mediaEncoder.SupportsDecoder("h264_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "h264_mediacodec", "h264", isColorDepth10); case "hevc": case "h265": - if (_mediaEncoder.SupportsDecoder("hevc_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "hevc_mediacodec", "hevc", isColorDepth10); case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("mpeg2_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg2_mediacodec", "mpeg2video", isColorDepth10); case "mpeg4": - if (_mediaEncoder.SupportsDecoder("mpeg4_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg4_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg4_mediacodec", "mpeg4", isColorDepth10); case "vp8": - if (_mediaEncoder.SupportsDecoder("vp8_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vp8_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp8_mediacodec", "vp8", isColorDepth10); case "vp9": - if (_mediaEncoder.SupportsDecoder("vp9_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_mediacodec"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp9_mediacodec", "vp9", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase)) @@ -3272,33 +3301,13 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_mmal"; - } - - break; + return GetHwDecoderName(encodingOptions, "h264_mmal", "h264", isColorDepth10); case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_mmal"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg2_mmal", "mpeg2video", isColorDepth10); case "mpeg4": - if (_mediaEncoder.SupportsDecoder("mpeg4_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg4_mmal"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg4_mmal", "mpeg4", isColorDepth10); case "vc1": - if (_mediaEncoder.SupportsDecoder("vc1_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vc1_mmal"; - } - - break; + return GetHwDecoderName(encodingOptions, "vc1_mmal", "vc1", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase)) @@ -3307,20 +3316,18 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - return GetHwaccelType(state, encodingOptions, "h264"); + return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10); case "hevc": case "h265": - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : GetHwaccelType(state, encodingOptions, "hevc"); + return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10); case "mpeg2video": - return GetHwaccelType(state, encodingOptions, "mpeg2video"); + return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10); case "vc1": - return GetHwaccelType(state, encodingOptions, "vc1"); + return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10); case "mpeg4": - return GetHwaccelType(state, encodingOptions, "mpeg4"); + return GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10); case "vp9": - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : GetHwaccelType(state, encodingOptions, "vp9"); + return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)) @@ -3329,20 +3336,18 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - return GetHwaccelType(state, encodingOptions, "h264"); + return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10); case "hevc": case "h265": - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : GetHwaccelType(state, encodingOptions, "hevc"); + return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10); case "mpeg2video": - return GetHwaccelType(state, encodingOptions, "mpeg2video"); + return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10); case "vc1": - return GetHwaccelType(state, encodingOptions, "vc1"); + return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10); case "vp8": - return GetHwaccelType(state, encodingOptions, "vp8"); + return GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10); case "vp9": - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : GetHwaccelType(state, encodingOptions, "vp9"); + return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10); } } else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase)) @@ -3351,57 +3356,20 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - if (_mediaEncoder.SupportsDecoder("h264_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v h264_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "h264_opencl", "h264", isColorDepth10); case "hevc": case "h265": - if (_mediaEncoder.SupportsDecoder("hevc_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "hevc_opencl", "hevc", isColorDepth10); case "mpeg2video": - if (_mediaEncoder.SupportsDecoder("mpeg2_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg2_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg2_opencl", "mpeg2video", isColorDepth10); case "mpeg4": - if (_mediaEncoder.SupportsDecoder("mpeg4_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v mpeg4_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "mpeg4_opencl", "mpeg4", isColorDepth10); case "vc1": - if (_mediaEncoder.SupportsDecoder("vc1_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vc1_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "vc1_opencl", "vc1", isColorDepth10); case "vp8": - if (_mediaEncoder.SupportsDecoder("vp8_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return "-c:v vp8_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp8_opencl", "vp8", isColorDepth10); case "vp9": - if (_mediaEncoder.SupportsDecoder("vp9_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) - { - return (isColorDepth10 && - !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_opencl"; - } - - break; + return GetHwDecoderName(encodingOptions, "vp9_opencl", "vp9", isColorDepth10); } } } @@ -3424,15 +3392,43 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } + /// + /// Gets a hw decoder name + /// + public string GetHwDecoderName(EncodingOptions options, string decoder, string videoCodec, bool isColorDepth10) + { + var isCodecAvailable = _mediaEncoder.SupportsDecoder(decoder) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase); + if (isColorDepth10 && isCodecAvailable) + { + if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc) + || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9)) + { + return null; + } + } + + return isCodecAvailable ? ("-c:v " + decoder) : null; + } + /// /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system /// - public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec) + public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec, bool isColorDepth10) { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1); var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va"); + var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase); + + if (isColorDepth10 && isCodecAvailable) + { + if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc) + || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9)) + { + return null; + } + } if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase)) { @@ -3462,6 +3458,14 @@ namespace MediaBrowser.Controller.MediaEncoding } } + if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)) + { + if (IsCudaSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase)) + { + return "-hwaccel cuda"; + } + } + return null; } diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index 38b3335107..5cd8744eda 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -65,6 +65,8 @@ namespace MediaBrowser.Model.Configuration public bool EnableDecodingColorDepth10Vp9 { get; set; } + public bool EnableEnhancedNvdecDecoder { get; set; } + public bool EnableHardwareEncoding { get; set; } public bool AllowHevcEncoding { get; set; } @@ -100,6 +102,7 @@ namespace MediaBrowser.Model.Configuration DeinterlaceMethod = "yadif"; EnableDecodingColorDepth10Hevc = true; EnableDecodingColorDepth10Vp9 = true; + EnableEnhancedNvdecDecoder = true; EnableHardwareEncoding = true; AllowHevcEncoding = true; EnableSubtitleExtraction = true; From ef97ead707a100f1599d22a7b37095ed6f3fd041 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 24 Jan 2021 14:36:36 -0700 Subject: [PATCH 1027/1930] Fix openapi nullable properties --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 77fb64674d..da4cc267b3 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -308,6 +308,9 @@ namespace Jellyfin.Server.Extensions ?? null; }); + // Allow parameters to properly be nullable. + c.UseAllOfToExtendReferenceSchemas(); + // TODO - remove when all types are supported in System.Text.Json c.AddSwaggerTypeMappings(); From 77b417e41e76dadfacbff5605c81eeb5ce2d5d2d Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 24 Jan 2021 15:02:56 -0700 Subject: [PATCH 1028/1930] Mark non-nullable body as null --- Jellyfin.Api/Controllers/PackageController.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index 9ab8e0bdcf..c589f54ac4 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -158,7 +158,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Repositories")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult SetRepositories([FromBody] List repositoryInfos) + public ActionResult SetRepositories([FromBody, Required] List repositoryInfos) { _serverConfigurationManager.Configuration.PluginRepositories = repositoryInfos; _serverConfigurationManager.SaveConfiguration(); diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 0f0bee4bcf..87a4ffd92e 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -514,7 +514,7 @@ namespace Jellyfin.Api.Controllers /// A containing a . [HttpPost("ForgotPassword/Pin")] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> ForgotPasswordPin([FromBody] string? pin) + public async Task> ForgotPasswordPin([FromBody, Required] string pin) { var result = await _userManager.RedeemPasswordResetPin(pin).ConfigureAwait(false); return result; From b014f2309d546779d7e9530daa1ddd55741cbb32 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Mon, 25 Jan 2021 09:44:06 +0100 Subject: [PATCH 1029/1930] Update Emby.Server.Implementations/Plugins/PluginManager.cs Co-authored-by: Claus Vium --- Emby.Server.Implementations/Plugins/PluginManager.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index de4b71433a..adf62124a7 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -126,6 +126,14 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.NotSupported); continue; } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin.", file); + ChangePluginState(plugin, PluginStatus.Malfunctioned); + continue; + } _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, file); yield return assembly; From 09471a206a51f1d0ce740d75ac53c50e35d7ca98 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Jan 2021 12:00:44 +0000 Subject: [PATCH 1030/1930] Bump coverlet.collector from 3.0.1 to 3.0.2 Bumps [coverlet.collector](https://github.com/coverlet-coverage/coverlet) from 3.0.1 to 3.0.2. - [Release notes](https://github.com/coverlet-coverage/coverlet/releases) - [Commits](https://github.com/coverlet-coverage/coverlet/commits) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 98a2cda607..3da728c633 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 7ff4d0e87c..57edbf902c 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index af412eed3b..c766c54458 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 21389b926d..52a9e11932 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 9a1cfcfa41..24f6fb3561 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 31e41b12f9..a4d5c0d6fd 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index bb2bae8e8f..d77645cd9e 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 7f909847ec..469fe01e29 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -20,7 +20,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index fe40122a35..2106a78a84 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -18,7 +18,7 @@ - + From 4e2d029b3df0e5c77adc7c7fee25f76d209c7946 Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 25 Jan 2021 08:48:24 -0700 Subject: [PATCH 1031/1930] Add null check for ImageTags --- Emby.Server.Implementations/Dto/DtoService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 8a901516c0..e3ab0d6eab 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1157,7 +1157,7 @@ namespace Emby.Server.Implementations.Dto if (episodeSeries != null) { dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, episodeSeries, ImageType.Primary); - if (!dto.ImageTags.ContainsKey(ImageType.Primary)) + if (dto.ImageTags == null || !dto.ImageTags.ContainsKey(ImageType.Primary)) { AttachPrimaryImageAspectRatio(dto, episodeSeries); } @@ -1207,7 +1207,7 @@ namespace Emby.Server.Implementations.Dto if (series != null) { dto.SeriesPrimaryImageTag = GetTagAndFillBlurhash(dto, series, ImageType.Primary); - if (!dto.ImageTags.ContainsKey(ImageType.Primary)) + if (dto.ImageTags == null || !dto.ImageTags.ContainsKey(ImageType.Primary)) { AttachPrimaryImageAspectRatio(dto, series); } From 21d15989f5abe6d50529207df4df047c0e3f06ea Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 25 Jan 2021 17:34:11 +0000 Subject: [PATCH 1032/1930] 1 attempted fix --- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index e1be79a060..c1f5bfb255 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -203,10 +203,10 @@ namespace MediaBrowser.XbmcMetadata.Savers var directory = Path.GetDirectoryName(path) ?? throw new ArgumentException($"Provided path ({path}) is not valid.", nameof(path)); Directory.CreateDirectory(directory); - // On Windows, savint the file will fail if the file is hidden or readonly + // On Windows, saving the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); - using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) + using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { stream.CopyTo(filestream); } From 0d1f3563735d8ce212080719345fdd4afc835bb5 Mon Sep 17 00:00:00 2001 From: Mariusz Chryc Date: Tue, 26 Jan 2021 19:04:20 +0100 Subject: [PATCH 1033/1930] Remove season name from metadata result --- MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs index 6ca462474a..4c1f697632 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonProvider.cs @@ -54,7 +54,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV result.HasMetadata = true; result.Item = new Season { - Name = info.Name, IndexNumber = seasonNumber, Overview = seasonResult?.Overview }; From 80e22d9670f3ea8b722e1e57bc73529a5c652b25 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 26 Jan 2021 20:21:07 +0100 Subject: [PATCH 1034/1930] Add test for ShuffleExtensions --- .../Extensions/ShuffleExtensionsTests.cs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 tests/Jellyfin.Common.Tests/Extensions/ShuffleExtensionsTests.cs diff --git a/tests/Jellyfin.Common.Tests/Extensions/ShuffleExtensionsTests.cs b/tests/Jellyfin.Common.Tests/Extensions/ShuffleExtensionsTests.cs new file mode 100644 index 0000000000..cbdbcf112c --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Extensions/ShuffleExtensionsTests.cs @@ -0,0 +1,22 @@ +using System; +using MediaBrowser.Common.Extensions; +using Xunit; + +namespace Jellyfin.Common.Tests.Extensions +{ + public static class ShuffleExtensionsTests + { + private static readonly Random _rng = new Random(); + + [Fact] + public static void Shuffle_Valid_Correct() + { + byte[] original = new byte[1 << 6]; + _rng.NextBytes(original); + byte[] shuffled = (byte[])original.Clone(); + shuffled.Shuffle(); + + Assert.NotEqual(original, shuffled); + } + } +} From bf4829a38ce6b393c2bbab258c4a7ebe5ee33aba Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 26 Jan 2021 20:28:35 +0100 Subject: [PATCH 1035/1930] Remove redundant statement --- MediaBrowser.Common/Extensions/ShuffleExtensions.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Extensions/ShuffleExtensions.cs b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs index 459bec1105..6f0ea9bd58 100644 --- a/MediaBrowser.Common/Extensions/ShuffleExtensions.cs +++ b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs @@ -33,8 +33,7 @@ namespace MediaBrowser.Common.Extensions int n = list.Count; while (n > 1) { - n--; - int k = rng.Next(n + 1); + int k = rng.Next(n--); T value = list[k]; list[k] = list[n]; list[n] = value; From 3ce0d589ba49ad46cb6167955e4f8561ba1d29aa Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Thu, 28 Jan 2021 01:00:55 +0800 Subject: [PATCH 1036/1930] make FRAME-RATE field culture invariant --- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index a4da54cfdf..92ff42b49f 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -427,7 +427,7 @@ namespace Jellyfin.Api.Helpers if (framerate.HasValue) { builder.Append(",FRAME-RATE=") - .Append(framerate.Value); + .Append(framerate.Value.ToString(CultureInfo.InvariantCulture)); } } From a50459a2a1020b53b3f7005bbb3b08c488c477ee Mon Sep 17 00:00:00 2001 From: WWWesten Date: Thu, 28 Jan 2021 19:29:23 +0000 Subject: [PATCH 1037/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- Emby.Server.Implementations/Localization/Core/kk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index befe4e14f6..b34e28b064 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -118,5 +118,5 @@ "TaskRefreshLibraryDescription": "Tasyǵyshhanadaǵy jańa faıldardy skanerleıdі jáne metaderekterdі jańartady.", "TaskRefreshChapterImagesDescription": "Sahnalarǵa bólіngen beıneler úshіn nobaılar jasaıdy.", "TaskCleanCacheDescription": "Júıede qajet emes keshtelgen faıldardy joıady.", - "TaskCleanActivityLogDescription": "Áreketter jurnalyndaǵy teńshelgen jasynan asqan jazbalaly joıady." + "TaskCleanActivityLogDescription": "Áreketter jurnalyndaǵy teńshelgen jasynan asqan jazbalary joıady." } From 027ef41d87d3093e940acac87f865faf43c8d886 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Sun, 31 Jan 2021 10:33:51 +0000 Subject: [PATCH 1038/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- .../Localization/Core/kk.json | 220 +++++++++--------- 1 file changed, 110 insertions(+), 110 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index b34e28b064..f4f6b442e0 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -1,122 +1,122 @@ { - "Albums": "Álbomdar", - "AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}", + "Albums": "Älbomdar", + "AppDeviceValues": "Qoldanba: {0}, Qūrylğy: {1}", "Application": "Qoldanba", - "Artists": "Oryndaýshylar", - "AuthenticationSucceededWithUserName": "{0} túpnusqalyq rastalýy sátti aıaqtaldy", - "Books": "Kitaptar", - "CameraImageUploadedFrom": "{0} kamerasynan jańa sýret júktep salyndy", + "Artists": "Oryndauşylar", + "AuthenticationSucceededWithUserName": "{0} tüpnūsqalyq rastaluy sättı aiaqtaldy", + "Books": "Kıtaptar", + "CameraImageUploadedFrom": "{0} kamerasynan jaŋa suret jüktep salyndy", "Channels": "Arnalar", "ChapterNameValue": "{0}-sahna", - "Collections": "Jıyntyqtar", - "DeviceOfflineWithName": "{0} ajyratylǵan", - "DeviceOnlineWithName": "{0} qosylǵan", - "FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz aıaqtaldy", - "Favorites": "Tańdaýlylar", + "Collections": "Jiyntyqtar", + "DeviceOfflineWithName": "{0} ajyratylğan", + "DeviceOnlineWithName": "{0} qosylğan", + "FailedLoginAttemptWithUserName": "{0} tarapynan kıru äreketı sätsız aiaqtaldy", + "Favorites": "Taŋdaulylar", "Folders": "Qaltalar", "Genres": "Janrlar", - "HeaderAlbumArtists": "Álbom oryndaýshylary", - "HeaderContinueWatching": "Qaraýdy jalǵastyrý", - "HeaderFavoriteAlbums": "Tańdaýly álbomdar", - "HeaderFavoriteArtists": "Tańdaýly oryndaýshylar", - "HeaderFavoriteEpisodes": "Tańdaýly bólimder", - "HeaderFavoriteShows": "Tańdaýly kórsetimder", - "HeaderFavoriteSongs": "Tańdaýly áýender", - "HeaderLiveTV": "Efır", - "HeaderNextUp": "Kezekti", + "HeaderAlbumArtists": "Älbom oryndauşylary", + "HeaderContinueWatching": "Qaraudy jalğastyru", + "HeaderFavoriteAlbums": "Taŋdauly älbomdar", + "HeaderFavoriteArtists": "Taŋdauly oryndauşylar", + "HeaderFavoriteEpisodes": "Taŋdauly bölımder", + "HeaderFavoriteShows": "Taŋdauly körsetımder", + "HeaderFavoriteSongs": "Taŋdauly äuender", + "HeaderLiveTV": "Efir", + "HeaderNextUp": "Kezektı", "HeaderRecordingGroups": "Jazba toptary", - "HomeVideos": "Úılik beıneler", - "Inherit": "Muraǵa ıelený", - "ItemAddedWithName": "{0} tasyǵyshhanaǵa ústeldi", - "ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy", - "LabelIpAddressValue": "IP-mekenjaıy: {0}", - "LabelRunningTimeValue": "Oınatý ýaqyty: {0}", - "Latest": "Eń keıingi", - "MessageApplicationUpdated": "Jellyfin Serveri jańartyldy", - "MessageApplicationUpdatedTo": "Jellyfin Serveri {0} nusqasyna jańartyldy", - "MessageNamedServerConfigurationUpdatedWithValue": "Server konfıgýrasýasynyń {0} bólimi jańartyldy", - "MessageServerConfigurationUpdated": "Server konfıgýrasıasy jańartyldy", - "MixedContent": "Aralas mazmun", - "Movies": "Fılmder", - "Music": "Mýzyka", - "MusicVideos": "Mýzykalyq beıneler", - "NameInstallFailed": "{0} ornatylýy sátsiz", - "NameSeasonNumber": "{0}-maýsym", - "NameSeasonUnknown": "Belgisiz maýsym", - "NewVersionIsAvailable": "Jańa Jellyfin Server nusqasy júktep alýǵa qoljetimdi.", - "NotificationOptionApplicationUpdateAvailable": "Qoldanba jańartýy qoljetimdi", - "NotificationOptionApplicationUpdateInstalled": "Qoldanba jańartýy ornatyldy", - "NotificationOptionAudioPlayback": "Dybys oınatýy bastaldy", - "NotificationOptionAudioPlaybackStopped": "Dybys oınatýy toqtatyldy", - "NotificationOptionCameraImageUploaded": "Kameradan fotosýret júktep salynǵan", - "NotificationOptionInstallationFailed": "Ornatý sátsizdigi", - "NotificationOptionNewLibraryContent": "Jańa mazmun ústelgen", - "NotificationOptionPluginError": "Plagın sátsizdigi", - "NotificationOptionPluginInstalled": "Plagın ornatyldy", - "NotificationOptionPluginUninstalled": "Plagın ornatýy boldyrylmady", - "NotificationOptionPluginUpdateInstalled": "Plagın jańartýy ornatyldy", - "NotificationOptionServerRestartRequired": "Serverdi qaıta iske qosý qajet", - "NotificationOptionTaskFailed": "Josparlaǵan tapsyrma sátsizdigi", - "NotificationOptionUserLockedOut": "Paıdalanýshy qursaýly", - "NotificationOptionVideoPlayback": "Beıne oınatýy bastaldy", - "NotificationOptionVideoPlaybackStopped": "Beıne oınatýy toqtatyldy", - "Photos": "Fotosýretter", - "Playlists": "Oınatý tizimderi", - "Plugin": "Plagın", + "HomeVideos": "Üilık beineler", + "Inherit": "Mūrağa ielenu", + "ItemAddedWithName": "{0} tasyğyşhanağa üsteldı", + "ItemRemovedWithName": "{0} tasyğyşhanadan alastaldy", + "LabelIpAddressValue": "İP-mekenjaiy: {0}", + "LabelRunningTimeValue": "Oinatu uaqyty: {0}", + "Latest": "Eŋ keiıngı", + "MessageApplicationUpdated": "Jellyfin Serverı jaŋartyldy", + "MessageApplicationUpdatedTo": "Jellyfin Serverı {0} nūsqasyna jaŋartyldy", + "MessageNamedServerConfigurationUpdatedWithValue": "Server konfigurasuasynyŋ {0} bölımı jaŋartyldy", + "MessageServerConfigurationUpdated": "Server konfigurasiasy jaŋartyldy", + "MixedContent": "Aralas mazmūn", + "Movies": "Filmder", + "Music": "Muzyka", + "MusicVideos": "Muzykalyq beineler", + "NameInstallFailed": "{0} ornatyluy sätsız", + "NameSeasonNumber": "{0}-mausym", + "NameSeasonUnknown": "Belgısız mausym", + "NewVersionIsAvailable": "Jaŋa Jellyfin Server nūsqasy jüktep aluğa qoljetımdı.", + "NotificationOptionApplicationUpdateAvailable": "Qoldanba jaŋartuy qoljetımdı", + "NotificationOptionApplicationUpdateInstalled": "Qoldanba jaŋartuy ornatyldy", + "NotificationOptionAudioPlayback": "Dybys oinatuy bastaldy", + "NotificationOptionAudioPlaybackStopped": "Dybys oinatuy toqtatyldy", + "NotificationOptionCameraImageUploaded": "Kameradan fotosuret jüktep salynğan", + "NotificationOptionInstallationFailed": "Ornatu sätsızdıgı", + "NotificationOptionNewLibraryContent": "Jaŋa mazmūn üstelgen", + "NotificationOptionPluginError": "Plagin sätsızdıgı", + "NotificationOptionPluginInstalled": "Plagin ornatyldy", + "NotificationOptionPluginUninstalled": "Plagin ornatuy boldyrylmady", + "NotificationOptionPluginUpdateInstalled": "Plagin jaŋartuy ornatyldy", + "NotificationOptionServerRestartRequired": "Serverdı qaita ıske qosu qajet", + "NotificationOptionTaskFailed": "Josparlağan tapsyrma sätsızdıgı", + "NotificationOptionUserLockedOut": "Paidalanuşy qūrsauly", + "NotificationOptionVideoPlayback": "Beine oinatuy bastaldy", + "NotificationOptionVideoPlaybackStopped": "Beine oinatuy toqtatyldy", + "Photos": "Fotosuretter", + "Playlists": "Oinatu tızımderı", + "Plugin": "Plagin", "PluginInstalledWithName": "{0} ornatyldy", - "PluginUninstalledWithName": "{0} joıyldy", - "PluginUpdatedWithName": "{0} jańartyldy", - "ProviderValue": "Jetkizýshi: {0}", - "ScheduledTaskFailedWithName": "{0} sátsiz", - "ScheduledTaskStartedWithName": "{0} iske qosyldy", - "ServerNameNeedsToBeRestarted": "{0} qaıta iske qosý qajet", - "Shows": "Kórsetimder", - "Songs": "Áýender", - "StartupEmbyServerIsLoading": "Jellyfin Server júktelýde. Áreketti kóp uzamaı qaıtalańyz.", + "PluginUninstalledWithName": "{0} joiyldy", + "PluginUpdatedWithName": "{0} jaŋartyldy", + "ProviderValue": "Jetkızuşı: {0}", + "ScheduledTaskFailedWithName": "{0} sätsız", + "ScheduledTaskStartedWithName": "{0} ıske qosyldy", + "ServerNameNeedsToBeRestarted": "{0} qaita ıske qosu qajet", + "Shows": "Körsetımder", + "Songs": "Äuender", + "StartupEmbyServerIsLoading": "Jellyfin Server jüktelude. Ärekettı köp ūzamai qaitalaŋyz.", "SubtitleDownloadFailureForItem": "Субтитрлер {0} үшін жүктеліп алынуы сәтсіз", - "SubtitleDownloadFailureFromForItem": "{1} úshin sýbtıtrlerdi {0} kózinen júktep alý sátsiz", - "Sync": "Úndestirý", - "System": "Júıe", - "TvShows": "TD-kórsetimder", - "User": "Paıdalanýshy", - "UserCreatedWithName": "Paıdalanýshy {0} jasalǵan", - "UserDeletedWithName": "Paıdalanýshy {0} joıylǵan", - "UserDownloadingItemWithValues": "{0} mynany júktep alýda: {1}", - "UserLockedOutWithName": "Paıdalanýshy {0} qursaýly", - "UserOfflineFromDevice": "{0} - {1} tarapynan ajyratylǵan", - "UserOnlineFromDevice": "{0} - {1} arqyly qosylǵan", - "UserPasswordChangedWithName": "Paıdalanýshy {0} úshin paról ózgertildi", - "UserPolicyUpdatedWithName": "Paıdalanýshy {0} úshin saıasattary jańartyldy", - "UserStartedPlayingItemWithValues": "{0} - {1} oınatýyn {2} bastady", - "UserStoppedPlayingItemWithValues": "{0} - {1} oınatýyn {2} toqtatty", - "ValueHasBeenAddedToLibrary": "{0} (tasyǵyshhanaǵa ústelindi)", - "ValueSpecialEpisodeName": "Arnaıy - {0}", - "VersionNumber": "Nusqasy {0}", - "Default": "Ádepki", - "TaskDownloadMissingSubtitles": "Joq sýbtıtrlerdi júktep alý", - "TaskRefreshChannels": "Arnalardy jańǵyrtý", - "TaskCleanTranscode": "Qaıta kodtaý katalogyn tazalaý", - "TaskUpdatePlugins": "Plagınderdi jańartý", - "TaskRefreshPeople": "Adamdardy jańartý", - "TaskCleanLogs": "Jurnal katalogyn tazalaý", - "TaskRefreshLibrary": "Tasyǵyshhanany skanerleý", - "TaskRefreshChapterImages": "Sahna keskinderin shyǵaryp alý", - "TaskCleanCache": "Kesh katalogyn tazalaý", - "TaskCleanActivityLog": "Áreket jurnalyn tazalaý", - "TasksChannelsCategory": "Internet-arnalar", + "SubtitleDownloadFailureFromForItem": "{1} üşın subtitrlerdı {0} közınen jüktep alu sätsız", + "Sync": "Ündestıru", + "System": "Jüie", + "TvShows": "TD-körsetımder", + "User": "Paidalanuşy", + "UserCreatedWithName": "Paidalanuşy {0} jasalğan", + "UserDeletedWithName": "Paidalanuşy {0} joiylğan", + "UserDownloadingItemWithValues": "{0} mynany jüktep aluda: {1}", + "UserLockedOutWithName": "Paidalanuşy {0} qūrsauly", + "UserOfflineFromDevice": "{0} - {1} tarapynan ajyratylğan", + "UserOnlineFromDevice": "{0} - {1} arqyly qosylğan", + "UserPasswordChangedWithName": "Paidalanuşy {0} üşın paröl özgertıldı", + "UserPolicyUpdatedWithName": "Paidalanuşy {0} üşın saiasattary jaŋartyldy", + "UserStartedPlayingItemWithValues": "{0} - {1} oinatuyn {2} bastady", + "UserStoppedPlayingItemWithValues": "{0} - {1} oinatuyn {2} toqtatty", + "ValueHasBeenAddedToLibrary": "{0} (tasyğyşhanağa üstelındı)", + "ValueSpecialEpisodeName": "Arnaiy - {0}", + "VersionNumber": "Nūsqasy {0}", + "Default": "Ädepkı", + "TaskDownloadMissingSubtitles": "Joq subtitrlerdı jüktep alu", + "TaskRefreshChannels": "Arnalardy jaŋğyrtu", + "TaskCleanTranscode": "Qaita kodtau katalogyn tazalau", + "TaskUpdatePlugins": "Plaginderdı jaŋartu", + "TaskRefreshPeople": "Adamdardy jaŋartu", + "TaskCleanLogs": "Jūrnal katalogyn tazalau", + "TaskRefreshLibrary": "Tasyğyşhanany skanerleu", + "TaskRefreshChapterImages": "Sahna keskınderın şyğaryp alu", + "TaskCleanCache": "Keş katalogyn tazalau", + "TaskCleanActivityLog": "Äreket jūrnalyn tazalau", + "TasksChannelsCategory": "İnternet-arnalar", "TasksApplicationCategory": "Qoldanba", - "TasksLibraryCategory": "Tasyǵyshhana", - "TasksMaintenanceCategory": "Qyzmet kórsetý", + "TasksLibraryCategory": "Tasyğyşhana", + "TasksMaintenanceCategory": "Qyzmet körsetu", "Undefined": "Anyqtalmady", - "Forced": "Májbúrli", - "TaskDownloadMissingSubtitlesDescription": "Metaderekter teńshelimi negіzіnde joq sýbtıtrlerdі Internetten іzdeıdі.", - "TaskRefreshChannelsDescription": "Internet-arnalar málimetterin jańǵyrtady.", - "TaskCleanTranscodeDescription": "Bіr kúnnen asqan qaıta kodtaý faıldaryn joıady.", - "TaskUpdatePluginsDescription": "Avtomatty túrde jańartýǵa teńshelgen plagınder úshin jańartýlardy júktep alady jáne ornatady.", - "TaskRefreshPeopleDescription": "Tasyǵyshhanadaǵy aktórler men rejısórler metaderekterіn jańartady.", - "TaskCleanLogsDescription": "{0} kúnnen asqan jurnal faıldaryn joıady.", - "TaskRefreshLibraryDescription": "Tasyǵyshhanadaǵy jańa faıldardy skanerleıdі jáne metaderekterdі jańartady.", - "TaskRefreshChapterImagesDescription": "Sahnalarǵa bólіngen beıneler úshіn nobaılar jasaıdy.", - "TaskCleanCacheDescription": "Júıede qajet emes keshtelgen faıldardy joıady.", - "TaskCleanActivityLogDescription": "Áreketter jurnalyndaǵy teńshelgen jasynan asqan jazbalary joıady." + "Forced": "Mäjbürlı", + "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımı negіzіnde joq subtitrlerdі İnternetten іzdeidі.", + "TaskRefreshChannelsDescription": "İnternet-arnalar mälımetterın jaŋğyrtady.", + "TaskCleanTranscodeDescription": "Bіr künnen asqan qaita kodtau faildaryn joiady.", + "TaskUpdatePluginsDescription": "Avtomatty türde jaŋartuğa teŋşelgen plaginder üşın jaŋartulardy jüktep alady jäne ornatady.", + "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterіn jaŋartady.", + "TaskCleanLogsDescription": "{0} künnen asqan jūrnal faildaryn joiady.", + "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaŋa faildardy skanerleidі jäne metaderekterdі jaŋartady.", + "TaskRefreshChapterImagesDescription": "Sahnalarğa bölіngen beineler üşіn nobailar jasaidy.", + "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.", + "TaskCleanActivityLogDescription": "Äreketter jūrnalyndağy teŋşelgen jasynan asqan jazbalary joiady." } From fa59d2afe3c9698297b9014e8d331939215b05dd Mon Sep 17 00:00:00 2001 From: WWWesten Date: Sun, 31 Jan 2021 13:23:08 +0000 Subject: [PATCH 1039/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index 03d30247a7..9119cf0af6 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -90,7 +90,7 @@ "UserStartedPlayingItemWithValues": "{0} - воспроизведение «{1}» на {2}", "UserStoppedPlayingItemWithValues": "{0} - воспроизведение остановлено «{1}» на {2}", "ValueHasBeenAddedToLibrary": "{0} (добавлено в медиатеку)", - "ValueSpecialEpisodeName": "Специальный эпизод - {0}", + "ValueSpecialEpisodeName": "Спецэпизод - {0}", "VersionNumber": "Версия {0}", "TaskDownloadMissingSubtitles": "Загрузка отсутствующих субтитров", "TaskRefreshChannels": "Обновление каналов", From edc7efe4d71f51b9f653a4405ee5780bd86181f9 Mon Sep 17 00:00:00 2001 From: Jacob Adlers Date: Sat, 30 Jan 2021 18:04:51 +0000 Subject: [PATCH 1040/1930] Translated using Weblate (Swedish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sv/ --- Emby.Server.Implementations/Localization/Core/sv.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json index 552710d703..345d41e9ee 100644 --- a/Emby.Server.Implementations/Localization/Core/sv.json +++ b/Emby.Server.Implementations/Localization/Core/sv.json @@ -117,5 +117,5 @@ "TaskCleanActivityLogDescription": "Radera aktivitets logg inlägg som är äldre än definerad ålder.", "TaskCleanActivityLog": "Rensa Aktivitets Logg", "Undefined": "odefinierad", - "Forced": "Tvinga" + "Forced": "Tvingad" } From 4bcf684b7241af10c15459cf83cb93e536471c8c Mon Sep 17 00:00:00 2001 From: Tomi Date: Sun, 31 Jan 2021 11:58:16 +0000 Subject: [PATCH 1041/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- Emby.Server.Implementations/Localization/Core/fi.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index 954759b5c0..b45bdcbad7 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -39,7 +39,7 @@ "Channels": "Kanavat", "CameraImageUploadedFrom": "Uusi kamerakuva on ladattu {0}", "Books": "Kirjat", - "AuthenticationSucceededWithUserName": "{0} todennus onnistui", + "AuthenticationSucceededWithUserName": "Käyttäjän {0} todennus onnistui", "Artists": "Artistit", "Application": "Sovellus", "AppDeviceValues": "Sovellus: {0}, Laite: {1}", From 8c640a1492ad3722778636222a6c29d0cce8cdc9 Mon Sep 17 00:00:00 2001 From: Troy <47042611+M0ssTee@users.noreply.github.com> Date: Mon, 1 Feb 2021 02:46:30 +0000 Subject: [PATCH 1042/1930] Replaced /d with [0-9], see issue #2923 --- Emby.Dlna/Profiles/SonyBravia2010Profile.cs | 4 ++-- Emby.Dlna/Profiles/SonyBravia2011Profile.cs | 4 ++-- Emby.Dlna/Profiles/SonyBravia2012Profile.cs | 4 ++-- Emby.Dlna/Profiles/SonyBravia2013Profile.cs | 4 ++-- Emby.Dlna/Profiles/SonyBravia2014Profile.cs | 4 ++-- Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml | 4 ++-- Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml | 4 ++-- Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml | 4 ++-- Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml | 4 ++-- Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml | 4 ++-- Emby.Naming/Common/NamingOptions.cs | 2 +- .../LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs | 2 +- MediaBrowser.MediaEncoding/Subtitles/AssParser.cs | 2 +- MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs | 2 +- 14 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs index 8ab4acd1be..9f0d82b8f8 100644 --- a/Emby.Dlna/Profiles/SonyBravia2010Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2010Profile.cs @@ -13,7 +13,7 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"KDL-\d{2}[EHLNPB]X\d[01]\d.*", + FriendlyName = @"KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*", Manufacturer = "Sony", Headers = new[] @@ -21,7 +21,7 @@ namespace Emby.Dlna.Profiles new HttpHeaderInfo { Name = "X-AV-Client-Info", - Value = @".*KDL-\d{2}[EHLNPB]X\d[01]\d.*", + Value = @".*KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].*", Match = HeaderMatchType.Regex } } diff --git a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs index 42d253394c..dfb91817ac 100644 --- a/Emby.Dlna/Profiles/SonyBravia2011Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2011Profile.cs @@ -13,7 +13,7 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"KDL-\d{2}([A-Z]X\d2\d|CX400).*", + FriendlyName = @"KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*", Manufacturer = "Sony", Headers = new[] @@ -21,7 +21,7 @@ namespace Emby.Dlna.Profiles new HttpHeaderInfo { Name = "X-AV-Client-Info", - Value = @".*KDL-\d{2}([A-Z]X\d2\d|CX400).*", + Value = @".*KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).*", Match = HeaderMatchType.Regex } } diff --git a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs index 0598e83422..d59ee38d74 100644 --- a/Emby.Dlna/Profiles/SonyBravia2012Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2012Profile.cs @@ -13,7 +13,7 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"KDL-\d{2}[A-Z]X\d5(\d|G).*", + FriendlyName = @"KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*", Manufacturer = "Sony", Headers = new[] @@ -21,7 +21,7 @@ namespace Emby.Dlna.Profiles new HttpHeaderInfo { Name = "X-AV-Client-Info", - Value = @".*KDL-\d{2}[A-Z]X\d5(\d|G).*", + Value = @".*KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).*", Match = HeaderMatchType.Regex } } diff --git a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs index 3d90a1e72d..73b0fd67eb 100644 --- a/Emby.Dlna/Profiles/SonyBravia2013Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2013Profile.cs @@ -13,7 +13,7 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"KDL-\d{2}[WR][5689]\d{2}A.*", + FriendlyName = @"KDL-[0-9]{2}[WR][5689][0-9]{2}A.*", Manufacturer = "Sony", Headers = new[] @@ -21,7 +21,7 @@ namespace Emby.Dlna.Profiles new HttpHeaderInfo { Name = "X-AV-Client-Info", - Value = @".*KDL-\d{2}[WR][5689]\d{2}A.*", + Value = @".*KDL-[0-9]{2}[WR][5689][0-9]{2}A.*", Match = HeaderMatchType.Regex } } diff --git a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs index 9188f73ef1..db8ee5750f 100644 --- a/Emby.Dlna/Profiles/SonyBravia2014Profile.cs +++ b/Emby.Dlna/Profiles/SonyBravia2014Profile.cs @@ -13,7 +13,7 @@ namespace Emby.Dlna.Profiles Identification = new DeviceIdentification { - FriendlyName = @"(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*", + FriendlyName = @"(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*", Manufacturer = "Sony", Headers = new[] @@ -21,7 +21,7 @@ namespace Emby.Dlna.Profiles new HttpHeaderInfo { Name = "X-AV-Client-Info", - Value = @".*(KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).*", + Value = @".*(KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).*", Match = HeaderMatchType.Regex } } diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml index f20e9fcb6f..1461db3117 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2010).xml @@ -3,10 +3,10 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Sony Bravia (2010) - KDL-\d{2}[EHLNPB]X\d[01]\d.* + KDL-[0-9]{2}[EHLNPB]X[0-9][01][0-9].* Sony - + Microsoft Corporation diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml index e516ff512d..7c5f2b1817 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2011).xml @@ -3,10 +3,10 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Sony Bravia (2011) - KDL-\d{2}([A-Z]X\d2\d|CX400).* + KDL-[0-9]{2}([A-Z]X[0-9]2[0-9]|CX400).* Sony - + Microsoft Corporation diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml index 88bd1c2f53..842a8fba33 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2012).xml @@ -3,10 +3,10 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Sony Bravia (2012) - KDL-\d{2}[A-Z]X\d5(\d|G).* + KDL-[0-9]{2}[A-Z]X[0-9]5([0-9]|G).* Sony - + Microsoft Corporation diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml index 3ca9893cdc..f1135c3fe3 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2013).xml @@ -3,10 +3,10 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Sony Bravia (2013) - KDL-\d{2}[WR][5689]\d{2}A.* + KDL-[0-9]{2}[WR][5689][0-9]{2}A.* Sony - + Microsoft Corporation diff --git a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml index 8804a75dfa..85c7868c66 100644 --- a/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml +++ b/Emby.Dlna/Profiles/Xml/Sony Bravia (2014).xml @@ -3,10 +3,10 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Sony Bravia (2014) - (KDL-\d{2}W[5-9]\d{2}B|KDL-\d{2}R480|XBR-\d{2}X[89]\d{2}B|KD-\d{2}[SX][89]\d{3}B).* + (KDL-[0-9]{2}W[5-9][0-9]{2}B|KDL-[0-9]{2}R480|XBR-[0-9]{2}X[89][0-9]{2}B|KD-[0-9]{2}[SX][89][0-9]{3}B).* Sony - + Microsoft Corporation diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 035d1b2280..365f1a9268 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -587,7 +587,7 @@ namespace Emby.Naming.Common AudioBookNamesExpressions = new[] { // Detect year usually in brackets after name Batman (2020) - @"^(?.+?)\s*\(\s*(?\d{4})\s*\)\s*$", + @"^(?.+?)\s*\(\s*(?[0-9]{4})\s*\)\s*$", @"^\s*(?[^ ].*?)\s*$" }; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index cdc8c6870a..615eff2c4e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -26,7 +26,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public LegacyHdHomerunChannelCommands(string url) { // parse url for channel and program - var regExp = new Regex(@"\/ch(\d+)-?(\d*)"); + var regExp = new Regex(@"\/ch([0-9]+)-?([[0-9]*)"); var match = regExp.Match(url); if (match.Success) { diff --git a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs index e0b7914fbe..3b46fdaf79 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles subEvent.Text = subEvent.Text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase); - subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase); + subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w[0-9]]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase); trackEvents.Add(subEvent); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index 4a87f87dc1..ccef7eeeae 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -79,7 +79,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles subEvent.Text = string.Join(ParserValues.NewLine, multiline); subEvent.Text = subEvent.Text.Replace(@"\N", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase); - subEvent.Text = Regex.Replace(subEvent.Text, @"\{(?:\\\d?[\w.-]+(?:\([^\)]*\)|&H?[0-9A-Fa-f]+&|))+\}", string.Empty, RegexOptions.IgnoreCase); + subEvent.Text = Regex.Replace(subEvent.Text, @"\{(?:\\[0-9]?[\w.-]+(?:\([^\)]*\)|&H?[0-9A-Fa-f]+&|))+\}", string.Empty, RegexOptions.IgnoreCase); subEvent.Text = Regex.Replace(subEvent.Text, "<", "<", RegexOptions.IgnoreCase); subEvent.Text = Regex.Replace(subEvent.Text, ">", ">", RegexOptions.IgnoreCase); subEvent.Text = Regex.Replace(subEvent.Text, "<(\\/?(font|b|u|i|s))((\\s+(\\w|\\w[\\w\\-]*\\w)(\\s*=\\s*(?:\\\".*?\\\"|'.*?'|[^'\\\">\\s]+))?)+\\s*|\\s*)(\\/?)>", "<$1$3$7>", RegexOptions.IgnoreCase); From 8d902478a0f44a90f947feaa32a889423bbaa40b Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 2 Feb 2021 07:14:11 -0700 Subject: [PATCH 1043/1930] Don't skip hidden files --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 5ebc9b61b5..c0e757543d 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -684,7 +684,9 @@ namespace Emby.Server.Implementations.IO return new EnumerationOptions { RecurseSubdirectories = recursive, - IgnoreInaccessible = true + IgnoreInaccessible = true, + // Don't skip any files. + AttributesToSkip = 0 }; } From 8f88d0d2cbcfb8ef0a79fbfa4173aabda9395366 Mon Sep 17 00:00:00 2001 From: M0ssTee <47042611+M0ssTee@users.noreply.github.com> Date: Wed, 3 Feb 2021 00:57:04 -0500 Subject: [PATCH 1044/1930] Update Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs Co-authored-by: Cody Robibero --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 615eff2c4e..f09338330f 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -26,7 +26,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun public LegacyHdHomerunChannelCommands(string url) { // parse url for channel and program - var regExp = new Regex(@"\/ch([0-9]+)-?([[0-9]*)"); + var regExp = new Regex(@"\/ch([0-9]+)-?([0-9]*)"); var match = regExp.Match(url); if (match.Success) { From f854a1ce1ff98224c231e5ad95101ad84128f65b Mon Sep 17 00:00:00 2001 From: David Date: Wed, 3 Feb 2021 11:34:21 +0100 Subject: [PATCH 1045/1930] Remove unused files --- .drone.yml | 30 ---------------- .../MediaBrowser.MediaEncoding.nuget.targets | 6 ---- MediaBrowser.sln.GhostDoc.xml | 35 ------------------- hooks/pre_build | 6 ---- 4 files changed, 77 deletions(-) delete mode 100644 .drone.yml delete mode 100644 MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets delete mode 100644 MediaBrowser.sln.GhostDoc.xml delete mode 100644 hooks/pre_build diff --git a/.drone.yml b/.drone.yml deleted file mode 100644 index 87c8e414e9..0000000000 --- a/.drone.yml +++ /dev/null @@ -1,30 +0,0 @@ ---- -kind: pipeline -name: build-debug - -steps: -- name: submodules - image: docker:git - commands: - - git submodule update --init --recursive - -- name: build - image: microsoft/dotnet:2-sdk - commands: - - dotnet publish "Jellyfin.Server" --configuration Debug --output "../ci/ci-debug" - ---- -kind: pipeline -name: build-release - -steps: -- name: submodules - image: docker:git - commands: - - git submodule update --init --recursive - -- name: build - image: microsoft/dotnet:2-sdk - commands: - - dotnet publish "Jellyfin.Server" --configuration Release --output "../ci/ci-release" - diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets deleted file mode 100644 index f793e09bcb..0000000000 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.nuget.targets +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/MediaBrowser.sln.GhostDoc.xml b/MediaBrowser.sln.GhostDoc.xml deleted file mode 100644 index eafee0bf55..0000000000 --- a/MediaBrowser.sln.GhostDoc.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - D:\Development\MediaBrowser\Help - - - true - false - false - false - - - true - false - false - false - true - false - - - true - - - - - - diff --git a/hooks/pre_build b/hooks/pre_build deleted file mode 100644 index 2fd6136c53..0000000000 --- a/hooks/pre_build +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -git submodule update --init --recursive - -# Register qemu-*-static for all supported processors except the -# current one, but also remove all registered binfmt_misc before -docker run --rm --privileged multiarch/qemu-user-static:register --reset From 8d12e6d6eb98ee5f14a0ca30cb8ca824aa051155 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 3 Feb 2021 10:42:17 +0000 Subject: [PATCH 1046/1930] Update BaseNfoSaver.cs --- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index c1f5bfb255..9f22e618ef 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -206,6 +206,7 @@ namespace MediaBrowser.XbmcMetadata.Savers // On Windows, saving the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { stream.CopyTo(filestream); From 256bb3ee989082ed10bfb0cb3f02481bf3292a43 Mon Sep 17 00:00:00 2001 From: M0ssTee <47042611+M0ssTee@users.noreply.github.com> Date: Thu, 4 Feb 2021 16:14:57 -0500 Subject: [PATCH 1047/1930] Update MediaBrowser.MediaEncoding/Subtitles/AssParser.cs Co-authored-by: Cody Robibero --- MediaBrowser.MediaEncoding/Subtitles/AssParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs index 3b46fdaf79..bb48bed270 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles subEvent.Text = subEvent.Text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase); - subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w[0-9]]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase); + subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w0-9]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase); trackEvents.Add(subEvent); } From 9eabad685e623fc61c30c4608979808e7c097c54 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Fri, 5 Feb 2021 08:57:54 +0000 Subject: [PATCH 1048/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- .../Localization/Core/kk.json | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index f4f6b442e0..a321e35d03 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -19,23 +19,23 @@ "HeaderContinueWatching": "Qaraudy jalğastyru", "HeaderFavoriteAlbums": "Taŋdauly älbomdar", "HeaderFavoriteArtists": "Taŋdauly oryndauşylar", - "HeaderFavoriteEpisodes": "Taŋdauly bölımder", + "HeaderFavoriteEpisodes": "Taŋdauly telebölımder", "HeaderFavoriteShows": "Taŋdauly körsetımder", "HeaderFavoriteSongs": "Taŋdauly äuender", "HeaderLiveTV": "Efir", "HeaderNextUp": "Kezektı", "HeaderRecordingGroups": "Jazba toptary", "HomeVideos": "Üilık beineler", - "Inherit": "Mūrağa ielenu", - "ItemAddedWithName": "{0} tasyğyşhanağa üsteldı", + "Inherit": "İelenu", + "ItemAddedWithName": "{0} tasyğyşhanağa üstelindı", "ItemRemovedWithName": "{0} tasyğyşhanadan alastaldy", - "LabelIpAddressValue": "İP-mekenjaiy: {0}", + "LabelIpAddressValue": "IP-mekenjaiy: {0}", "LabelRunningTimeValue": "Oinatu uaqyty: {0}", "Latest": "Eŋ keiıngı", "MessageApplicationUpdated": "Jellyfin Serverı jaŋartyldy", "MessageApplicationUpdatedTo": "Jellyfin Serverı {0} nūsqasyna jaŋartyldy", - "MessageNamedServerConfigurationUpdatedWithValue": "Server konfigurasuasynyŋ {0} bölımı jaŋartyldy", - "MessageServerConfigurationUpdated": "Server konfigurasiasy jaŋartyldy", + "MessageNamedServerConfigurationUpdatedWithValue": "Server teŋşelımderınıŋ {0} bölımı jaŋartyldy", + "MessageServerConfigurationUpdated": "Server teŋşelımderı jaŋartyldy", "MixedContent": "Aralas mazmūn", "Movies": "Filmder", "Music": "Muzyka", @@ -50,7 +50,7 @@ "NotificationOptionAudioPlaybackStopped": "Dybys oinatuy toqtatyldy", "NotificationOptionCameraImageUploaded": "Kameradan fotosuret jüktep salynğan", "NotificationOptionInstallationFailed": "Ornatu sätsızdıgı", - "NotificationOptionNewLibraryContent": "Jaŋa mazmūn üstelgen", + "NotificationOptionNewLibraryContent": "Jaŋa mazmūn üstelıngen", "NotificationOptionPluginError": "Plagin sätsızdıgı", "NotificationOptionPluginInstalled": "Plagin ornatyldy", "NotificationOptionPluginUninstalled": "Plagin ornatuy boldyrylmady", @@ -81,15 +81,15 @@ "User": "Paidalanuşy", "UserCreatedWithName": "Paidalanuşy {0} jasalğan", "UserDeletedWithName": "Paidalanuşy {0} joiylğan", - "UserDownloadingItemWithValues": "{0} mynany jüktep aluda: {1}", - "UserLockedOutWithName": "Paidalanuşy {0} qūrsauly", - "UserOfflineFromDevice": "{0} - {1} tarapynan ajyratylğan", - "UserOnlineFromDevice": "{0} - {1} arqyly qosylğan", + "UserDownloadingItemWithValues": "{0} — {1} jüktep aluda", + "UserLockedOutWithName": "Paidalanuşy {0} qūrsaulanğan", + "UserOfflineFromDevice": "{0} — {1} tarapynan ajyratyldy", + "UserOnlineFromDevice": "{0} — {1} tarapynan qosyldy", "UserPasswordChangedWithName": "Paidalanuşy {0} üşın paröl özgertıldı", "UserPolicyUpdatedWithName": "Paidalanuşy {0} üşın saiasattary jaŋartyldy", - "UserStartedPlayingItemWithValues": "{0} - {1} oinatuyn {2} bastady", - "UserStoppedPlayingItemWithValues": "{0} - {1} oinatuyn {2} toqtatty", - "ValueHasBeenAddedToLibrary": "{0} (tasyğyşhanağa üstelındı)", + "UserStartedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuda", + "UserStoppedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuyn toqtatty", + "ValueHasBeenAddedToLibrary": "{0} tasyğyşhanağa üstelındı", "ValueSpecialEpisodeName": "Arnaiy - {0}", "VersionNumber": "Nūsqasy {0}", "Default": "Ädepkı", @@ -97,26 +97,26 @@ "TaskRefreshChannels": "Arnalardy jaŋğyrtu", "TaskCleanTranscode": "Qaita kodtau katalogyn tazalau", "TaskUpdatePlugins": "Plaginderdı jaŋartu", - "TaskRefreshPeople": "Adamdardy jaŋartu", + "TaskRefreshPeople": "Adamdardy jaŋğyrtu", "TaskCleanLogs": "Jūrnal katalogyn tazalau", "TaskRefreshLibrary": "Tasyğyşhanany skanerleu", - "TaskRefreshChapterImages": "Sahna keskınderın şyğaryp alu", + "TaskRefreshChapterImages": "Sahna suretterın şyğaryp alu", "TaskCleanCache": "Keş katalogyn tazalau", "TaskCleanActivityLog": "Äreket jūrnalyn tazalau", - "TasksChannelsCategory": "İnternet-arnalar", + "TasksChannelsCategory": "Internet-arnalar", "TasksApplicationCategory": "Qoldanba", "TasksLibraryCategory": "Tasyğyşhana", "TasksMaintenanceCategory": "Qyzmet körsetu", - "Undefined": "Anyqtalmady", + "Undefined": "Anyqtalmağan", "Forced": "Mäjbürlı", - "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımı negіzіnde joq subtitrlerdі İnternetten іzdeidі.", - "TaskRefreshChannelsDescription": "İnternet-arnalar mälımetterın jaŋğyrtady.", + "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımderı negızınde joq subtitrlerdı Internetten ızdeidı.", + "TaskRefreshChannelsDescription": "Internet-arnalar mälımetterın jaŋğyrtady.", "TaskCleanTranscodeDescription": "Bіr künnen asqan qaita kodtau faildaryn joiady.", "TaskUpdatePluginsDescription": "Avtomatty türde jaŋartuğa teŋşelgen plaginder üşın jaŋartulardy jüktep alady jäne ornatady.", - "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterіn jaŋartady.", + "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterın jaŋartady.", "TaskCleanLogsDescription": "{0} künnen asqan jūrnal faildaryn joiady.", - "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaŋa faildardy skanerleidі jäne metaderekterdі jaŋartady.", - "TaskRefreshChapterImagesDescription": "Sahnalarğa bölіngen beineler üşіn nobailar jasaidy.", + "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaŋa faildardy skanerleidі jäne metaderekterdı jaŋğyrtady.", + "TaskRefreshChapterImagesDescription": "Sahnalary bar beineler üşіn nobailar jasaidy.", "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.", - "TaskCleanActivityLogDescription": "Äreketter jūrnalyndağy teŋşelgen jasynan asqan jazbalary joiady." + "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teŋşelgen jasynan asqan jazbalary joiady." } From f8283d8c207cd816dc16768fe0cb454e1732a963 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Fri, 5 Feb 2021 09:49:42 +0000 Subject: [PATCH 1049/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index 9119cf0af6..46b47cf4a8 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -89,7 +89,7 @@ "UserPolicyUpdatedWithName": "Политики пользователя {0} были обновлены", "UserStartedPlayingItemWithValues": "{0} - воспроизведение «{1}» на {2}", "UserStoppedPlayingItemWithValues": "{0} - воспроизведение остановлено «{1}» на {2}", - "ValueHasBeenAddedToLibrary": "{0} (добавлено в медиатеку)", + "ValueHasBeenAddedToLibrary": "{0} добавлено в медиатеку", "ValueSpecialEpisodeName": "Спецэпизод - {0}", "VersionNumber": "Версия {0}", "TaskDownloadMissingSubtitles": "Загрузка отсутствующих субтитров", From b646787ab6cae179e2e31f05bbdfd9201c7d1a69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20V=C3=A1radi?= Date: Fri, 5 Feb 2021 20:02:47 +0100 Subject: [PATCH 1050/1930] Get IndexNumberEnd from nfo --- .../Parsers/EpisodeNfoParser.cs | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index 81774b8735..5922b4f44f 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -35,14 +35,17 @@ namespace MediaBrowser.XbmcMetadata.Parsers { item.ResetPeople(); - var xml = streamReader.ReadToEnd(); + var xmlFile = streamReader.ReadToEnd(); var srch = ""; - var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase); + var index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase); + + var xml = xmlFile; if (index != -1) { - xml = xml.Substring(0, index + srch.Length); + xml = xmlFile.Substring(0, index + srch.Length); + xmlFile = xmlFile.Substring(index + srch.Length); } // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions @@ -73,6 +76,38 @@ namespace MediaBrowser.XbmcMetadata.Parsers catch (XmlException) { } + + while ((index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase)) != -1) + { + xml = xmlFile.Substring(0, index + srch.Length); + xmlFile = xmlFile.Substring(index + srch.Length); + + // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions + try + { + using (var stringReader = new StringReader(xml)) + using (var reader = XmlReader.Create(stringReader, settings)) + { + reader.MoveToContent(); + + if (reader.ReadToDescendant("episode")) + { + var number = reader.ReadElementContentAsString(); + + if (!string.IsNullOrWhiteSpace(number)) + { + if (int.TryParse(number, out var num)) + { + item.Item.IndexNumberEnd = Math.Max(num, item.Item.IndexNumberEnd ?? num); + } + } + } + } + } + catch (XmlException) + { + } + } } } From 09b9fa3ce12e8837605c00f7b8f963e649c7ecc7 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Tue, 26 Jan 2021 03:45:56 +0800 Subject: [PATCH 1051/1930] add vpp tonemapping for vaapi --- .../MediaEncoding/EncodingHelper.cs | 92 +++++++++++++------ .../Configuration/EncodingOptions.cs | 3 + 2 files changed, 69 insertions(+), 26 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 3b70ed9ddc..1ba02e276e 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -127,6 +127,25 @@ namespace MediaBrowser.Controller.MediaEncoding && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase); } + private bool IsVppTonemappingSupported(EncodingJobInfo state, EncodingOptions options) + { + var videoStream = state.VideoStream; + var codec = videoStream.Codec; + if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)) + { + // Limited to HEVC for now since the filter doesn't accept master data from VP9. + return IsColorDepth10(state) + && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) + && _mediaEncoder.SupportsHwaccel("vaapi") + && options.EnableVppTonemapping + && !string.IsNullOrEmpty(videoStream.ColorTransfer) + && videoStream.ColorTransfer.Equals("smpte2084", StringComparison.OrdinalIgnoreCase); + } + + // Vpp tonemapping may come to QSV in the future. + return false; + } + /// /// Gets the name of the output video codec. /// @@ -469,6 +488,7 @@ namespace MediaBrowser.Controller.MediaEncoding var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); var isTonemappingSupported = IsTonemappingSupported(state, encodingOptions); + var isVppTonemappingSupported = IsVppTonemappingSupported(state, encodingOptions); if (!IsCopyCodec(outputVideoCodec)) { @@ -478,7 +498,7 @@ namespace MediaBrowser.Controller.MediaEncoding { if (isVaapiDecoder) { - if (isTonemappingSupported) + if (isTonemappingSupported && !isVppTonemappingSupported) { arg.Append("-init_hw_device vaapi=va:") .Append(encodingOptions.VaapiDevice) @@ -938,7 +958,7 @@ namespace MediaBrowser.Controller.MediaEncoding var videoStream = state.VideoStream; var isColorDepth10 = IsColorDepth10(state); var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty; - var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase); if (!isNvdecDecoder) { @@ -1932,14 +1952,15 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; - var isNvencEncoder = outputVideoCodec.IndexOf("nvenc", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase); + var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase); var isTonemappingSupported = IsTonemappingSupported(state, options); + var isVppTonemappingSupported = IsVppTonemappingSupported(state, options); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); // Tonemapping and burn-in graphical subtitles requires overlay_vaapi. // But it's still in ffmpeg mailing list. Disable it for now. - if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + if (isTonemappingSupported && isTonemappingSupportedOnVaapi && !isVppTonemappingSupported) { return GetOutputSizeParam(state, options, outputVideoCodec); } @@ -2123,17 +2144,24 @@ namespace MediaBrowser.Controller.MediaEncoding || state.DeInterlace("h265", true) || state.DeInterlace("hevc", true); + var isVaapiDecoder = videoDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase); + var isVaapiH264Encoder = videoEncoder.Contains("h264_vaapi", StringComparison.OrdinalIgnoreCase); + var isVaapiHevcEncoder = videoEncoder.Contains("hevc_vaapi", StringComparison.OrdinalIgnoreCase); var isTonemappingSupported = IsTonemappingSupported(state, options); - var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && !qsv_or_vaapi; + var isVppTonemappingSupported = IsVppTonemappingSupported(state, options); + var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); - var outputPixFmt = string.Empty; - if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + var outputPixFmt = "format=nv12"; + if (isTonemappingSupportedOnVaapi) { - outputPixFmt = "format=p010:out_range=limited"; - } - else - { - outputPixFmt = "format=nv12"; + if (isVppTonemappingSupported) + { + outputPixFmt = "format=p010"; + } + else if (isTonemappingSupported) + { + outputPixFmt = "format=p010:out_range=limited"; + } } if (!videoWidth.HasValue @@ -2164,7 +2192,7 @@ namespace MediaBrowser.Controller.MediaEncoding (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty)); } } - else if ((videoDecoder ?? string.Empty).IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1 + else if ((videoDecoder ?? string.Empty).Contains("cuda", StringComparison.OrdinalIgnoreCase) && width.HasValue && height.HasValue) { @@ -2418,15 +2446,16 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1; var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; - var isNvencEncoder = outputVideoCodec.IndexOf("nvenc", StringComparison.OrdinalIgnoreCase) != -1; - var isCuvidH264Decoder = videoDecoder.IndexOf("h264_cuvid", StringComparison.OrdinalIgnoreCase) != -1; - var isCuvidHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase); + var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase); + var isCuvidH264Decoder = videoDecoder.Contains("h264_cuvid", StringComparison.OrdinalIgnoreCase); + var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase); var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1; var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1; var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isColorDepth10 = IsColorDepth10(state); var isTonemappingSupported = IsTonemappingSupported(state, options); + var isVppTonemappingSupported = IsVppTonemappingSupported(state, options); var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder); var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); @@ -2444,7 +2473,8 @@ namespace MediaBrowser.Controller.MediaEncoding var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true); var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true); - if (isTonemappingSupportedOnNvenc || isTonemappingSupportedOnAmf || isTonemappingSupportedOnVaapi) + // Add OpenCL tonemapping filter for NVENC/AMF/VAAPI. + if (isTonemappingSupportedOnNvenc || isTonemappingSupportedOnAmf || (isTonemappingSupportedOnVaapi && !isVppTonemappingSupported)) { // Currently only with the use of NVENC decoder can we get a decent performance. // Currently only the HEVC/H265 format is supported with NVDEC decoder. @@ -2490,7 +2520,7 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add( string.Format( CultureInfo.InvariantCulture, - "yadif={0}:-1:0", + "yadif_cuda={0}:-1:0", doubleRateDeinterlace ? "1" : "0")); } @@ -2563,7 +2593,10 @@ namespace MediaBrowser.Controller.MediaEncoding } // When the input may or may not be hardware VAAPI decodable. - if ((isVaapiH264Encoder || isVaapiHevcEncoder) && !isTonemappingSupported && !isTonemappingSupportedOnVaapi) + if ((isVaapiH264Encoder || isVaapiHevcEncoder) + && !isTonemappingSupported + && !isVppTonemappingSupported + && !isTonemappingSupportedOnVaapi) { filters.Add("format=nv12|vaapi"); filters.Add("hwupload"); @@ -2668,21 +2701,28 @@ namespace MediaBrowser.Controller.MediaEncoding request.MaxHeight)); } - // Another case is using Nvenc decoder. + // Add Vpp tonemapping filter for VAAPI. + // Full hardware based video post processing, faster than OpenCL but lacks fine tuning options. + if (isTonemappingSupportedOnVaapi && isVppTonemappingSupported) + { + filters.Add("tonemap_vaapi=format=nv12:transfer=bt709:matrix=bt709:primaries=bt709"); + } + + // Another case is when using Nvenc decoder. if (isNvdecDecoder && !isTonemappingSupported) { - var codec = videoStream.Codec.ToLowerInvariant(); + var codec = videoStream.Codec; // Assert 10-bit hardware decodable if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))) { - // Download data from GPU to CPU as p010le format. + // Download data from GPU to CPU as p010 format. filters.Add("hwdownload"); filters.Add("format=p010"); - // cuda lacks of a pixel format converter. + // Cuda lacks of a pixel format converter. if (isNvencEncoder) { isHwuploadCudaRequired = true; @@ -2710,7 +2750,7 @@ namespace MediaBrowser.Controller.MediaEncoding { // Convert hw context from ocl to va. // For tonemapping and text subs burn-in. - if (isTonemappingSupported && isTonemappingSupportedOnVaapi) + if (isTonemappingSupported && isTonemappingSupportedOnVaapi && !isVppTonemappingSupported) { filters.Add("scale_vaapi"); } diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index 5cd8744eda..da467e133f 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -39,6 +39,8 @@ namespace MediaBrowser.Model.Configuration public bool EnableTonemapping { get; set; } + public bool EnableVppTonemapping { get; set; } + public string TonemappingAlgorithm { get; set; } public string TonemappingRange { get; set; } @@ -90,6 +92,7 @@ namespace MediaBrowser.Model.Configuration // The left side of the dot is the platform number, and the right side is the device number on the platform. OpenclDevice = "0.0"; EnableTonemapping = false; + EnableVppTonemapping = false; TonemappingAlgorithm = "hable"; TonemappingRange = "auto"; TonemappingDesat = 0; From b0e0e19468eeadcff0c3a16b47607ce2620227af Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Wed, 27 Jan 2021 03:20:53 +0800 Subject: [PATCH 1052/1930] add cuda format converter --- .../MediaEncoding/EncodingHelper.cs | 131 +++++++++++------- .../MediaEncoding/IMediaEncoder.cs | 8 ++ .../Encoder/EncoderValidator.cs | 32 +++++ .../Encoder/MediaEncoder.cs | 11 ++ 4 files changed, 133 insertions(+), 49 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1ba02e276e..1f60f3bcc4 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -112,9 +112,11 @@ namespace MediaBrowser.Controller.MediaEncoding return _mediaEncoder.SupportsHwaccel("vaapi"); } - private bool IsCudaSupported(EncodingJobInfo state) + private bool IsCudaSupported() { - return _mediaEncoder.SupportsHwaccel("cuda"); + return _mediaEncoder.SupportsHwaccel("cuda") + && _mediaEncoder.SupportsFilter("scale_cuda", null) + && _mediaEncoder.SupportsFilter("yadif_cuda", null); } private bool IsTonemappingSupported(EncodingJobInfo state, EncodingOptions options) @@ -123,8 +125,7 @@ namespace MediaBrowser.Controller.MediaEncoding return IsColorDepth10(state) && _mediaEncoder.SupportsHwaccel("opencl") && options.EnableTonemapping - && !string.IsNullOrEmpty(videoStream.VideoRange) - && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase); + && string.Equals(videoStream.VideoRange, "HDR", StringComparison.OrdinalIgnoreCase); } private bool IsVppTonemappingSupported(EncodingJobInfo state, EncodingOptions options) @@ -138,8 +139,7 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) && _mediaEncoder.SupportsHwaccel("vaapi") && options.EnableVppTonemapping - && !string.IsNullOrEmpty(videoStream.ColorTransfer) - && videoStream.ColorTransfer.Equals("smpte2084", StringComparison.OrdinalIgnoreCase); + && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase); } // Vpp tonemapping may come to QSV in the future. @@ -482,8 +482,8 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1; var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1; - var isNvdecDecoder = videoDecoder.IndexOf("cuda", StringComparison.OrdinalIgnoreCase) != -1; - var isCuvidHevcDecoder = videoDecoder.IndexOf("hevc_cuvid", StringComparison.OrdinalIgnoreCase) != -1; + var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase); + var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase); var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); @@ -560,17 +560,17 @@ namespace MediaBrowser.Controller.MediaEncoding } if (state.IsVideoRequest - && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)) + && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) + && isNvdecDecoder) { - if (isNvdecDecoder) - { - arg.Append("-hwaccel_output_format cuda "); - } + arg.Append("-hwaccel_output_format cuda "); } if (state.IsVideoRequest - && (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder)) - || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder))) + && ((string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) + && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder)) + || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) + && (isD3d11vaDecoder || isSwDecoder)))) { if (isTonemappingSupported) { @@ -2051,8 +2051,8 @@ namespace MediaBrowser.Controller.MediaEncoding else if (isNvdecDecoder && isNvencEncoder) { retStr = !outputSizeParam.IsEmpty - ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=yuv420p|nv12,hwupload_cuda\"" - : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=yuv420p|nv12,hwupload_cuda\""; + ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=nv12|yuv420p,hwupload_cuda\"" + : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=nv12|yuv420p,hwupload_cuda\""; } return string.Format( @@ -2152,16 +2152,9 @@ namespace MediaBrowser.Controller.MediaEncoding var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); var outputPixFmt = "format=nv12"; - if (isTonemappingSupportedOnVaapi) + if (isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported)) { - if (isVppTonemappingSupported) - { - outputPixFmt = "format=p010"; - } - else if (isTonemappingSupported) - { - outputPixFmt = "format=p010:out_range=limited"; - } + outputPixFmt = "format=p010"; } if (!videoWidth.HasValue @@ -2181,7 +2174,9 @@ namespace MediaBrowser.Controller.MediaEncoding ":" + outputPixFmt, (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty)); } - else + + // Assert 10-bit is P010 so as we can avoid the extra scaler to get a bit more fps on high res HDR videos. + else if (!(isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported))) { filters.Add( string.Format( @@ -2199,6 +2194,20 @@ namespace MediaBrowser.Controller.MediaEncoding var outputWidth = width.Value; var outputHeight = height.Value; + var isTonemappingSupported = IsTonemappingSupported(state, options); + var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase); + var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilter("scale_cuda", "Output format (default \"same\")"); + + var outputPixFmt = string.Empty; + if (isCudaFormatConversionSupported) + { + outputPixFmt = "format=nv12"; + if (isTonemappingSupported && isTonemappingSupportedOnNvenc) + { + outputPixFmt = "format=p010"; + } + } + if (!videoWidth.HasValue || outputWidth != videoWidth.Value || !videoHeight.HasValue @@ -2207,9 +2216,18 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add( string.Format( CultureInfo.InvariantCulture, - "scale_cuda=w={0}:h={1}", + "scale_cuda=w={0}:h={1}{2}", outputWidth, - outputHeight)); + outputHeight, + isCudaFormatConversionSupported ? (":" + outputPixFmt) : string.Empty)); + } + else if (isCudaFormatConversionSupported) + { + filters.Add( + string.Format( + CultureInfo.InvariantCulture, + "scale_cuda={0}", + outputPixFmt)); } } else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1 @@ -2594,9 +2612,7 @@ namespace MediaBrowser.Controller.MediaEncoding // When the input may or may not be hardware VAAPI decodable. if ((isVaapiH264Encoder || isVaapiHevcEncoder) - && !isTonemappingSupported - && !isVppTonemappingSupported - && !isTonemappingSupportedOnVaapi) + && !(isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported))) { filters.Add("format=nv12|vaapi"); filters.Add("hwupload"); @@ -2611,7 +2627,7 @@ namespace MediaBrowser.Controller.MediaEncoding // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first. else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)) { - var codec = videoStream.Codec.ToLowerInvariant(); + var codec = videoStream.Codec; // Assert 10-bit hardware VAAPI decodable if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) @@ -2712,21 +2728,38 @@ namespace MediaBrowser.Controller.MediaEncoding if (isNvdecDecoder && !isTonemappingSupported) { var codec = videoStream.Codec; + var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilter("scale_cuda", "Output format (default \"same\")"); // Assert 10-bit hardware decodable if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))) { - // Download data from GPU to CPU as p010 format. - filters.Add("hwdownload"); - filters.Add("format=p010"); - - // Cuda lacks of a pixel format converter. - if (isNvencEncoder) + if (isCudaFormatConversionSupported) { - isHwuploadCudaRequired = true; - filters.Add("format=yuv420p"); + if (isLibX264Encoder || isLibX265Encoder || hasSubs) + { + if (isNvencEncoder) + { + isHwuploadCudaRequired = true; + } + + filters.Add("hwdownload"); + filters.Add("format=nv12"); + } + } + else + { + // Download data from GPU to CPU as p010 format. + filters.Add("hwdownload"); + filters.Add("format=p010"); + + // Cuda lacks of a pixel format converter. + if (isNvencEncoder) + { + isHwuploadCudaRequired = true; + filters.Add("format=yuv420p"); + } } } @@ -3285,32 +3318,32 @@ namespace MediaBrowser.Controller.MediaEncoding { case "avc": case "h264": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "h264", isColorDepth10) : GetHwDecoderName(encodingOptions, "h264_cuvid", "h264", isColorDepth10); case "hevc": case "h265": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10) : GetHwDecoderName(encodingOptions, "hevc_cuvid", "hevc", isColorDepth10); case "mpeg2video": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10) : GetHwDecoderName(encodingOptions, "mpeg2_cuvid", "mpeg2video", isColorDepth10); case "vc1": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10) : GetHwDecoderName(encodingOptions, "vc1_cuvid", "vc1", isColorDepth10); case "mpeg4": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10) : GetHwDecoderName(encodingOptions, "mpeg4_cuvid", "mpeg4", isColorDepth10); case "vp8": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10) : GetHwDecoderName(encodingOptions, "vp8_cuvid", "vp8", isColorDepth10); case "vp9": - return encodingOptions.EnableEnhancedNvdecDecoder + return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported() ? GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10) : GetHwDecoderName(encodingOptions, "vp9_cuvid", "vp9", isColorDepth10); } @@ -3500,7 +3533,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)) { - if (IsCudaSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase)) + if (options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase)) { return "-hwaccel cuda"; } diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 34fe895cc4..0bfa7d3c2b 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -50,6 +50,14 @@ namespace MediaBrowser.Controller.MediaEncoding /// true if XXXX, false otherwise. bool SupportsHwaccel(string hwaccel); + /// + /// Whether given filter is supported. + /// + /// The filter. + /// The option. + /// true if XXXX, false otherwise. + bool SupportsFilter(string filter, string option); + /// /// Extracts the audio image. /// diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 92f16ab95c..9e24176033 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -296,6 +296,38 @@ namespace MediaBrowser.MediaEncoding.Encoder return found; } + public bool CheckFilter(string filter, string option) + { + if (string.IsNullOrEmpty(filter)) + { + return false; + } + + string output = null; + try + { + output = GetProcessOutput(_encoderPath, "-h filter=" + filter); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error detecting the given filter"); + } + + if (output.Contains("Filter " + filter, StringComparison.Ordinal)) + { + if (string.IsNullOrEmpty(option)) + { + return true; + } + + return output.Contains(option, StringComparison.Ordinal); + } + + _logger.LogWarning("Filter: {Name} with option {Option} is not available", filter, option); + + return false; + } + private IEnumerable GetCodecs(Codec codec) { string codecstr = codec == Codec.Encoder ? "encoders" : "decoders"; diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index fbd08a97c7..c0b6cf28bb 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -295,6 +295,17 @@ namespace MediaBrowser.MediaEncoding.Encoder return _hwaccels.Contains(hwaccel, StringComparer.OrdinalIgnoreCase); } + public bool SupportsFilter(string filter, string option) + { + if (_ffmpegPath != null) + { + var validator = new EncoderValidator(_logger, _ffmpegPath); + return validator.CheckFilter(filter, option); + } + + return false; + } + public bool CanEncodeToAudioCodec(string codec) { if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase)) From 305206816163515907f9a20f26d1c7a06f9132d1 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Fri, 29 Jan 2021 17:53:42 +0800 Subject: [PATCH 1053/1930] hybird vpp tonemapping for QSV on Linux --- .../MediaEncoding/EncodingHelper.cs | 113 ++++++++++++++---- .../MediaEncoding/IMediaEncoder.cs | 2 +- 2 files changed, 94 insertions(+), 21 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1f60f3bcc4..cbba1a6345 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -142,7 +142,20 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase); } - // Vpp tonemapping may come to QSV in the future. + // Hybrid VPP tonemapping for QSV with VAAPI + var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + if (isLinux && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)) + { + // Limited to HEVC for now since the filter doesn't accept master data from VP9. + return IsColorDepth10(state) + && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) + && _mediaEncoder.SupportsHwaccel("vaapi") + && _mediaEncoder.SupportsHwaccel("qsv") + && options.EnableVppTonemapping + && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase); + } + + // Native VPP tonemapping may come to QSV in the future. return false; } @@ -552,10 +565,20 @@ namespace MediaBrowser.Controller.MediaEncoding } // While using SW decoder - else + else if (isSwDecoder) { arg.Append("-init_hw_device qsv=hw -filter_hw_device hw "); } + + // Hybrid VPP tonemapping with VAAPI + else if (isVaapiDecoder && isVppTonemappingSupported) + { + arg.Append("-init_hw_device vaapi=va:") + .Append(encodingOptions.VaapiDevice) + .Append(' ') + .Append("-init_hw_device qsv@va ") + .Append("-hwaccel_output_format vaapi "); + } } } @@ -1952,15 +1975,18 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1; var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1; + var isQsvH264Encoder = outputVideoCodec.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase); + var isQsvHevcEncoder = outputVideoCodec.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase); var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase); var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase); var isTonemappingSupported = IsTonemappingSupported(state, options); var isVppTonemappingSupported = IsVppTonemappingSupported(state, options); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder); // Tonemapping and burn-in graphical subtitles requires overlay_vaapi. // But it's still in ffmpeg mailing list. Disable it for now. - if (isTonemappingSupported && isTonemappingSupportedOnVaapi && !isVppTonemappingSupported) + if (isTonemappingSupportedOnVaapi && isTonemappingSupported && !isVppTonemappingSupported) { return GetOutputSizeParam(state, options, outputVideoCodec); } @@ -1983,7 +2009,8 @@ namespace MediaBrowser.Controller.MediaEncoding height.Value); } - if (!string.IsNullOrEmpty(videoSizeParam)) + if (!string.IsNullOrEmpty(videoSizeParam) + && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { // For QSV, feed it into hardware encoder now if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) @@ -2017,7 +2044,9 @@ namespace MediaBrowser.Controller.MediaEncoding [sub]: SW scaling subtitle to FixedOutputSize [base][sub]: SW overlay */ - retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\""; + retStr = !outputSizeParam.IsEmpty + ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"" + : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwdownload[base];[base][sub]overlay,format=nv12,hwupload\""; } // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first @@ -2030,7 +2059,9 @@ namespace MediaBrowser.Controller.MediaEncoding [sub]: SW scaling subtitle to FixedOutputSize [base][sub]: SW overlay */ - retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\""; + retStr = !outputSizeParam.IsEmpty + ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"" + : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""; } else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) @@ -2041,7 +2072,11 @@ namespace MediaBrowser.Controller.MediaEncoding with fixed frame size. Currently only supports linux. */ - if (isLinux) + if (isTonemappingSupportedOnQsv && isVppTonemappingSupported) + { + retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload,format=nv12[base];[base][sub]overlay\""; + } + else if (isLinux) { retStr = !outputSizeParam.IsEmpty ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_qsv\"" @@ -2147,16 +2182,27 @@ namespace MediaBrowser.Controller.MediaEncoding var isVaapiDecoder = videoDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase); var isVaapiH264Encoder = videoEncoder.Contains("h264_vaapi", StringComparison.OrdinalIgnoreCase); var isVaapiHevcEncoder = videoEncoder.Contains("hevc_vaapi", StringComparison.OrdinalIgnoreCase); + var isQsvH264Encoder = videoEncoder.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase); + var isQsvHevcEncoder = videoEncoder.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase); var isTonemappingSupported = IsTonemappingSupported(state, options); var isVppTonemappingSupported = IsVppTonemappingSupported(state, options); - var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)&& isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder); + var isP010PixFmtRequired = (isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported)) + || (isTonemappingSupportedOnQsv && isVppTonemappingSupported); + var outputPixFmt = "format=nv12"; - if (isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported)) + if (isP010PixFmtRequired) { outputPixFmt = "format=p010"; } + if (isTonemappingSupportedOnQsv && isVppTonemappingSupported) + { + qsv_or_vaapi = false; + } + if (!videoWidth.HasValue || outputWidth != videoWidth.Value || !videoHeight.HasValue @@ -2176,7 +2222,7 @@ namespace MediaBrowser.Controller.MediaEncoding } // Assert 10-bit is P010 so as we can avoid the extra scaler to get a bit more fps on high res HDR videos. - else if (!(isTonemappingSupportedOnVaapi && (isTonemappingSupported || isVppTonemappingSupported))) + else if (!isP010PixFmtRequired) { filters.Add( string.Format( @@ -2477,6 +2523,7 @@ namespace MediaBrowser.Controller.MediaEncoding var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder); var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder); var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder); + var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder); var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; @@ -2619,13 +2666,15 @@ namespace MediaBrowser.Controller.MediaEncoding } // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context. - else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)) + else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder) + && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { filters.Add("hwupload=extra_hw_frames=64"); } // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first. - else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)) + else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder) + && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { var codec = videoStream.Codec; @@ -2654,7 +2703,8 @@ namespace MediaBrowser.Controller.MediaEncoding // Add hardware deinterlace filter before scaling filter. if (isDeinterlaceH264 || isDeinterlaceHevc) { - if (isVaapiEncoder) + if (isVaapiEncoder + || (isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { filters.Add( string.Format( @@ -2717,9 +2767,10 @@ namespace MediaBrowser.Controller.MediaEncoding request.MaxHeight)); } - // Add Vpp tonemapping filter for VAAPI. + // Add VPP tonemapping filter for VAAPI. // Full hardware based video post processing, faster than OpenCL but lacks fine tuning options. - if (isTonemappingSupportedOnVaapi && isVppTonemappingSupported) + if ((isTonemappingSupportedOnVaapi || isTonemappingSupportedOnQsv) + && isVppTonemappingSupported) { filters.Add("tonemap_vaapi=format=nv12:transfer=bt709:matrix=bt709:primaries=bt709"); } @@ -2777,13 +2828,15 @@ namespace MediaBrowser.Controller.MediaEncoding } // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642) - if (isVaapiH264Encoder || isVaapiHevcEncoder) + if (isVaapiH264Encoder + || isVaapiHevcEncoder + || (isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { if (hasTextSubs) { // Convert hw context from ocl to va. // For tonemapping and text subs burn-in. - if (isTonemappingSupported && isTonemappingSupportedOnVaapi && !isVppTonemappingSupported) + if (isTonemappingSupportedOnVaapi && isTonemappingSupported && !isVppTonemappingSupported) { filters.Add("scale_vaapi"); } @@ -2794,8 +2847,6 @@ namespace MediaBrowser.Controller.MediaEncoding } } - var output = string.Empty; - if (hasTextSubs) { var subParam = GetTextSubtitleParam(state); @@ -2809,17 +2860,29 @@ namespace MediaBrowser.Controller.MediaEncoding filters.Add("hwmap"); } + if (isTonemappingSupportedOnQsv && isVppTonemappingSupported) + { + filters.Add("hwmap,format=vaapi"); + } + if (isNvdecDecoder && isNvencEncoder) { isHwuploadCudaRequired = true; } } + // Interop the VAAPI data to QSV for hybrid tonemapping + if (isTonemappingSupportedOnQsv && isVppTonemappingSupported && !hasGraphicalSubs) + { + filters.Add("hwmap=derive_device=qsv,scale_qsv"); + } + if (isHwuploadCudaRequired && !hasGraphicalSubs) { filters.Add("hwupload_cuda"); } + var output = string.Empty; if (filters.Count > 0) { output += string.Format( @@ -3292,6 +3355,14 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } + // Hybrid VPP tonemapping with VAAPI + if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) + && IsVppTonemappingSupported(state, encodingOptions)) + { + // Since tonemap_vaapi only support HEVC for now, no need to check the codec again. + return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10); + } + if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)) { switch (videoStream.Codec.ToLowerInvariant()) @@ -3520,7 +3591,9 @@ namespace MediaBrowser.Controller.MediaEncoding } } - if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) + || (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) + && IsVppTonemappingSupported(state, options))) { if (IsVaapiSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 0bfa7d3c2b..5cbb579902 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller.MediaEncoding /// /// The filter. /// The option. - /// true if XXXX, false otherwise. + /// true if the filter is supported, false otherwise. bool SupportsFilter(string filter, string option); /// From eb0ff0c37077cc70def96713b257204179c15f80 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 6 Feb 2021 17:18:37 +0100 Subject: [PATCH 1054/1930] Fix forgot password pin request --- Jellyfin.Api/Controllers/UserController.cs | 6 +++--- .../Models/UserDtos/ForgotPasswordPinDto.cs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 87a4ffd92e..17c28779a9 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -509,14 +509,14 @@ namespace Jellyfin.Api.Controllers /// /// Redeems a forgot password pin. /// - /// The pin. + /// The forgot password pin request containing the endered pin. /// Pin reset process started. /// A containing a . [HttpPost("ForgotPassword/Pin")] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task> ForgotPasswordPin([FromBody, Required] string pin) + public async Task> ForgotPasswordPin([FromBody, Required] ForgotPasswordPinDto forgotPasswordPinRequest) { - var result = await _userManager.RedeemPasswordResetPin(pin).ConfigureAwait(false); + var result = await _userManager.RedeemPasswordResetPin(forgotPasswordPinRequest.Pin).ConfigureAwait(false); return result; } diff --git a/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs b/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs new file mode 100644 index 0000000000..62780e23c5 --- /dev/null +++ b/Jellyfin.Api/Models/UserDtos/ForgotPasswordPinDto.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; + +namespace Jellyfin.Api.Models.UserDtos +{ + /// + /// Forgot Password Pin enter request body DTO. + /// + public class ForgotPasswordPinDto + { + /// + /// Gets or sets the entered pin to have the password reset. + /// + [Required] + public string? Pin { get; set; } + } +} From 07f1a2c2dcad7890f19591ccd14d43cbc0e51e95 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Sat, 6 Feb 2021 18:36:18 +0100 Subject: [PATCH 1055/1930] Update Jellyfin.Api/Controllers/UserController.cs Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/UserController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 17c28779a9..43ee309b76 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -509,7 +509,7 @@ namespace Jellyfin.Api.Controllers /// /// Redeems a forgot password pin. /// - /// The forgot password pin request containing the endered pin. + /// The forgot password pin request containing the entered pin. /// Pin reset process started. /// A containing a . [HttpPost("ForgotPassword/Pin")] From a5e55ba85956fe54539cb22dfd95c9499aa3de6c Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 6 Feb 2021 15:59:27 -0500 Subject: [PATCH 1056/1930] Clean up UserManager.AuthenticateUser --- .../Users/UserManager.cs | 23 ++++++------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index d1de5408c4..38a074e988 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -402,27 +402,18 @@ namespace Jellyfin.Server.Implementations.Users } var user = Users.FirstOrDefault(i => string.Equals(username, i.Username, StringComparison.OrdinalIgnoreCase)); - bool success; - IAuthenticationProvider? authenticationProvider; + var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint) + .ConfigureAwait(false); + var authenticationProvider = authResult.authenticationProvider; + var success = authResult.success; - if (user != null) + if (user is null) { - var authResult = await AuthenticateLocalUser(username, password, user, remoteEndPoint) - .ConfigureAwait(false); - authenticationProvider = authResult.authenticationProvider; - success = authResult.success; - } - else - { - var authResult = await AuthenticateLocalUser(username, password, null, remoteEndPoint) - .ConfigureAwait(false); - authenticationProvider = authResult.authenticationProvider; string updatedUsername = authResult.username; - success = authResult.success; if (success - && authenticationProvider != null - && !(authenticationProvider is DefaultAuthenticationProvider)) + && authenticationProvider is not null + && authenticationProvider is not DefaultAuthenticationProvider) { // Trust the username returned by the authentication provider username = updatedUsername; From 49b08798e628a4dee9af6e220d709af36b12fd97 Mon Sep 17 00:00:00 2001 From: Oskari Lavinto Date: Sun, 7 Feb 2021 08:22:51 +0000 Subject: [PATCH 1057/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- .../Localization/Core/fi.json | 148 +++++++++--------- 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index b45bdcbad7..fd6148e789 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -1,121 +1,121 @@ { - "HeaderLiveTV": "Live-TV", - "NewVersionIsAvailable": "Uusi versio Jellyfin palvelimesta on ladattavissa.", + "HeaderLiveTV": "Live TV", + "NewVersionIsAvailable": "Uusi versio Jellyfin-palvelimesta on ladattavissa.", "NameSeasonUnknown": "Tuntematon kausi", "NameSeasonNumber": "Kausi {0}", "NameInstallFailed": "{0} asennus epäonnistui", "MusicVideos": "Musiikkivideot", "Music": "Musiikki", "Movies": "Elokuvat", - "MixedContent": "Sekoitettu sisältö", + "MixedContent": "Sekalainen sisältö", "MessageServerConfigurationUpdated": "Palvelimen asetukset on päivitetty", - "MessageNamedServerConfigurationUpdatedWithValue": "Palvelimen asetusryhmä {0} on päivitetty", - "MessageApplicationUpdatedTo": "Jellyfin palvelin on päivitetty versioon {0}", - "MessageApplicationUpdated": "Jellyfin palvelin on päivitetty", - "Latest": "Uusimmat", - "LabelRunningTimeValue": "Toiston kesto: {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Palvelimen asetusten osio {0} on päivitetty", + "MessageApplicationUpdatedTo": "Jellyfin-palvelin on päivitetty versioon {0}", + "MessageApplicationUpdated": "Jellyfin-palvelin on päivitetty", + "Latest": "Viimeisimmät", + "LabelRunningTimeValue": "Kesto: {0}", "LabelIpAddressValue": "IP-osoite: {0}", "ItemRemovedWithName": "{0} poistettiin kirjastosta", "ItemAddedWithName": "{0} lisättiin kirjastoon", - "Inherit": "Periytyä", + "Inherit": "Peri", "HomeVideos": "Kotivideot", "HeaderRecordingGroups": "Tallennusryhmät", "HeaderNextUp": "Seuraavaksi", "HeaderFavoriteSongs": "Suosikkikappaleet", "HeaderFavoriteShows": "Suosikkisarjat", "HeaderFavoriteEpisodes": "Suosikkijaksot", - "HeaderFavoriteArtists": "Suosikkiartistit", + "HeaderFavoriteArtists": "Suosikkiesittäjät", "HeaderFavoriteAlbums": "Suosikkialbumit", - "HeaderContinueWatching": "Jatka katsomista", - "HeaderAlbumArtists": "Albumin artistit", + "HeaderContinueWatching": "Jatka katselua", + "HeaderAlbumArtists": "Albumin esittäjät", "Genres": "Tyylilajit", "Folders": "Kansiot", "Favorites": "Suosikit", - "FailedLoginAttemptWithUserName": "Kirjautuminen epäonnistui kohteesta {0}", + "FailedLoginAttemptWithUserName": "Epäonnistunut kirjautumisyritys lähteestä \"{0}\"", "DeviceOnlineWithName": "{0} on yhdistetty", - "DeviceOfflineWithName": "{0} yhteys on katkaistu", + "DeviceOfflineWithName": "{0} on katkaissut yhteyden", "Collections": "Kokoelmat", - "ChapterNameValue": "Jakso: {0}", + "ChapterNameValue": "Kappale {0}", "Channels": "Kanavat", - "CameraImageUploadedFrom": "Uusi kamerakuva on ladattu {0}", + "CameraImageUploadedFrom": "Uusi kameran kuva on sirretty lähteestä {0}", "Books": "Kirjat", - "AuthenticationSucceededWithUserName": "Käyttäjän {0} todennus onnistui", - "Artists": "Artistit", + "AuthenticationSucceededWithUserName": "{0} on todennettu", + "Artists": "Esittäjät", "Application": "Sovellus", "AppDeviceValues": "Sovellus: {0}, Laite: {1}", "Albums": "Albumit", "User": "Käyttäjä", "System": "Järjestelmä", "ScheduledTaskFailedWithName": "{0} epäonnistui", - "PluginUpdatedWithName": "{0} päivitetty", - "PluginInstalledWithName": "{0} asennettu", - "Photos": "Kuvat", - "ScheduledTaskStartedWithName": "{0} aloitettu", - "PluginUninstalledWithName": "{0} poistettu", + "PluginUpdatedWithName": "{0} päivitettiin", + "PluginInstalledWithName": "{0} asennettiin", + "Photos": "Valokuvat", + "ScheduledTaskStartedWithName": "\"{0}\" käynnistetty", + "PluginUninstalledWithName": "{0} poistettiin", "Playlists": "Soittolistat", "VersionNumber": "Versio {0}", - "ValueSpecialEpisodeName": "Erikois - {0}", - "ValueHasBeenAddedToLibrary": "{0} lisättiin mediakirjastoon", - "UserStoppedPlayingItemWithValues": "{0} toistaminen valmistui {1} laitteella {2}", - "UserStartedPlayingItemWithValues": "{0} toistaa {1} laitteella {2}", - "UserPolicyUpdatedWithName": "Käyttöoikeudet päivitetty käyttäjälle {0}", - "UserPasswordChangedWithName": "Salasana vaihdettu käyttäjälle {0}", - "UserOnlineFromDevice": "{0} on paikalla osoitteesta {1}", - "UserOfflineFromDevice": "{0} yhteys katkaistu kohteesta {1}", - "UserLockedOutWithName": "Käyttäjä {0} lukittu", - "UserDownloadingItemWithValues": "{0} lataa {1}", - "UserDeletedWithName": "Käyttäjä {0} poistettu", - "UserCreatedWithName": "Käyttäjä {0} luotu", - "TvShows": "TV-ohjelmat", - "Sync": "Synkronoi", - "SubtitleDownloadFailureFromForItem": "Tekstitystä ei voitu ladata osoitteesta {0} kohteelle {1}", - "StartupEmbyServerIsLoading": "Jellyfin palvelin latautuu. Yritä hetken kuluttua uudelleen.", + "ValueSpecialEpisodeName": "Erikoisjakso - {0}", + "ValueHasBeenAddedToLibrary": "\"{0}\" on lisätty mediakirjastoon", + "UserStoppedPlayingItemWithValues": "{0} lopetti kohteen \"{1}\" toiston sijainnissa \"{2}\"", + "UserStartedPlayingItemWithValues": "{0} toistaa kohdetta \"{1}\" sijainnissa \"{2}\"", + "UserPolicyUpdatedWithName": "Käyttäjän {0} käyttöoikeudet on päivitetty", + "UserPasswordChangedWithName": "Käyttäjän {0} salasana on vaihdettu", + "UserOnlineFromDevice": "{0} on yhdistänyt sijainnista \"{1}\"", + "UserOfflineFromDevice": "{0} on katkaissut yhteyden sijainnista \"{1}\"", + "UserLockedOutWithName": "Käyttäjä {0} on lukittu", + "UserDownloadingItemWithValues": "{0} lataa kohdetta \"{1}\"", + "UserDeletedWithName": "Käyttäjä {0} on poistettu", + "UserCreatedWithName": "Käyttäjä {0} on luotu", + "TvShows": "Sarjat", + "Sync": "Synkronointi", + "SubtitleDownloadFailureFromForItem": "Tekstityksen lataus lähteestä \"{0}\" kohteelle \"{1}\" epäonnistui", + "StartupEmbyServerIsLoading": "Jellyfin-palvelin latautuu. Yritä hetken kuluttua uudelleen.", "Songs": "Kappaleet", - "Shows": "Ohjelmat", - "ServerNameNeedsToBeRestarted": "{0} on käynnistettävä uudelleen", - "ProviderValue": "Tarjoaja: {0}", - "Plugin": "Liitännäinen", - "NotificationOptionVideoPlaybackStopped": "Videon toisto pysäytetty", - "NotificationOptionVideoPlayback": "Videota toistetaan", - "NotificationOptionUserLockedOut": "Käyttäjä kirjautui ulos", - "NotificationOptionTaskFailed": "Ajastettu tehtävä epäonnistui", - "NotificationOptionServerRestartRequired": "Palvelin on käynnistettävä uudelleen", - "NotificationOptionPluginUpdateInstalled": "Liitännäinen päivitetty", - "NotificationOptionPluginUninstalled": "Liitännäinen poistettu", - "NotificationOptionPluginInstalled": "Liitännäinen asennettu", - "NotificationOptionPluginError": "Ongelma liitännäisessä", - "NotificationOptionNewLibraryContent": "Uutta sisältöä lisätty", + "Shows": "Sarjat", + "ServerNameNeedsToBeRestarted": "\"{0}\" on käynnistettävä uudelleen", + "ProviderValue": "Lähde: {0}", + "Plugin": "Laajennus", + "NotificationOptionVideoPlaybackStopped": "Videon toisto lopetettu", + "NotificationOptionVideoPlayback": "Videon toisto aloitettu", + "NotificationOptionUserLockedOut": "Käyttäjä on lukittu", + "NotificationOptionTaskFailed": "Ajoitettu tehtävä epäonnistui", + "NotificationOptionServerRestartRequired": "Tarvitaan palvelimen uudelleenkäynnistys", + "NotificationOptionPluginUpdateInstalled": "Laajennus on päivitetty", + "NotificationOptionPluginUninstalled": "Laajennus on poistettu", + "NotificationOptionPluginInstalled": "Laajennus on asennettu", + "NotificationOptionPluginError": "Laajennuksen virhe", + "NotificationOptionNewLibraryContent": "Sisältöä on lisätty", "NotificationOptionInstallationFailed": "Asennus epäonnistui", - "NotificationOptionCameraImageUploaded": "Kameran kuva ladattu", + "NotificationOptionCameraImageUploaded": "Kameran kuva on tallennettu", "NotificationOptionAudioPlaybackStopped": "Äänen toisto lopetettu", - "NotificationOptionAudioPlayback": "Toistetaan ääntä", - "NotificationOptionApplicationUpdateInstalled": "Sovelluspäivitys asennettu", - "NotificationOptionApplicationUpdateAvailable": "Ohjelmistopäivitys saatavilla", + "NotificationOptionAudioPlayback": "Äänen toisto aloitettu", + "NotificationOptionApplicationUpdateInstalled": "Sovelluspäivitys asennettiin", + "NotificationOptionApplicationUpdateAvailable": "Sovelluspäivitys on saatavilla", "TasksMaintenanceCategory": "Ylläpito", - "TaskDownloadMissingSubtitlesDescription": "Etsii puuttuvia tekstityksiä videon metadatatietojen pohjalta.", + "TaskDownloadMissingSubtitlesDescription": "Etsii puuttuvia tekstityksiä määritettyjen metatietoasetusten mukaisesti.", "TaskDownloadMissingSubtitles": "Lataa puuttuvat tekstitykset", "TaskRefreshChannelsDescription": "Päivittää internet-kanavien tiedot.", "TaskRefreshChannels": "Päivitä kanavat", - "TaskCleanTranscodeDescription": "Poistaa transkoodatut tiedostot jotka ovat yli päivän vanhoja.", - "TaskCleanTranscode": "Puhdista transkoodaushakemisto", - "TaskUpdatePluginsDescription": "Lataa ja asentaa päivitykset liitännäisille jotka on asetettu päivittymään automaattisesti.", - "TaskUpdatePlugins": "Päivitä liitännäiset", - "TaskRefreshPeopleDescription": "Päivittää näyttelijöiden ja ohjaajien mediatiedot kirjastossasi.", + "TaskCleanTranscodeDescription": "Poistaa päivää vanhemmat transkoodaustiedostot.", + "TaskCleanTranscode": "Puhdista transkoodauskansio", + "TaskUpdatePluginsDescription": "Lataa ja asentaa päivitykset laajennuksille, jotka on määritetty päivittymään automaattisesti.", + "TaskUpdatePlugins": "Päivitä laajennukset", + "TaskRefreshPeopleDescription": "Päivittää mediakirjaston näyttelijöiden ja ohjaajien metatiedot.", "TaskRefreshPeople": "Päivitä henkilöt", - "TaskCleanLogsDescription": "Poistaa lokitiedostot jotka ovat yli {0} päivää vanhoja.", - "TaskCleanLogs": "Puhdista lokihakemisto", - "TaskRefreshLibraryDescription": "Skannaa mediakirjastosi uudet tiedostot ja päivittää metatiedot.", - "TaskRefreshLibrary": "Skannaa mediakirjasto", - "TaskRefreshChapterImagesDescription": "Luo pienoiskuvat videoille joissa on jaksoja.", - "TaskRefreshChapterImages": "Pura jakson kuvat", - "TaskCleanCacheDescription": "Poistaa järjestelmälle tarpeettomat väliaikaistiedostot.", - "TaskCleanCache": "Tyhjennä välimuisti-hakemisto", - "TasksChannelsCategory": "Internet kanavat", + "TaskCleanLogsDescription": "Poistaa {0} päivää vanhemmat lokitiedostot.", + "TaskCleanLogs": "Siivoa lokikansio", + "TaskRefreshLibraryDescription": "Tarkastaa mediakirjastosi sisällön uusien tiedostojen varalta ja päivittää metatiedot.", + "TaskRefreshLibrary": "Päivitä mediakirjasto", + "TaskRefreshChapterImagesDescription": "Luo esikatselukuvat videoille, jotka sisältävät kappalejaon.", + "TaskRefreshChapterImages": "Pura kappalejaon kuvat", + "TaskCleanCacheDescription": "Poistaa tarpeettomiksi jääneet väliaikaistiedostot.", + "TaskCleanCache": "Tyhjennä välimuistikansio", + "TasksChannelsCategory": "Internet-kanavat", "TasksApplicationCategory": "Sovellus", "TasksLibraryCategory": "Kirjasto", "Forced": "Pakotettu", "Default": "Oletus", - "TaskCleanActivityLogDescription": "Poistaa määritettyä vanhemmat tapahtumat aktiviteettilokista.", - "TaskCleanActivityLog": "Tyhjennä aktiviteettiloki", + "TaskCleanActivityLogDescription": "Poistaa määritettyä ikää vanhemmat tapahtumat toimintahistoriasta.", + "TaskCleanActivityLog": "Tyhjennä toimintahistoria", "Undefined": "Määrittelemätön" } From 053063fd479a19efed31e38464d0a5d7ac2aeaca Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 7 Feb 2021 17:42:23 +0000 Subject: [PATCH 1058/1930] Fixed IP6 host parsing --- MediaBrowser.Common/Net/IPHost.cs | 104 +++++++++--------- .../NetworkTesting/NetworkParseTests.cs | 65 +++++------ 2 files changed, 84 insertions(+), 85 deletions(-) diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 4cede9ab16..84aebb6e78 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -128,62 +128,62 @@ namespace MediaBrowser.Common.Net /// true if the parsing is successful, false if not. public static bool TryParse(string host, out IPHost hostObj) { - if (!string.IsNullOrEmpty(host)) + if (string.IsNullOrWhiteSpace(host)) { - // See if it's an IPv6 with port address e.g. [::1]:120. - int i = host.IndexOf("]:", StringComparison.OrdinalIgnoreCase); - if (i != -1) + hostObj = IPHost.None; + return false; + } + + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + int i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); + if (i != -1) + { + return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); + } + + if (IPNetAddress.TryParse(host, out var netAddress)) + { + // Host name is an ip address, so fake resolve. + hostObj = new IPHost(host, netAddress.Address); + return true; + } + + // Is it a host, IPv4/6 with/out port? + string[] hosts = host.Split(':'); + + if (hosts.Length <= 2) + { + // This is either a hostname: port, or an IP4:port. + host = hosts[0]; + + if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) { - return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); - } - else - { - // See if it's an IPv6 in [] with no port. - i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase); - if (i != -1) - { - return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); - } - - // Is it a host or IPv4 with port? - string[] hosts = host.Split(':'); - - if (hosts.Length > 2) - { - hostObj = new IPHost(string.Empty, IPAddress.None); - return false; - } - - // Remove port from IPv4 if it exists. - host = hosts[0]; - - if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) - { - hostObj = new IPHost(host, new IPAddress(Ipv4Loopback)); - return true; - } - - if (IPNetAddress.TryParse(host, out IPNetAddress netIP)) - { - // Host name is an ip address, so fake resolve. - hostObj = new IPHost(host, netIP.Address); - return true; - } + hostObj = new IPHost(host); + return true; } - // Only thing left is to see if it's a host string. - if (!string.IsNullOrEmpty(host)) + if (IPAddress.TryParse(host, out var netIP)) { - // Use regular expression as CheckHostName isn't RFC5892 compliant. - // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation - Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); - if (re.Match(host).Success) - { - hostObj = new IPHost(host); - return true; - } + // Host name is an ip address, so fake resolve. + hostObj = new IPHost(host, netIP); + return true; } } + else + { + // Invalid host name, as it cannot contain : + hostObj = new IPHost(string.Empty, IPAddress.None); + return false; + } + + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); + if (re.Match(host).Success) + { + hostObj = new IPHost(host); + return true; + } hostObj = IPHost.None; return false; @@ -344,10 +344,14 @@ namespace MediaBrowser.Common.Net { output += "Any Address,"; } - else + else if (i.AddressFamily == AddressFamily.InterNetwork) { output += $"{i}/32,"; } + else + { + output += $"{i}/128,"; + } } output = output[0..^1]; diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index b7c1510d27..7086162a7f 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -13,34 +13,6 @@ namespace Jellyfin.Networking.Tests { public class NetworkParseTests { - /// - /// Tries to identify the string and return an object of that class. - /// - /// String to parse. - /// IPObject to return. - /// True if the value parsed successfully. - private static bool TryParse(string addr, out IPObject result) - { - if (!string.IsNullOrEmpty(addr)) - { - // Is it an IP address - if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) - { - result = nw; - return true; - } - - if (IPHost.TryParse(addr, out IPHost h)) - { - result = h; - return true; - } - } - - result = IPNetAddress.None; - return false; - } - private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) { var configManager = new Mock @@ -118,11 +90,33 @@ namespace Jellyfin.Networking.Tests [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]:124")] [InlineData("fe80::7add:12ff:febb:c67b%16")] [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] + [InlineData("fe80::7add:12ff:febb:c67b%16:123")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]")] + [InlineData("192.168.1.2/255.255.255.0")] + [InlineData("192.168.1.2/24")] + public void ValidHostStrings(string address) + { + Assert.True(IPHost.TryParse(address, out _)); + } + + /// + /// Checks IP address formats. + /// + /// + [Theory] + [InlineData("127.0.0.1")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] + [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")] + [InlineData("fe80::7add:12ff:febb:c67b%16")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] + [InlineData("fe80::7add:12ff:febb:c67b%16:123")] + [InlineData("[fe80::7add:12ff:febb:c67b%16]")] [InlineData("192.168.1.2/255.255.255.0")] [InlineData("192.168.1.2/24")] public void ValidIPStrings(string address) { - Assert.True(TryParse(address, out _)); + Assert.True(IPNetAddress.TryParse(address, out _)); } @@ -138,7 +132,8 @@ namespace Jellyfin.Networking.Tests [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public void InvalidAddressString(string address) { - Assert.False(TryParse(address, out _)); + Assert.False(IPNetAddress.TryParse(address, out _)); + Assert.False(IPHost.TryParse(address, out _)); } @@ -172,11 +167,11 @@ namespace Jellyfin.Networking.Tests "[]")] [InlineData( "192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, !10.10.10.10", - "[192.158.1.2/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]", + "[192.158.1.2/16,[127.0.0.1/32,::1/128],fd23:184f:2029:0:3139:7386:67d7:d517/128]", "[192.158.1.2/16,127.0.0.1/32]", "[10.10.10.10/32]", "[10.10.10.10/32]", - "[192.158.0.0/16,127.0.0.1/32,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] + "[192.158.0.0/16,127.0.0.1/32,::1/128,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] [InlineData("192.158.1.2/255.255.0.0,192.169.1.2/8", "[192.158.1.2/16,192.169.1.2/8]", "[192.158.1.2/16,192.169.1.2/8]", @@ -333,8 +328,8 @@ namespace Jellyfin.Networking.Tests public void TestSubnetContains(string network, string ip) { - Assert.True(TryParse(network, out IPObject? networkObj)); - Assert.True(TryParse(ip, out IPObject? ipObj)); + Assert.True(IPNetAddress.TryParse(network, out var networkObj)); + Assert.True(IPNetAddress.TryParse(ip, out var ipObj)); Assert.True(networkObj.Contains(ipObj)); } @@ -468,7 +463,7 @@ namespace Jellyfin.Networking.Tests // User on internal network, no binding specified - so result is the 1st internal. [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")] - // User on external network, internal binding only - so asumption is a proxy forward, return external override. + // User on external network, internal binding only - so assumption is a proxy forward, return external override. [InlineData("jellyfin.org", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")] // User on external network, no binding - so result is the 1st external which is overriden. From e8fd4531ed9e41be7996ee5e67a5f4c98cc75c39 Mon Sep 17 00:00:00 2001 From: Jakub Fabijan Date: Sun, 7 Feb 2021 19:57:33 +0000 Subject: [PATCH 1059/1930] Added translation using Weblate (Esperanto) --- Emby.Server.Implementations/Localization/Core/eo.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 Emby.Server.Implementations/Localization/Core/eo.json diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/Emby.Server.Implementations/Localization/Core/eo.json @@ -0,0 +1 @@ +{} From 6c2eb5fc7e872a29b4a0951849681ae0764dbb8e Mon Sep 17 00:00:00 2001 From: Jakub Fabijan Date: Sun, 7 Feb 2021 20:20:17 +0000 Subject: [PATCH 1060/1930] Translated using Weblate (Esperanto) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/eo/ --- .../Localization/Core/eo.json | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json index 0967ef424b..3ff7eddae3 100644 --- a/Emby.Server.Implementations/Localization/Core/eo.json +++ b/Emby.Server.Implementations/Localization/Core/eo.json @@ -1 +1,26 @@ -{} +{ + "NotificationOptionInstallationFailed": "Instalada fiasko", + "NotificationOptionAudioPlaybackStopped": "Sono de ludado haltis", + "NotificationOptionAudioPlayback": "Ludado de sono startis", + "NameSeasonUnknown": "Sezono Nekonata", + "NameSeasonNumber": "Sezono {0}", + "NameInstallFailed": "{0} instalado fiaskis", + "Music": "Muziko", + "Movies": "Filmoj", + "ItemRemovedWithName": "{0} forigis el la biblioteko", + "ItemAddedWithName": "{0} aldonis al la biblioteko", + "HeaderLiveTV": "Viva Televido", + "HeaderContinueWatching": "Daŭrigi Spektado", + "HeaderAlbumArtists": "Artistoj de Albumo", + "Folders": "Dosierujoj", + "DeviceOnlineWithName": "{0} estas konektita", + "Default": "Defaŭlte", + "Collections": "Kolektoj", + "ChapterNameValue": "Ĉapitro {0}", + "Channels": "Kanaloj", + "Books": "Libroj", + "Artists": "Artistoj", + "Application": "Aplikaĵo", + "AppDeviceValues": "Aplikaĵo: {0}, Aparato: {1}", + "Albums": "Albumoj" +} From 22e86671052841eb3ce949074fba465f48c9c236 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Mon, 8 Feb 2021 16:41:38 +0800 Subject: [PATCH 1061/1930] Apply suggestions from code review Co-authored-by: Claus Vium --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index cbba1a6345..07a9f5ba61 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2234,8 +2234,8 @@ namespace MediaBrowser.Controller.MediaEncoding } } else if ((videoDecoder ?? string.Empty).Contains("cuda", StringComparison.OrdinalIgnoreCase) - && width.HasValue - && height.HasValue) + && width.HasValue + && height.HasValue) { var outputWidth = width.Value; var outputHeight = height.Value; @@ -2667,14 +2667,14 @@ namespace MediaBrowser.Controller.MediaEncoding // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context. else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder) - && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) + && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { filters.Add("hwupload=extra_hw_frames=64"); } // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first. else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder) - && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) + && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported)) { var codec = videoStream.Codec; From df121c1516e4fa531904529397736e89ca41366c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Feb 2021 12:00:45 +0000 Subject: [PATCH 1062/1930] Bump Swashbuckle.AspNetCore.ReDoc from 5.6.3 to 6.0.2 Bumps [Swashbuckle.AspNetCore.ReDoc](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 5.6.3 to 6.0.2. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v5.6.3...v6.0.2) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 8437369b2f..3dd4776c12 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -18,7 +18,7 @@ - + From 311b2f50122237d96fc93fc48c3658f4970de5a2 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 8 Feb 2021 15:38:06 +0100 Subject: [PATCH 1063/1930] Exclude BOM when writing meta.json plugin manifest --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 8e5987026b..2e2b3f332f 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -348,7 +348,7 @@ namespace Emby.Server.Implementations.Plugins try { var data = JsonSerializer.Serialize(manifest, _jsonOptions); - File.WriteAllText(Path.Combine(path, "meta.json"), data, Encoding.UTF8); + File.WriteAllText(Path.Combine(path, "meta.json"), data); return true; } #pragma warning disable CA1031 // Do not catch general exception types From 88f37833df41bdb4865b90bfb16319b5bd6d2695 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 8 Feb 2021 16:33:37 +0100 Subject: [PATCH 1064/1930] Remove last usage of \d --- Emby.Naming/Common/NamingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/Common/NamingOptions.cs b/Emby.Naming/Common/NamingOptions.cs index 413976d9d7..22a3e8bb49 100644 --- a/Emby.Naming/Common/NamingOptions.cs +++ b/Emby.Naming/Common/NamingOptions.cs @@ -284,7 +284,7 @@ namespace Emby.Naming.Common // Not a Kodi rule as well, but below rule also causes false positives for triple-digit episode names // [bar] Foo - 1 [baz] special case of below expression to prevent false positives with digits in the series name - new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[\s_]*-[\s_]*(?\d+).*$") + new EpisodeExpression(@".*?(\[.*?\])+.*?(?[\w\s]+?)[\s_]*-[\s_]*(?[0-9]+).*$") { IsNamed = true }, From 13c1c2815f82be2bd316f73fe377b1ff3587e24f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 8 Feb 2021 17:10:20 +0100 Subject: [PATCH 1065/1930] Add regression test for PluginManager.SaveManifest --- .../Plugins/PluginManager.cs | 2 +- .../Plugins/PluginManagerTests.cs | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 2e2b3f332f..c26ccfd886 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -519,7 +519,7 @@ namespace Emby.Server.Implementations.Plugins return _plugins.Remove(plugin); } - private LocalPlugin LoadManifest(string dir) + internal LocalPlugin LoadManifest(string dir) { Version? version; PluginManifest? manifest = null; diff --git a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs new file mode 100644 index 0000000000..bc6a447410 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Emby.Server.Implementations.Plugins; +using MediaBrowser.Common.Plugins; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Plugins +{ + public class PluginManagerTests + { + private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data"); + + [Fact] + public void SaveManifest_RoundTrip_Success() + { + var pluginManager = new PluginManager(new NullLogger(), null!, null!, null!, new Version(1, 0)); + var manifest = new PluginManifest() + { + Version = "1.0" + }; + + var tempPath = Path.Combine(_testPathRoot, "manifest-" + Path.GetRandomFileName()); + Directory.CreateDirectory(tempPath); + + Assert.True(pluginManager.SaveManifest(manifest, tempPath)); + + var res = pluginManager.LoadManifest(tempPath); + + Assert.Equal(manifest.Category, res.Manifest.Category); + Assert.Equal(manifest.Changelog, res.Manifest.Changelog); + Assert.Equal(manifest.Description, res.Manifest.Description); + Assert.Equal(manifest.Id, res.Manifest.Id); + Assert.Equal(manifest.Name, res.Manifest.Name); + Assert.Equal(manifest.Overview, res.Manifest.Overview); + Assert.Equal(manifest.Owner, res.Manifest.Owner); + Assert.Equal(manifest.TargetAbi, res.Manifest.TargetAbi); + Assert.Equal(manifest.Timestamp, res.Manifest.Timestamp); + Assert.Equal(manifest.Version, res.Manifest.Version); + Assert.Equal(manifest.Status, res.Manifest.Status); + Assert.Equal(manifest.AutoUpdate, res.Manifest.AutoUpdate); + Assert.Equal(manifest.ImagePath, res.Manifest.ImagePath); + } + } +} From 094ffafb249e454f8e71279f8aa0693a17990e1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20V=C3=A1radi?= Date: Mon, 8 Feb 2021 18:56:06 +0100 Subject: [PATCH 1066/1930] Comment and simplify code --- .../Parsers/EpisodeNfoParser.cs | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index 5922b4f44f..3a852384af 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -51,6 +51,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions try { + // Extract episode details from the firs episodedetails block using (var stringReader = new StringReader(xml)) using (var reader = XmlReader.Create(stringReader, settings)) { @@ -72,19 +73,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers } } } - } - catch (XmlException) - { - } - while ((index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase)) != -1) - { - xml = xmlFile.Substring(0, index + srch.Length); - xmlFile = xmlFile.Substring(index + srch.Length); - - // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions - try + // Extract the last episode number from nfo + // This is needed because XBMC metadata uses multiple episodedetails blocks instead of episodenumberend tag + while ((index = xmlFile.IndexOf(srch, StringComparison.OrdinalIgnoreCase)) != -1) { + xml = xmlFile.Substring(0, index + srch.Length); + xmlFile = xmlFile.Substring(index + srch.Length); + using (var stringReader = new StringReader(xml)) using (var reader = XmlReader.Create(stringReader, settings)) { @@ -104,9 +100,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers } } } - catch (XmlException) - { - } + } + catch (XmlException) + { } } } From 351d61a3181c6caf217ec74eed37f972190b624d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20V=C3=A1radi?= Date: Mon, 8 Feb 2021 19:40:17 +0100 Subject: [PATCH 1067/1930] Add test for multiepisode nfo parsing --- .../Parsers/EpisodeNfoProviderTests.cs | 20 +++++++++++++++++++ .../Test Data/Rising.nfo | 20 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs index 67b4b969a3..7f87163fdf 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs @@ -81,6 +81,26 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal(new DateTime(2017, 10, 7, 14, 25, 47), item.DateCreated); } + [Fact] + public void Fetch_Valid_MultiEpisode_Succes() + { + var result = new MetadataResult() + { + Item = new Episode() + }; + + _parser.Fetch(result, "Test Data/Rising.nfo", CancellationToken.None); + + var item = result.Item; + Assert.Equal("Rising (1)", item.Name); + Assert.Equal(1, item.IndexNumber); + Assert.Equal(2, item.IndexNumberEnd); + Assert.Equal(1, item.ParentIndexNumber); + Assert.Equal("A new Stargate team embarks on a dangerous mission to a distant galaxy, where they discover a mythical lost city -- and a deadly new enemy.", item.Overview); + Assert.Equal(new DateTime(2004, 7, 16), item.PremiereDate); + Assert.Equal(2004, item.ProductionYear); + } + [Fact] public void Fetch_WithNullItem_ThrowsArgumentException() { diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo new file mode 100644 index 0000000000..56250c09a8 --- /dev/null +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Rising.nfo @@ -0,0 +1,20 @@ + + Rising (1) + 1 + 1 + 2004-07-16 + A new Stargate team embarks on a dangerous mission to a distant galaxy, where they discover a mythical lost city -- and a deadly new enemy. + https://artworks.thetvdb.com/banners/episodes/70851/25333.jpg + false + 8.0 + + + Rising (2) + 1 + 2 + 2004-07-16 + Sheppard tries to convince Weir to mount a rescue mission to free Colonel Sumner, Teyla, and the others captured by the Wraith. + https://artworks.thetvdb.com/banners/episodes/70851/25334.jpg + false + 7.9 + From c97edc96eb432940fb7352165c644bab4d6d0dda Mon Sep 17 00:00:00 2001 From: netpok Date: Mon, 8 Feb 2021 21:02:54 +0100 Subject: [PATCH 1068/1930] Fix typo Co-authored-by: Cody Robibero --- MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index 3a852384af..aa3be587b4 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -51,7 +51,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions try { - // Extract episode details from the firs episodedetails block + // Extract episode details from the first episodedetails block using (var stringReader = new StringReader(xml)) using (var reader = XmlReader.Create(stringReader, settings)) { From 7ba53548a2ed07cf3b6b4692ddd79df9d85edf63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20V=C3=A1radi?= Date: Tue, 9 Feb 2021 07:21:08 +0100 Subject: [PATCH 1069/1930] Fix typos in nfo tests --- .../Parsers/EpisodeNfoProviderTests.cs | 4 ++-- .../Parsers/MovieNfoParserTests.cs | 2 +- .../Parsers/MusicAlbumNfoProviderTests.cs | 2 +- .../Parsers/MusicArtistNfoParserTests.cs | 2 +- .../Parsers/SeasonNfoProviderTests.cs | 2 +- .../Parsers/SeriesNfoParserTests.cs | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs index 7f87163fdf..3710d52c31 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs @@ -32,7 +32,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers } [Fact] - public void Fetch_Valid_Succes() + public void Fetch_Valid_Success() { var result = new MetadataResult() { @@ -82,7 +82,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers } [Fact] - public void Fetch_Valid_MultiEpisode_Succes() + public void Fetch_Valid_MultiEpisode_Success() { var result = new MetadataResult() { diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 765464eced..007a41a24a 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -30,7 +30,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers } [Fact] - public void Fetch_Valid_Succes() + public void Fetch_Valid_Success() { var result = new MetadataResult public class AssParser : SubtitleEditParser { + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public AssParser(ILogger logger) : base(logger) + { + } } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index 7a7196f6c3..19fb951dc5 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -1,5 +1,6 @@ #nullable enable +using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core.SubtitleFormats; namespace MediaBrowser.MediaEncoding.Subtitles @@ -9,5 +10,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// public class SrtParser : SubtitleEditParser { + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public SrtParser(ILogger logger) : base(logger) + { + } } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs index 8cd06194d9..36dc2e01fc 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs @@ -1,5 +1,6 @@ #nullable enable +using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core.SubtitleFormats; namespace MediaBrowser.MediaEncoding.Subtitles @@ -9,5 +10,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// public class SsaParser : SubtitleEditParser { + /// + /// Initializes a new instance of the class. + /// + /// The logger. + public SsaParser(ILogger logger) : base(logger) + { + } } } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs index 441b9ce332..82ec6ca217 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs @@ -6,17 +6,31 @@ using System.Linq; using System.Threading; using MediaBrowser.Common.Extensions; using MediaBrowser.Model.MediaInfo; +using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core; +using ILogger = Microsoft.Extensions.Logging.ILogger; +using SubtitleFormat = Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat; namespace MediaBrowser.MediaEncoding.Subtitles { /// /// SubStation Alpha subtitle parser. /// - /// The . + /// The . public abstract class SubtitleEditParser : ISubtitleParser - where T : Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat, new() + where T : SubtitleFormat, new() { + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The logger. + protected SubtitleEditParser(ILogger logger) + { + _logger = logger; + } + /// public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken) { @@ -24,6 +38,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles var subRip = new T(); var lines = stream.ReadAllLines().ToList(); subRip.LoadSubtitle(subtitle, lines, "untitled"); + if (subRip.ErrorCount > 0) + { + _logger.LogError("{ErrorCount} errors encountered while parsing subtitle."); + } var trackInfo = new SubtitleTrackInfo(); int len = subtitle.Paragraphs.Count; diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 62ac83c91b..a9d118ef58 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -271,17 +271,17 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase)) { - return new SrtParser(); + return new SrtParser(_logger); } if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase)) { - return new SsaParser(); + return new SsaParser(_logger); } if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase)) { - return new AssParser(); + return new AssParser(_logger); } if (throwIfMissing) diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs index 457ef45446..f38fc23d5e 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Threading; using MediaBrowser.MediaEncoding.Subtitles; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Jellyfin.MediaEncoding.Subtitles.Tests @@ -14,7 +15,7 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests { using (var stream = File.OpenRead("Test Data/example.ass")) { - var parsed = new AssParser().Parse(stream, CancellationToken.None); + var parsed = new AssParser(new NullLogger()).Parse(stream, CancellationToken.None); Assert.Single(parsed.TrackEvents); var trackEvent = parsed.TrackEvents[0]; diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs index 6bfc426cb1..25b8b47461 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Threading; using MediaBrowser.MediaEncoding.Subtitles; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Jellyfin.MediaEncoding.Subtitles.Tests @@ -14,7 +15,7 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests { using (var stream = File.OpenRead("Test Data/example.srt")) { - var parsed = new SrtParser().Parse(stream, CancellationToken.None); + var parsed = new SrtParser(new NullLogger()).Parse(stream, CancellationToken.None); Assert.Equal(2, parsed.TrackEvents.Count); var trackEvent1 = parsed.TrackEvents[0]; diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs index 660b7f1be6..0ff7cb1ec3 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Threading; using MediaBrowser.MediaEncoding.Subtitles; +using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Jellyfin.MediaEncoding.Subtitles.Tests @@ -14,7 +15,7 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests { using (var stream = File.OpenRead("Test Data/example.ssa")) { - var parsed = new SsaParser().Parse(stream, CancellationToken.None); + var parsed = new SsaParser(new NullLogger()).Parse(stream, CancellationToken.None); Assert.Single(parsed.TrackEvents); var trackEvent = parsed.TrackEvents[0]; From f81bcf7f35ce4d63e771b1e4e7fb25626faae884 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 8 Jan 2021 23:23:48 +0100 Subject: [PATCH 1074/1930] Fix tests on windows --- tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs | 2 +- tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs index f38fc23d5e..3775555dec 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/AssParserTests.cs @@ -22,7 +22,7 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests Assert.Equal("1", trackEvent.Id); Assert.Equal(TimeSpan.Parse("00:00:01.18", CultureInfo.InvariantCulture).Ticks, trackEvent.StartPositionTicks); Assert.Equal(TimeSpan.Parse("00:00:06.85", CultureInfo.InvariantCulture).Ticks, trackEvent.EndPositionTicks); - Assert.Equal("{\\pos(400,570)}Like an Angel with pity on nobody\nThe second line in subtitle", trackEvent.Text); + Assert.Equal("{\\pos(400,570)}Like an Angel with pity on nobody" + Environment.NewLine + "The second line in subtitle", trackEvent.Text); } } } diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs index 25b8b47461..537a944b03 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SrtParserTests.cs @@ -22,7 +22,7 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests Assert.Equal("1", trackEvent1.Id); Assert.Equal(TimeSpan.Parse("00:02:17.440", CultureInfo.InvariantCulture).Ticks, trackEvent1.StartPositionTicks); Assert.Equal(TimeSpan.Parse("00:02:20.375", CultureInfo.InvariantCulture).Ticks, trackEvent1.EndPositionTicks); - Assert.Equal("Senator, we're making\nour final approach into Coruscant.", trackEvent1.Text); + Assert.Equal("Senator, we're making" + Environment.NewLine + "our final approach into Coruscant.", trackEvent1.Text); var trackEvent2 = parsed.TrackEvents[1]; Assert.Equal("2", trackEvent2.Id); From 9e5c4439b9cba6922ccadf880edb9049ce18e824 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 9 Jan 2021 16:42:21 +0100 Subject: [PATCH 1075/1930] Comment out broken tests --- .../SsaParserTests.cs | 96 ------------------- .../Subtitles/SsaParserTests.cs | 88 ++++++++++++++++- 2 files changed, 87 insertions(+), 97 deletions(-) delete mode 100644 tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs diff --git a/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs deleted file mode 100644 index d11cb242c1..0000000000 --- a/tests/Jellyfin.MediaEncoding.Tests/SsaParserTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using MediaBrowser.MediaEncoding.Subtitles; -using MediaBrowser.Model.MediaInfo; -using Xunit; - -namespace Jellyfin.MediaEncoding.Tests -{ - public class SsaParserTests - { - // commonly shared invariant value between tests, assumes default format order - private const string InvariantDialoguePrefix = "[Events]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,"; - - private SsaParser parser = new SsaParser(); - - [Theory] - [InlineData("[EvEnTs]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,text", "text")] // label casing insensitivity - [InlineData("[Events]\n,0:00:00.00,0:00:00.01,,,,,,,labelless dialogue", "labelless dialogue")] // no "Dialogue:" label, it is optional - [InlineData("[Events]\nFormat: Text, Start, End, Layer, Effect, Style\nDialogue: reordered text,0:00:00.00,0:00:00.01", "reordered text")] // reordered formats - [InlineData(InvariantDialoguePrefix + "Cased TEXT", "Cased TEXT")] // preserve text casing - [InlineData(InvariantDialoguePrefix + " text ", " text ")] // do not trim text - [InlineData(InvariantDialoguePrefix + "text, more text", "text, more text")] // append excess dialogue values (> 10) to text - [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text{\\fn} end", "start text end")] // font name - [InlineData(InvariantDialoguePrefix + "start {\\fs10}text{\\fs} end", "start text end")] // font size - [InlineData(InvariantDialoguePrefix + "start {\\c&H112233}text{\\c} end", "start text end")] // color - [InlineData(InvariantDialoguePrefix + "start {\\1c&H112233}text{\\1c} end", "start text end")] // primay color - [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text1 {\\fs10}text2{\\fs}{\\fn} {\\1c&H112233}text3{\\1c} end", "start text1 text2 text3 end")] // nested formatting - public void Parse(string ssa, string expectedText) - { - using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) - { - SubtitleTrackInfo subtitleTrackInfo = parser.Parse(stream, CancellationToken.None); - SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[0]; - Assert.Equal(expectedText, actual.Text); - } - } - - [Theory] - [MemberData(nameof(Parse_MultipleDialogues_TestData))] - public void Parse_MultipleDialogues(string ssa, IReadOnlyList expectedSubtitleTrackEvents) - { - using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) - { - SubtitleTrackInfo subtitleTrackInfo = parser.Parse(stream, CancellationToken.None); - - Assert.Equal(expectedSubtitleTrackEvents.Count, subtitleTrackInfo.TrackEvents.Count); - - for (int i = 0; i < expectedSubtitleTrackEvents.Count; ++i) - { - SubtitleTrackEvent expected = expectedSubtitleTrackEvents[i]; - SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[i]; - - Assert.Equal(expected.StartPositionTicks, actual.StartPositionTicks); - Assert.Equal(expected.EndPositionTicks, actual.EndPositionTicks); - Assert.Equal(expected.Text, actual.Text); - } - } - } - - public static IEnumerable Parse_MultipleDialogues_TestData() - { - yield return new object[] - { - @"[Events] - Format: Layer, Start, End, Text - Dialogue: ,0:00:01.18,0:00:01.85,dialogue1 - Dialogue: ,0:00:02.18,0:00:02.85,dialogue2 - Dialogue: ,0:00:03.18,0:00:03.85,dialogue3 - ", - new List - { - new SubtitleTrackEvent - { - StartPositionTicks = 11800000, - EndPositionTicks = 18500000, - Text = "dialogue1" - }, - new SubtitleTrackEvent - { - StartPositionTicks = 21800000, - EndPositionTicks = 28500000, - Text = "dialogue2" - }, - new SubtitleTrackEvent - { - StartPositionTicks = 31800000, - EndPositionTicks = 38500000, - Text = "dialogue3" - } - } - }; - } - } -} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs index 0ff7cb1ec3..5033d1de91 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs @@ -1,8 +1,11 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Text; using System.Threading; using MediaBrowser.MediaEncoding.Subtitles; +using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -10,12 +13,95 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests { public class SsaParserTests { + // commonly shared invariant value between tests, assumes default format order + private const string InvariantDialoguePrefix = "[Events]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,"; + + private readonly SsaParser _parser = new SsaParser(new NullLogger()); + + [Theory] + [InlineData("[EvEnTs]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,text", "text")] // label casing insensitivity + [InlineData("[Events]\n,0:00:00.00,0:00:00.01,,,,,,,labelless dialogue", "labelless dialogue")] // no "Dialogue:" label, it is optional + // TODO: Fix upstream + // [InlineData("[Events]\nFormat: Text, Start, End, Layer, Effect, Style\nDialogue: reordered text,0:00:00.00,0:00:00.01", "reordered text")] // reordered formats + [InlineData(InvariantDialoguePrefix + "Cased TEXT", "Cased TEXT")] // preserve text casing + [InlineData(InvariantDialoguePrefix + " text ", " text ")] // do not trim text + [InlineData(InvariantDialoguePrefix + "text, more text", "text, more text")] // append excess dialogue values (> 10) to text + [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text{\\fn} end", "start text end")] // font name + [InlineData(InvariantDialoguePrefix + "start {\\fs10}text{\\fs} end", "start text end")] // font size + [InlineData(InvariantDialoguePrefix + "start {\\c&H112233}text{\\c} end", "start text end")] // color + // TODO: Fix upstream + // [InlineData(InvariantDialoguePrefix + "start {\\1c&H112233}text{\\1c} end", "start text end")] // primay color + // [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text1 {\\fs10}text2{\\fs}{\\fn} {\\1c&H112233}text3{\\1c} end", "start text1 text2 text3 end")] // nested formatting + public void Parse(string ssa, string expectedText) + { + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) + { + SubtitleTrackInfo subtitleTrackInfo = _parser.Parse(stream, CancellationToken.None); + SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[0]; + Assert.Equal(expectedText, actual.Text); + } + } + + [Theory] + [MemberData(nameof(Parse_MultipleDialogues_TestData))] + public void Parse_MultipleDialogues(string ssa, IReadOnlyList expectedSubtitleTrackEvents) + { + using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) + { + SubtitleTrackInfo subtitleTrackInfo = _parser.Parse(stream, CancellationToken.None); + + Assert.Equal(expectedSubtitleTrackEvents.Count, subtitleTrackInfo.TrackEvents.Count); + + for (int i = 0; i < expectedSubtitleTrackEvents.Count; ++i) + { + SubtitleTrackEvent expected = expectedSubtitleTrackEvents[i]; + SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[i]; + + Assert.Equal(expected.Id, actual.Id); + Assert.Equal(expected.Text, actual.Text); + Assert.Equal(expected.StartPositionTicks, actual.StartPositionTicks); + Assert.Equal(expected.EndPositionTicks, actual.EndPositionTicks); + } + } + } + + public static IEnumerable Parse_MultipleDialogues_TestData() + { + yield return new object[] + { + @"[Events] + Format: Layer, Start, End, Text + Dialogue: ,0:00:01.18,0:00:01.85,dialogue1 + Dialogue: ,0:00:02.18,0:00:02.85,dialogue2 + Dialogue: ,0:00:03.18,0:00:03.85,dialogue3 + ", + new List + { + new SubtitleTrackEvent("1", "dialogue1") + { + StartPositionTicks = 11800000, + EndPositionTicks = 18500000 + }, + new SubtitleTrackEvent("2", "dialogue2") + { + StartPositionTicks = 21800000, + EndPositionTicks = 28500000 + }, + new SubtitleTrackEvent("3", "dialogue3") + { + StartPositionTicks = 31800000, + EndPositionTicks = 38500000 + } + } + }; + } + [Fact] public void Parse_Valid_Success() { using (var stream = File.OpenRead("Test Data/example.ssa")) { - var parsed = new SsaParser(new NullLogger()).Parse(stream, CancellationToken.None); + var parsed = _parser.Parse(stream, CancellationToken.None); Assert.Single(parsed.TrackEvents); var trackEvent = parsed.TrackEvents[0]; From 407c35f087d7998ff072b68f837bdefb15a7304b Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 9 Feb 2021 19:02:02 -0700 Subject: [PATCH 1076/1930] Update to dotnet 5.0.3 --- .ci/azure-pipelines-abi.yml | 2 +- .ci/azure-pipelines-api-client.yml | 2 +- .ci/azure-pipelines-main.yml | 2 +- .ci/azure-pipelines-test.yml | 2 +- .ci/azure-pipelines.yml | 2 +- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- Jellyfin.Data/Jellyfin.Data.csproj | 4 ++-- .../Jellyfin.Server.Implementations.csproj | 4 ++-- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++-- deployment/Dockerfile.debian.amd64 | 2 +- deployment/Dockerfile.debian.arm64 | 2 +- deployment/Dockerfile.debian.armhf | 2 +- deployment/Dockerfile.linux.amd64 | 2 +- deployment/Dockerfile.linux.amd64-musl | 2 +- deployment/Dockerfile.linux.arm64 | 2 +- deployment/Dockerfile.linux.armhf | 2 +- deployment/Dockerfile.macos | 2 +- deployment/Dockerfile.portable | 2 +- deployment/Dockerfile.ubuntu.amd64 | 2 +- deployment/Dockerfile.ubuntu.arm64 | 2 +- deployment/Dockerfile.ubuntu.armhf | 2 +- deployment/Dockerfile.windows.amd64 | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- 23 files changed, 26 insertions(+), 26 deletions(-) diff --git a/.ci/azure-pipelines-abi.yml b/.ci/azure-pipelines-abi.yml index 14df7e7c8d..8d0737b66c 100644 --- a/.ci/azure-pipelines-abi.yml +++ b/.ci/azure-pipelines-abi.yml @@ -7,7 +7,7 @@ parameters: default: "ubuntu-latest" - name: DotNetSdkVersion type: string - default: 5.0.100 + default: 5.0.103 jobs: - job: CompatibilityCheck diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml index 177f78889c..0e944e6f47 100644 --- a/.ci/azure-pipelines-api-client.yml +++ b/.ci/azure-pipelines-api-client.yml @@ -4,7 +4,7 @@ default: "ubuntu-latest" - name: GeneratorVersion type: string - default: "5.0.0-beta2" + default: "5.0.1" jobs: - job: GenerateApiClients diff --git a/.ci/azure-pipelines-main.yml b/.ci/azure-pipelines-main.yml index 95dd3ccac2..4bc72f9eb0 100644 --- a/.ci/azure-pipelines-main.yml +++ b/.ci/azure-pipelines-main.yml @@ -1,7 +1,7 @@ parameters: LinuxImage: 'ubuntu-latest' RestoreBuildProjects: 'Jellyfin.Server/Jellyfin.Server.csproj' - DotNetSdkVersion: 5.0.100 + DotNetSdkVersion: 5.0.103 jobs: - job: Build diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index 36152c82a4..95e0d8c58d 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -10,7 +10,7 @@ parameters: default: "tests/**/*Tests.csproj" - name: DotNetSdkVersion type: string - default: 5.0.100 + default: 5.0.103 jobs: - job: Test diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index ec4c254358..6430503f9a 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -6,7 +6,7 @@ variables: - name: RestoreBuildProjects value: 'Jellyfin.Server/Jellyfin.Server.csproj' - name: DotNetSdkVersion - value: 5.0.100 + value: 5.0.103 pr: autoCancel: true diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 3dd4776c12..c2f4ab522a 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,7 +15,7 @@ - + diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index faea50297d..a8ac45645f 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -41,8 +41,8 @@ - - + + diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 05052e5c06..4f24da0ee4 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -26,11 +26,11 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 3ebcc3279d..bf4f806693 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -40,8 +40,8 @@ - - + + diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index f5cf232d65..4280726135 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index d9414a6104..b540efc09a 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 7f2275aaa3..426ce02fcd 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 54d75dcbe9..3b91515f36 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl index e4c7242191..2ca9072bae 100644 --- a/deployment/Dockerfile.linux.amd64-musl +++ b/deployment/Dockerfile.linux.amd64-musl @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 index 6338025981..03efd306d7 100644 --- a/deployment/Dockerfile.linux.arm64 +++ b/deployment/Dockerfile.linux.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf index ec0b015cc8..585572204b 100644 --- a/deployment/Dockerfile.linux.armhf +++ b/deployment/Dockerfile.linux.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index 25f15be183..b37afdcfbc 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index cd71ce9d49..686b20197c 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index ea539b3609..3513bf8ecb 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index f2f5368f7a..5acdf0d178 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index ba597801b5..42f757d058 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index c731268416..6ed1193fb0 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/7f736160-9f34-4595-8d72-13630c437aef/b9c4513afb0f8872eb95793c70ac52f6/dotnet-sdk-5.0.102-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 3da728c633..eca3df79b3 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -16,7 +16,7 @@ - + From 90236efdf247da77cac0ed47daabe82b1bd6f7c9 Mon Sep 17 00:00:00 2001 From: "me@justinharrison.ca" Date: Wed, 10 Feb 2021 17:08:55 -0500 Subject: [PATCH 1077/1930] Default to English metadata during the setup wizard. --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 0f0ad0f9aa..439a84024f 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -254,7 +254,7 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets the preferred metadata language. /// /// The preferred metadata language. - public string PreferredMetadataLanguage { get; set; } = string.Empty; + public string PreferredMetadataLanguage { get; set; } = "en"; /// /// Gets or sets the metadata country code. From d5f0b046bb21dea0c120aa27f68fabc5947a8f1d Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 10 Feb 2021 16:12:52 -0700 Subject: [PATCH 1078/1930] Add image file accept to openapi --- .../Attributes/AcceptsFileAttribute.cs | 28 ++++++++++++ .../Attributes/AcceptsImageFileAttribute.cs | 18 ++++++++ Jellyfin.Api/Controllers/ImageController.cs | 4 ++ .../ApiServiceCollectionExtensions.cs | 1 + Jellyfin.Server/Filters/FileRequestFilter.cs | 43 +++++++++++++++++++ 5 files changed, 94 insertions(+) create mode 100644 Jellyfin.Api/Attributes/AcceptsFileAttribute.cs create mode 100644 Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs create mode 100644 Jellyfin.Server/Filters/FileRequestFilter.cs diff --git a/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs new file mode 100644 index 0000000000..49b6689cde --- /dev/null +++ b/Jellyfin.Api/Attributes/AcceptsFileAttribute.cs @@ -0,0 +1,28 @@ +using System; + +namespace Jellyfin.Api.Attributes +{ + /// + /// Internal produces image attribute. + /// + [AttributeUsage(AttributeTargets.Method)] + public class AcceptsFileAttribute : Attribute + { + private readonly string[] _contentTypes; + + /// + /// Initializes a new instance of the class. + /// + /// Content types this endpoint produces. + public AcceptsFileAttribute(params string[] contentTypes) + { + _contentTypes = contentTypes; + } + + /// + /// Gets the configured content types. + /// + /// the configured content types. + public string[] GetContentTypes() => _contentTypes; + } +} diff --git a/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs new file mode 100644 index 0000000000..001f27409e --- /dev/null +++ b/Jellyfin.Api/Attributes/AcceptsImageFileAttribute.cs @@ -0,0 +1,18 @@ +namespace Jellyfin.Api.Attributes +{ + /// + /// Produces file attribute of "image/*". + /// + public class AcceptsImageFileAttribute : AcceptsFileAttribute + { + private const string ContentType = "image/*"; + + /// + /// Initializes a new instance of the class. + /// + public AcceptsImageFileAttribute() + : base(ContentType) + { + } + } +} diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index c606d327c5..dc36349704 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -87,6 +87,7 @@ namespace Jellyfin.Api.Controllers /// A . [HttpPost("Users/{userId}/Images/{imageType}")] [Authorize(Policy = Policies.DefaultAuthorization)] + [AcceptsImageFile] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")] @@ -133,6 +134,7 @@ namespace Jellyfin.Api.Controllers /// A . [HttpPost("Users/{userId}/Images/{imageType}/{index}")] [Authorize(Policy = Policies.DefaultAuthorization)] + [AcceptsImageFile] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageType", Justification = "Imported from ServiceStack")] @@ -312,6 +314,7 @@ namespace Jellyfin.Api.Controllers /// A on success, or a if item not found. [HttpPost("Items/{itemId}/Images/{imageType}")] [Authorize(Policy = Policies.RequiresElevation)] + [AcceptsImageFile] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] @@ -346,6 +349,7 @@ namespace Jellyfin.Api.Controllers /// A on success, or a if item not found. [HttpPost("Items/{itemId}/Images/{imageType}/{imageIndex}")] [Authorize(Policy = Policies.RequiresElevation)] + [AcceptsImageFile] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")] diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index da4cc267b3..545937207c 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -316,6 +316,7 @@ namespace Jellyfin.Server.Extensions c.OperationFilter(); c.OperationFilter(); + c.OperationFilter(); c.OperationFilter(); c.DocumentFilter(); }); diff --git a/Jellyfin.Server/Filters/FileRequestFilter.cs b/Jellyfin.Server/Filters/FileRequestFilter.cs new file mode 100644 index 0000000000..69e10994f4 --- /dev/null +++ b/Jellyfin.Server/Filters/FileRequestFilter.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using Jellyfin.Api.Attributes; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Jellyfin.Server.Filters +{ + /// + public class FileRequestFilter : IOperationFilter + { + /// + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + foreach (var attribute in context.ApiDescription.ActionDescriptor.EndpointMetadata) + { + if (attribute is AcceptsFileAttribute acceptsFileAttribute) + { + operation.RequestBody = GetRequestBody(acceptsFileAttribute.GetContentTypes()); + break; + } + } + } + + private static OpenApiRequestBody GetRequestBody(IEnumerable contentTypes) + { + var body = new OpenApiRequestBody(); + var mediaType = new OpenApiMediaType + { + Schema = new OpenApiSchema + { + Type = "string", + Format = "binary" + } + }; + foreach (var contentType in contentTypes) + { + body.Content.Add(contentType, mediaType); + } + + return body; + } + } +} From 223b42aed3395f7d01ea513bf352cdf4fd3e7002 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 10 Feb 2021 17:09:23 -0700 Subject: [PATCH 1079/1930] Create BaseItemKind enum --- Emby.Server.Implementations/Dto/DtoService.cs | 4 +- Jellyfin.Api/Controllers/ArtistsController.cs | 18 +- .../Controllers/CollectionController.cs | 1 - .../Controllers/DashboardController.cs | 6 - .../Controllers/DynamicHlsController.cs | 1 - Jellyfin.Api/Controllers/FilterController.cs | 37 ++-- Jellyfin.Api/Controllers/GenresController.cs | 9 +- .../Controllers/HlsSegmentController.cs | 2 - .../Controllers/InstantMixController.cs | 1 - .../Controllers/ItemLookupController.cs | 2 - Jellyfin.Api/Controllers/ItemsController.cs | 27 ++- Jellyfin.Api/Controllers/LibraryController.cs | 1 - .../Controllers/MusicGenresController.cs | 9 +- Jellyfin.Api/Controllers/PackageController.cs | 1 - Jellyfin.Api/Controllers/PersonsController.cs | 1 - .../Controllers/PlaylistsController.cs | 1 - Jellyfin.Api/Controllers/PluginsController.cs | 2 - Jellyfin.Api/Controllers/SearchController.cs | 9 +- Jellyfin.Api/Controllers/StudiosController.cs | 9 +- .../Controllers/SuggestionsController.cs | 1 - .../Controllers/SyncPlayController.cs | 1 - Jellyfin.Api/Controllers/SystemController.cs | 1 - .../Controllers/TimeSyncController.cs | 1 - .../Controllers/TrailersController.cs | 4 +- Jellyfin.Api/Controllers/TvShowsController.cs | 1 - .../Controllers/UserLibraryController.cs | 5 +- .../Controllers/UserViewsController.cs | 1 - .../Controllers/VideoHlsController.cs | 1 - Jellyfin.Api/Controllers/YearsController.cs | 15 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 16 ++ Jellyfin.Data/Enums/BaseItemKind.cs | 190 ++++++++++++++++++ MediaBrowser.Controller/Entities/BaseItem.cs | 5 + MediaBrowser.Model/Dto/BaseItemDto.cs | 3 +- 33 files changed, 289 insertions(+), 97 deletions(-) create mode 100644 Jellyfin.Data/Enums/BaseItemKind.cs diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index e3ab0d6eab..54b18a8c80 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -249,7 +249,7 @@ namespace Emby.Server.Implementations.Dto var activeRecording = liveTvManager.GetActiveRecordingInfo(item.Path); if (activeRecording != null) { - dto.Type = "Recording"; + dto.Type = BaseItemKind.Recording; dto.CanDownload = false; dto.RunTimeTicks = null; @@ -904,7 +904,7 @@ namespace Emby.Server.Implementations.Dto } } - dto.Type = item.GetClientTypeName(); + dto.Type = item.GetBaseItemKind(); if ((item.CommunityRating ?? 0) > 0) { dto.CommunityRating = item.CommunityRating; diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index fed7ed3e5a..4b2e5e7ea6 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -3,8 +3,10 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; +using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -88,8 +90,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, @@ -127,8 +129,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), MediaTypes = mediaTypes, StartIndex = startIndex, Limit = limit, @@ -287,8 +289,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, @@ -326,8 +328,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), MediaTypes = mediaTypes, StartIndex = startIndex, Limit = limit, diff --git a/Jellyfin.Api/Controllers/CollectionController.cs b/Jellyfin.Api/Controllers/CollectionController.cs index 2a7b2b5c62..852d1e9cbd 100644 --- a/Jellyfin.Api/Controllers/CollectionController.cs +++ b/Jellyfin.Api/Controllers/CollectionController.cs @@ -3,7 +3,6 @@ using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index ff7895373b..b2baa9cea0 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -7,17 +7,11 @@ using Jellyfin.Api.Attributes; using Jellyfin.Api.Models; using MediaBrowser.Common.Plugins; using MediaBrowser.Controller; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Extensions; -using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Net; using MediaBrowser.Model.Plugins; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Microsoft.Net.Http.Headers; namespace Jellyfin.Api.Controllers { diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 6e85737d26..e375645cf0 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -15,7 +15,6 @@ using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index 9220b988fa..223b2a2b66 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -1,13 +1,12 @@ using System; using System.Linq; using Jellyfin.Api.Constants; +using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; @@ -51,7 +50,7 @@ namespace Jellyfin.Api.Controllers public ActionResult GetQueryFiltersLegacy( [FromQuery] Guid? userId, [FromQuery] Guid? parentId, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes) { var user = userId.HasValue && !userId.Equals(Guid.Empty) @@ -60,10 +59,10 @@ namespace Jellyfin.Api.Controllers BaseItem? item = null; if (includeItemTypes.Length != 1 - || !(string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) + || !(includeItemTypes[0] == BaseItemKind.BoxSet + || includeItemTypes[0] == BaseItemKind.Playlist + || includeItemTypes[0] == BaseItemKind.Trailer + || includeItemTypes[0] == BaseItemKind.Program)) { item = _libraryManager.GetParentItem(parentId, user?.Id); } @@ -72,7 +71,7 @@ namespace Jellyfin.Api.Controllers { User = user, MediaTypes = mediaTypes, - IncludeItemTypes = includeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), Recursive = true, EnableTotalRecordCount = false, DtoOptions = new DtoOptions @@ -137,7 +136,7 @@ namespace Jellyfin.Api.Controllers public ActionResult GetQueryFilters( [FromQuery] Guid? userId, [FromQuery] Guid? parentId, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool? isAiring, [FromQuery] bool? isMovie, [FromQuery] bool? isSports, @@ -152,10 +151,10 @@ namespace Jellyfin.Api.Controllers BaseItem? parentItem = null; if (includeItemTypes.Length == 1 - && (string.Equals(includeItemTypes[0], nameof(BoxSet), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Playlist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Trailer), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], "Program", StringComparison.OrdinalIgnoreCase))) + && (includeItemTypes[0] == BaseItemKind.BoxSet + || includeItemTypes[0] == BaseItemKind.Playlist + || includeItemTypes[0] == BaseItemKind.Trailer + || includeItemTypes[0] == BaseItemKind.Program)) { parentItem = null; } @@ -167,7 +166,7 @@ namespace Jellyfin.Api.Controllers var filters = new QueryFilters(); var genreQuery = new InternalItemsQuery(user) { - IncludeItemTypes = includeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), DtoOptions = new DtoOptions { Fields = Array.Empty(), @@ -192,10 +191,10 @@ namespace Jellyfin.Api.Controllers } if (includeItemTypes.Length == 1 - && (string.Equals(includeItemTypes[0], nameof(MusicAlbum), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(MusicVideo), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(MusicArtist), StringComparison.OrdinalIgnoreCase) - || string.Equals(includeItemTypes[0], nameof(Audio), StringComparison.OrdinalIgnoreCase))) + && (includeItemTypes[0] == BaseItemKind.MusicAlbum + || includeItemTypes[0] == BaseItemKind.MusicVideo + || includeItemTypes[0] == BaseItemKind.MusicArtist + || includeItemTypes[0] == BaseItemKind.Audio)) { filters.Genres = _libraryManager.GetMusicGenres(genreQuery).Items.Select(i => new NameGuidPair { diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index b6755ed5e5..7bcf4674c6 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -6,6 +6,7 @@ using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -74,8 +75,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -96,8 +97,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index f519877326..25abe73ed0 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -2,13 +2,11 @@ using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index 2446257528..f061755c30 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.ModelBinders; diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index 6c38f77ce1..dfc68ffcec 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -2,8 +2,6 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; -using System.Linq; -using System.Net.Mime; using System.Text.Json; using System.Threading; using System.Threading.Tasks; diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 7d77474958..2c9760f6d0 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -1,6 +1,5 @@ using System; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; @@ -178,8 +177,8 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, @@ -233,8 +232,8 @@ namespace Jellyfin.Api.Controllers .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); if (includeItemTypes.Length == 1 - && (includeItemTypes[0].Equals("Playlist", StringComparison.OrdinalIgnoreCase) - || includeItemTypes[0].Equals("BoxSet", StringComparison.OrdinalIgnoreCase))) + && (includeItemTypes[0] == BaseItemKind.Playlist + || includeItemTypes[0] == BaseItemKind.BoxSet)) { parentId = null; } @@ -251,7 +250,7 @@ namespace Jellyfin.Api.Controllers && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase)) { recursive = true; - includeItemTypes = new[] { "Playlist" }; + includeItemTypes = new[] { BaseItemKind.Playlist }; } var enabledChannels = user!.GetPreferenceValues(PreferenceKind.EnabledChannels); @@ -286,8 +285,8 @@ namespace Jellyfin.Api.Controllers { IsPlayed = isPlayed, MediaTypes = mediaTypes, - IncludeItemTypes = includeItemTypes, - ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), Recursive = recursive ?? false, OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder), IsFavorite = isFavorite, @@ -611,8 +610,8 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, @@ -773,8 +772,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { @@ -810,8 +809,8 @@ namespace Jellyfin.Api.Controllers CollapseBoxSetItems = false, EnableTotalRecordCount = enableTotalRecordCount, AncestorIds = ancestorIds, - IncludeItemTypes = includeItemTypes, - ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), SearchTerm = searchTerm }); diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 28d359ac3a..db4aa96681 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.LibraryDtos; using Jellyfin.Data.Entities; diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 2608a9cd09..7f7058b5ef 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -6,6 +6,7 @@ using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; @@ -74,8 +75,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, @@ -96,8 +97,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, diff --git a/Jellyfin.Api/Controllers/PackageController.cs b/Jellyfin.Api/Controllers/PackageController.cs index c589f54ac4..5dd49ef2fd 100644 --- a/Jellyfin.Api/Controllers/PackageController.cs +++ b/Jellyfin.Api/Controllers/PackageController.cs @@ -4,7 +4,6 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Jellyfin.Api.Constants; -using MediaBrowser.Common.Json; using MediaBrowser.Common.Updates; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Updates; diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 17e631197c..70a94e27cb 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -3,7 +3,6 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Controllers/PlaylistsController.cs b/Jellyfin.Api/Controllers/PlaylistsController.cs index a55e4ad2ff..1667d6edee 100644 --- a/Jellyfin.Api/Controllers/PlaylistsController.cs +++ b/Jellyfin.Api/Controllers/PlaylistsController.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.PlaylistDtos; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index b73611c979..b2e8bee91e 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -1,10 +1,8 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.IO; using System.Linq; -using System.Net.Mime; using System.Text.Json; using System.Threading.Tasks; using Jellyfin.Api.Attributes; diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs index 08255ff8f6..6c22050a79 100644 --- a/Jellyfin.Api/Controllers/SearchController.cs +++ b/Jellyfin.Api/Controllers/SearchController.cs @@ -6,6 +6,7 @@ using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -83,8 +84,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? limit, [FromQuery] Guid? userId, [FromQuery, Required] string searchTerm, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery] Guid? parentId, [FromQuery] bool? isMovie, @@ -109,8 +110,8 @@ namespace Jellyfin.Api.Controllers IncludeStudios = includeStudios, StartIndex = startIndex, UserId = userId ?? Guid.Empty, - IncludeItemTypes = includeItemTypes, - ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), MediaTypes = mediaTypes, ParentId = parentId, diff --git a/Jellyfin.Api/Controllers/StudiosController.cs b/Jellyfin.Api/Controllers/StudiosController.cs index bb54c59f69..da8f8b1995 100644 --- a/Jellyfin.Api/Controllers/StudiosController.cs +++ b/Jellyfin.Api/Controllers/StudiosController.cs @@ -5,6 +5,7 @@ using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -73,8 +74,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? searchTerm, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool? isFavorite, [FromQuery] bool? enableUserData, [FromQuery] int? imageTypeLimit, @@ -96,8 +97,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), StartIndex = startIndex, Limit = limit, IsFavorite = isFavorite, diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index 9f1dec712a..a55f13e66e 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -3,7 +3,6 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Controllers/SyncPlayController.cs b/Jellyfin.Api/Controllers/SyncPlayController.cs index 82cbe58df2..f878f2329c 100644 --- a/Jellyfin.Api/Controllers/SyncPlayController.cs +++ b/Jellyfin.Api/Controllers/SyncPlayController.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading; diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index e67a27ae30..bbbe5fb8da 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -5,7 +5,6 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Mime; -using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; diff --git a/Jellyfin.Api/Controllers/TimeSyncController.cs b/Jellyfin.Api/Controllers/TimeSyncController.cs index c730ac12b3..7df51c7afb 100644 --- a/Jellyfin.Api/Controllers/TimeSyncController.cs +++ b/Jellyfin.Api/Controllers/TimeSyncController.cs @@ -1,5 +1,4 @@ using System; -using System.Globalization; using MediaBrowser.Model.SyncPlay; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; diff --git a/Jellyfin.Api/Controllers/TrailersController.cs b/Jellyfin.Api/Controllers/TrailersController.cs index 242b8f068e..dd3836551b 100644 --- a/Jellyfin.Api/Controllers/TrailersController.cs +++ b/Jellyfin.Api/Controllers/TrailersController.cs @@ -148,7 +148,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters, [FromQuery] bool? isFavorite, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, @@ -194,7 +194,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool? enableImages = true) { - var includeItemTypes = new[] { "Trailer" }; + var includeItemTypes = new[] { BaseItemKind.Trailer }; return _itemsController .GetItems( diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 223f588593..e1c67f8307 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.Globalization; using System.Linq; using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; diff --git a/Jellyfin.Api/Controllers/UserLibraryController.cs b/Jellyfin.Api/Controllers/UserLibraryController.cs index 0e65591cce..1d70406acc 100644 --- a/Jellyfin.Api/Controllers/UserLibraryController.cs +++ b/Jellyfin.Api/Controllers/UserLibraryController.cs @@ -8,6 +8,7 @@ using Jellyfin.Api.Constants; using Jellyfin.Api.Extensions; using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; +using Jellyfin.Data.Enums; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; @@ -269,7 +270,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid userId, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery] bool? isPlayed, [FromQuery] bool? enableImages, [FromQuery] int? imageTypeLimit, @@ -296,7 +297,7 @@ namespace Jellyfin.Api.Controllers new LatestItemsQuery { GroupItems = groupItems, - IncludeItemTypes = includeItemTypes, + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), IsPlayed = isPlayed, Limit = limit, ParentId = parentId ?? Guid.Empty, diff --git a/Jellyfin.Api/Controllers/UserViewsController.cs b/Jellyfin.Api/Controllers/UserViewsController.cs index e1483ce9d5..7bc5ecdf1d 100644 --- a/Jellyfin.Api/Controllers/UserViewsController.cs +++ b/Jellyfin.Api/Controllers/UserViewsController.cs @@ -4,7 +4,6 @@ using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using Jellyfin.Api.Extensions; -using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Api.Models.UserViewDtos; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 7e743ee0c7..ba51aa43e2 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -12,7 +12,6 @@ using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.PlaybackDtos; using Jellyfin.Api.Models.StreamingDtos; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Dlna; diff --git a/Jellyfin.Api/Controllers/YearsController.cs b/Jellyfin.Api/Controllers/YearsController.cs index 7c27752f7f..d6dc6650cf 100644 --- a/Jellyfin.Api/Controllers/YearsController.cs +++ b/Jellyfin.Api/Controllers/YearsController.cs @@ -74,8 +74,8 @@ namespace Jellyfin.Api.Controllers [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] Guid? parentId, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] excludeItemTypes, - [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] includeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, [FromQuery] bool? enableUserData, @@ -101,8 +101,8 @@ namespace Jellyfin.Api.Controllers var query = new InternalItemsQuery(user) { - ExcludeItemTypes = excludeItemTypes, - IncludeItemTypes = includeItemTypes, + ExcludeItemTypes = RequestHelpers.GetItemTypeStrings(excludeItemTypes), + IncludeItemTypes = RequestHelpers.GetItemTypeStrings(includeItemTypes), MediaTypes = mediaTypes, DtoOptions = dtoOptions }; @@ -193,16 +193,17 @@ namespace Jellyfin.Api.Controllers return _dtoService.GetBaseItemDto(item, dtoOptions); } - private bool FilterItem(BaseItem f, IReadOnlyCollection excludeItemTypes, IReadOnlyCollection includeItemTypes, IReadOnlyCollection mediaTypes) + private bool FilterItem(BaseItem f, IReadOnlyCollection excludeItemTypes, IReadOnlyCollection includeItemTypes, IReadOnlyCollection mediaTypes) { + var baseItemKind = f.GetBaseItemKind(); // Exclude item types - if (excludeItemTypes.Count > 0 && excludeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) + if (excludeItemTypes.Count > 0 && excludeItemTypes.Contains(baseItemKind)) { return false; } // Include item types - if (includeItemTypes.Count > 0 && !includeItemTypes.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase)) + if (includeItemTypes.Count > 0 && !includeItemTypes.Contains(baseItemKind)) { return false; } diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index db0ccc6577..94856e03ed 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -129,5 +129,21 @@ namespace Jellyfin.Api.Helpers TotalRecordCount = result.TotalRecordCount }; } + + internal static string[] GetItemTypeStrings(IReadOnlyList itemKinds) + { + if (itemKinds.Count == 0) + { + return Array.Empty(); + } + + var itemTypes = new string[itemKinds.Count]; + for (var i = 0; i < itemKinds.Count; i++) + { + itemTypes[i] = itemKinds[i].ToString(); + } + + return itemTypes; + } } } diff --git a/Jellyfin.Data/Enums/BaseItemKind.cs b/Jellyfin.Data/Enums/BaseItemKind.cs new file mode 100644 index 0000000000..aac30279ed --- /dev/null +++ b/Jellyfin.Data/Enums/BaseItemKind.cs @@ -0,0 +1,190 @@ +namespace Jellyfin.Data.Enums +{ + /// + /// The base item kind. + /// + /// + /// This enum is generated from all classes that inherit from BaseItem. + /// + public enum BaseItemKind + { + /// + /// Item is aggregate folder. + /// + AggregateFolder, + + /// + /// Item is audio. + /// + Audio, + + /// + /// Item is audio book. + /// + AudioBook, + + /// + /// Item is base plugin folder. + /// + BasePluginFolder, + + /// + /// Item is book. + /// + Book, + + /// + /// Item is box set. + /// + BoxSet, + + /// + /// Item is channel. + /// + Channel, + + /// + /// Item is channel folder item. + /// + ChannelFolderItem, + + /// + /// Item is collection folder. + /// + CollectionFolder, + + /// + /// Item is episode. + /// + Episode, + + /// + /// Item is folder. + /// + Folder, + + /// + /// Item is genre. + /// + Genre, + + /// + /// Item is manual playlists folder. + /// + ManualPlaylistsFolder, + + /// + /// Item is movie. + /// + Movie, + + /// + /// Item is music album. + /// + MusicAlbum, + + /// + /// Item is music artist. + /// + MusicArtist, + + /// + /// Item is music genre. + /// + MusicGenre, + + /// + /// Item is music video. + /// + MusicVideo, + + /// + /// Item is person. + /// + Person, + + /// + /// Item is photo. + /// + Photo, + + /// + /// Item is photo album. + /// + PhotoAlbum, + + /// + /// Item is playlist. + /// + Playlist, + + /// + /// Item is program + /// + Program, + + /// + /// Item is recording. + /// + /// + /// Manually added. + /// + Recording, + + /// + /// Item is season. + /// + Season, + + /// + /// Item is series. + /// + Series, + + /// + /// Item is studio. + /// + Studio, + + /// + /// Item is trailer. + /// + Trailer, + + /// + /// Item is live tv channel. + /// + /// + /// Type is overridden. + /// + TvChannel, + + /// + /// Item is live tv program. + /// + /// + /// Type is overridden. + /// + TvProgram, + + /// + /// Item is user root folder. + /// + UserRootFolder, + + /// + /// Item is user view. + /// + UserView, + + /// + /// Item is video. + /// + Video, + + /// + /// Item is year. + /// + Year + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index cbb02aabd7..7598b29e6e 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1998,6 +1998,11 @@ namespace MediaBrowser.Controller.Entities return GetType().Name; } + public BaseItemKind GetBaseItemKind() + { + return Enum.Parse(GetClientTypeName()); + } + /// /// Gets the linked child. /// diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs index 3f7aac9cd8..2f9f9d3cdb 100644 --- a/MediaBrowser.Model/Dto/BaseItemDto.cs +++ b/MediaBrowser.Model/Dto/BaseItemDto.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Jellyfin.Data.Enums; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Library; @@ -276,7 +277,7 @@ namespace MediaBrowser.Model.Dto /// Gets or sets the type. /// /// The type. - public string Type { get; set; } + public BaseItemKind Type { get; set; } /// /// Gets or sets the people. From d490c1c2bcb2852c9159e8578bc7a60e086e4202 Mon Sep 17 00:00:00 2001 From: Manjot Singh Date: Thu, 11 Feb 2021 06:16:43 +0000 Subject: [PATCH 1080/1930] Translated using Weblate (Hindi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hi/ --- Emby.Server.Implementations/Localization/Core/hi.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index b9e5f301d9..ef3697b15f 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -1,5 +1,5 @@ { - "Albums": "संग्रह", + "Albums": "एल्बम", "HeaderRecordingGroups": "रिकॉर्डिंग समूह", "HeaderNextUp": "इसके बाद", "HeaderLiveTV": "लाइव टीवी", @@ -26,7 +26,7 @@ "AuthenticationSucceededWithUserName": "सफलता से प्रमाणीकृत", "Artists": "कलाकारों", "Application": "एप्लिकेशन", - "AppDeviceValues": "एप: {0}, मशीन: {1}", + "AppDeviceValues": "एप: {0}, उपकरण: {1}", "NotificationOptionPluginUninstalled": "प्लगइन अनइंस्टाल हो गया", "NotificationOptionPluginInstalled": "प्लगइन इनस्टॉल हो गया", "NotificationOptionPluginError": "प्लगइन फ़ैल हो गया", From dc2f8b5e6b01e4bf47aa47f8833e27aa3a47d2b6 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Thu, 11 Feb 2021 12:43:36 +0100 Subject: [PATCH 1081/1930] Fix xml loop --- .../Parsers/BaseNfoParser.cs | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 34861c463b..56c546475a 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -377,9 +377,11 @@ namespace MediaBrowser.XbmcMetadata.Parsers case "watched": { + var val = reader.ReadElementContentAsBoolean(); + if (userData != null) { - userData.Played = reader.ReadElementContentAsBoolean(); + userData.Played = val; } break; @@ -387,9 +389,13 @@ namespace MediaBrowser.XbmcMetadata.Parsers case "playcount": { - if (userData != null) + var val = reader.ReadElementContentAsString(); + if (!string.IsNullOrWhiteSpace(val) && userData != null) { - userData.PlayCount = reader.ReadElementContentAsInt(); + if (int.TryParse(val.Split(' ')[0], NumberStyles.Integer, UsCulture, out var count)) + { + userData.PlayCount = count; + } } break; @@ -397,20 +403,16 @@ namespace MediaBrowser.XbmcMetadata.Parsers case "lasplayed": { - if (userData != null) + var val = reader.ReadElementContentAsString(); + if (!string.IsNullOrWhiteSpace(val) && userData != null) { - var val = reader.ReadElementContentAsString(); - - if (!string.IsNullOrWhiteSpace(val)) + if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var added)) { - if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var added)) - { - userData.LastPlayedDate = added.ToUniversalTime(); - } - else - { - Logger.LogWarning("Invalid lastplayed value found: {Value}", val); - } + userData.LastPlayedDate = added.ToUniversalTime(); + } + else + { + Logger.LogWarning("Invalid lastplayed value found: {Value}", val); } } From ae57ed4ac70eda1046c86e40e41b9683b2115f59 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Thu, 11 Feb 2021 13:36:35 +0100 Subject: [PATCH 1082/1930] Add nfo user data tests --- .../Parsers/BaseNfoParser.cs | 2 +- .../Parsers/MovieNfoParserTests.cs | 35 +++++++++++++++---- .../Test Data/Justice League.nfo | 5 +-- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 56c546475a..81af1819d9 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -401,7 +401,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } - case "lasplayed": + case "lastplayed": { var val = reader.ReadElementContentAsString(); if (!string.IsNullOrWhiteSpace(val) && userData != null) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 9710d31d85..4d4270a55d 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Threading; +using Jellyfin.Data.Entities; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -18,19 +19,35 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers public class MovieNfoParserTests { private readonly MovieNfoParser _parser; + private readonly IUserDataManager _userDataManager; + private readonly User _testUser; public MovieNfoParserTests() { + _testUser = new User("Test User", "Auth provider", "Reset provider"); + var providerManager = new Mock(); providerManager.Setup(x => x.GetExternalIdInfos(It.IsAny())) .Returns(Enumerable.Empty()); - var config = new Mock(); - config.Setup(x => x.GetConfiguration(It.IsAny())) - .Returns(new XbmcMetadataOptions()); - var user = new Mock(); - var userData = new Mock(); - _parser = new MovieNfoParser(new NullLogger(), config.Object, providerManager.Object, user.Object, userData.Object); + var nfoConfig = new XbmcMetadataOptions() + { + UserId = "F38E6443-090B-4F7A-BD12-9CFF5020F7BC" + }; + var configManager = new Mock(); + configManager.Setup(x => x.GetConfiguration(It.IsAny())) + .Returns(nfoConfig); + + var user = new Mock(); + user.Setup(x => x.GetUserById(It.IsAny())) + .Returns(_testUser); + + var userData = new Mock(); + userData.Setup(x => x.GetUserData(_testUser, It.IsAny())) + .Returns(new UserItemData()); + + _userDataManager = userData.Object; + _parser = new MovieNfoParser(new NullLogger(), configManager.Object, providerManager.Object, user.Object, userData.Object); } [Fact] @@ -91,6 +108,12 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal("Test Lyricist", lyricist!.Name); Assert.Equal(new DateTime(2019, 8, 6, 9, 1, 18), item.DateCreated); + + // userData + var userData = _userDataManager.GetUserData(_testUser, item); + Assert.Equal(2, userData.PlayCount); + Assert.True(userData.Played); + Assert.Equal(new DateTime(2021, 02, 11, 07, 47, 23), userData.LastPlayedDate); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo index 6e6da25d30..98880cdc9e 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo @@ -30,6 +30,9 @@ Fueled by his restored faith in humanity and inspired by Superman's selfless act, Bruce Wayne enlists the help of his newfound ally, Diana Prince, to face an even greater enemy. Together, Batman and Wonder Woman work quickly to find and recruit a team of meta-humans to stand against this newly awakened threat. But despite the formation of this unprecedented league of heroes-Batman, Wonder Woman, Aquaman, Cyborg and The Flash-it may already be too late to save the planet from an assault of catastrophic proportions. Justice for all. 120 + 2 + true + 2021-02-11 07:47:23 https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg https://assets.fanart.tv/fanart/movies/468551/movieposter/justice-league-collection-5c24ea65591d3.jpg https://assets.fanart.tv/fanart/movies/468551/hdmovielogo/justice-league-collection-5ba855ed4239a.png @@ -81,8 +84,6 @@ https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a119394ea362.jpg Australia:M - 0 - tt0974015 tt0974015 Action From eaaab10cf3e7ced50c0cb3587d0852b56bd52ead Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Thu, 11 Feb 2021 14:15:11 +0100 Subject: [PATCH 1083/1930] Don't split playcount --- MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 8a9e6674ee..6f164caf37 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -392,7 +392,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers var val = reader.ReadElementContentAsString(); if (!string.IsNullOrWhiteSpace(val) && userData != null) { - if (int.TryParse(val.Split(' ')[0], NumberStyles.Integer, UsCulture, out var count)) + if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var count)) { userData.PlayCount = count; } From 97935d2cd2b5b75e6ca515c99f5821045a06a019 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 11 Feb 2021 17:46:27 +0100 Subject: [PATCH 1084/1930] Add tests for RequestHelpers.GetItemTypeStrings --- Jellyfin.Api/Jellyfin.Api.csproj | 6 ++++ .../Helpers/RequestHelpersTests.cs | 34 +++++++++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index c2f4ab522a..ef105fdced 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -38,4 +38,10 @@ ../jellyfin.ruleset + + + <_Parameter1>Jellyfin.Api.Tests + + + diff --git a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs index 606041c7f4..97e441b1dc 100644 --- a/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs +++ b/tests/Jellyfin.Api.Tests/Helpers/RequestHelpersTests.cs @@ -6,11 +6,11 @@ using Xunit; namespace Jellyfin.Api.Tests.Helpers { - public class RequestHelpersTests + public static class RequestHelpersTests { [Theory] [MemberData(nameof(GetOrderBy_Success_TestData))] - public void GetOrderBy_Success(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder, (string, SortOrder)[] expected) + public static void GetOrderBy_Success(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder, (string, SortOrder)[] expected) { Assert.Equal(expected, RequestHelpers.GetOrderBy(sortBy, requestedSortOrder)); } @@ -55,5 +55,35 @@ namespace Jellyfin.Api.Tests.Helpers } }; } + + [Fact] + public static void GetItemTypeStrings_Empty_Empty() + { + Assert.Empty(RequestHelpers.GetItemTypeStrings(Array.Empty())); + } + + [Fact] + public static void GetItemTypeStrings_Valid_Success() + { + BaseItemKind[] input = + { + BaseItemKind.AggregateFolder, + BaseItemKind.Audio, + BaseItemKind.BasePluginFolder, + BaseItemKind.CollectionFolder + }; + + string[] expected = + { + "AggregateFolder", + "Audio", + "BasePluginFolder", + "CollectionFolder" + }; + + var res = RequestHelpers.GetItemTypeStrings(input); + + Assert.Equal(expected, res); + } } } From 9fcdbd4c4b79560cb22f6f27182b4c36606dae79 Mon Sep 17 00:00:00 2001 From: dkanada Date: Fri, 12 Feb 2021 21:58:37 +0900 Subject: [PATCH 1085/1930] remove deprecated settings from server config --- .../Library/Resolvers/Audio/MusicArtistResolver.cs | 5 ----- Jellyfin.Api/Controllers/PluginsController.cs | 4 +--- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 7 ------- 3 files changed, 1 insertion(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index e9e688fa67..60f82806fb 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -79,11 +79,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio return new MusicArtist(); } - if (_config.Configuration.EnableSimpleArtistDetection) - { - return null; - } - // Avoid mis-identifying top folders if (args.Parent.IsRoot) { diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index b2e8bee91e..a5aa9bfcae 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -298,9 +298,7 @@ namespace Jellyfin.Api.Controllers } var imagePath = Path.Combine(plugin.Path, plugin.Manifest.ImagePath ?? string.Empty); - if (((ServerConfiguration)_config.CommonConfiguration).DisablePluginImages - || plugin.Manifest.ImagePath == null - || !System.IO.File.Exists(imagePath)) + if (plugin.Manifest.ImagePath == null || !System.IO.File.Exists(imagePath)) { return NotFound(); } diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 0f0ad0f9aa..ba55a2ace6 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -418,8 +418,6 @@ namespace MediaBrowser.Model.Configuration public PathSubstitution[] PathSubstitutions { get; set; } = Array.Empty(); - public bool EnableSimpleArtistDetection { get; set; } = false; - public string[] UninstalledPlugins { get; set; } = Array.Empty(); /// @@ -461,10 +459,5 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets a value indicating whether older plugins should automatically be deleted from the plugin folder. /// public bool RemoveOldPlugins { get; set; } - - /// - /// Gets or sets a value indicating whether plugin image should be disabled. - /// - public bool DisablePluginImages { get; set; } } } From 57091d2854013cdc7af90fb1bae19cb6d02c8b20 Mon Sep 17 00:00:00 2001 From: dkanada Date: Fri, 12 Feb 2021 22:25:43 +0900 Subject: [PATCH 1086/1930] rename the solution file --- MediaBrowser.sln => Jellyfin.sln | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename MediaBrowser.sln => Jellyfin.sln (100%) diff --git a/MediaBrowser.sln b/Jellyfin.sln similarity index 100% rename from MediaBrowser.sln rename to Jellyfin.sln From 9caf3119257544d6fb8fd3e1f1cb2b50eba7bd39 Mon Sep 17 00:00:00 2001 From: dkanada Date: Fri, 12 Feb 2021 22:33:10 +0900 Subject: [PATCH 1087/1930] handle plugin manifests automatically --- .../Plugins/PluginManager.cs | 56 +++++++++++++------ .../Updates/InstallationManager.cs | 22 ++------ MediaBrowser.Common/Plugins/IPluginManager.cs | 10 ++++ .../Updates/InstallationInfo.cs | 7 +++ 4 files changed, 61 insertions(+), 34 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index c26ccfd886..696133c9f0 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -1,12 +1,13 @@ #nullable enable + using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net; using System.Reflection; using System.Text; using System.Text.Json; -using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; @@ -14,6 +15,7 @@ using MediaBrowser.Common.Json.Converters; using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Updates; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -332,34 +334,54 @@ namespace Emby.Server.Implementations.Plugins ChangePluginState(plugin, PluginStatus.Malfunctioned); } - /// - /// Saves the manifest back to disk. - /// - /// The to save. - /// The path where to save the manifest. - /// True if successful. + /// public bool SaveManifest(PluginManifest manifest, string path) { - if (manifest == null) - { - return false; - } - try { var data = JsonSerializer.Serialize(manifest, _jsonOptions); File.WriteAllText(Path.Combine(path, "meta.json"), data); return true; } -#pragma warning disable CA1031 // Do not catch general exception types - catch (Exception e) -#pragma warning restore CA1031 // Do not catch general exception types + catch (ArgumentException e) { - _logger.LogWarning(e, "Unable to save plugin manifest. {Path}", path); + _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path); return false; } } + /// + public bool GenerateManifest(PackageInfo packageInfo, Version version, string path) + { + var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString()); + var url = packageInfo.ImageUrl ?? string.Empty; + var imageFilename = url.Substring(url.LastIndexOf('/') + 1, url.Length); + + using (var client = new WebClient()) + { + client.DownloadFile(url, Path.Join(path, imageFilename)); + } + + var manifest = new PluginManifest + { + Category = packageInfo.Category, + Changelog = versionInfo.Changelog ?? string.Empty, + Description = packageInfo.Description, + Id = new Guid(packageInfo.Id), + Name = packageInfo.Name, + Overview = packageInfo.Overview, + Owner = packageInfo.Owner, + TargetAbi = versionInfo.TargetAbi ?? string.Empty, + Timestamp = DateTime.Parse(versionInfo.Timestamp ?? string.Empty), + Version = versionInfo.Version, + Status = PluginStatus.Active, + AutoUpdate = true, + ImagePath = Path.Join(path, imageFilename) + }; + + return SaveManifest(manifest, path); + } + /// /// Changes a plugin's load status. /// @@ -410,7 +432,7 @@ namespace Emby.Server.Implementations.Plugins if (plugin == null) { // Create a dummy record for the providers. - // TODO: remove this code, if all provided have been released as separate plugins. + // TODO: remove this code once all provided have been released as separate plugins. plugin = new LocalPlugin( instance.AssemblyFilePath, true, diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index abcb4313f3..534c0aa4b8 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -192,17 +192,12 @@ namespace Emby.Server.Implementations.Updates var version = package.Versions[i]; var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber); - // Update the manifests, if anything changes. if (plugin != null) { - if (!string.Equals(plugin.Manifest.TargetAbi, version.TargetAbi, StringComparison.Ordinal)) - { - plugin.Manifest.TargetAbi = version.TargetAbi ?? string.Empty; - _pluginManager.SaveManifest(plugin.Manifest, plugin.Path); - } + _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path); } - // Remove versions with a target abi that is greater then the current application version. + // Remove versions with a target ABI greater then the current application version. if (Version.TryParse(version.TargetAbi, out var targetAbi) && _applicationHost.ApplicationVersion < targetAbi) { package.Versions.RemoveAt(i); @@ -294,7 +289,8 @@ namespace Emby.Server.Implementations.Updates Name = package.Name, Version = v.VersionNumber, SourceUrl = v.SourceUrl, - Checksum = v.Checksum + Checksum = v.Checksum, + PackageInfo = package }; } } @@ -571,24 +567,16 @@ namespace Emby.Server.Implementations.Updates stream.Position = 0; _zipClient.ExtractAllFromZip(stream, targetDir, true); + _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir); _pluginManager.ImportPluginFrom(targetDir); } private async Task InstallPackageInternal(InstallationInfo package, CancellationToken cancellationToken) { - // Set last update time if we were installed before LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version)) ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version)); - if (plugin != null) - { - plugin.Manifest.Timestamp = DateTime.UtcNow; - _pluginManager.SaveManifest(plugin.Manifest, plugin.Path); - } - // Do the install await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); - - // Do plugin-specific processing _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version); return plugin != null; diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index 3da34d8bb3..6f0a0fbfc8 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; +using MediaBrowser.Model.Updates; using Microsoft.Extensions.DependencyInjection; namespace MediaBrowser.Common.Plugins @@ -44,6 +45,15 @@ namespace MediaBrowser.Common.Plugins /// True if successful. bool SaveManifest(PluginManifest manifest, string path); + /// + /// Generates a manifest from repository data. + /// + /// The used to generate a manifest. + /// Version to be installed. + /// The path where to save the manifest. + /// True if successful. + bool GenerateManifest(PackageInfo packageInfo, Version version, string path); + /// /// Imports plugin details from a folder. /// diff --git a/MediaBrowser.Model/Updates/InstallationInfo.cs b/MediaBrowser.Model/Updates/InstallationInfo.cs index eebe1a9034..cc600de9de 100644 --- a/MediaBrowser.Model/Updates/InstallationInfo.cs +++ b/MediaBrowser.Model/Updates/InstallationInfo.cs @@ -1,4 +1,5 @@ #nullable disable + using System; using System.Text.Json.Serialization; @@ -45,5 +46,11 @@ namespace MediaBrowser.Model.Updates /// /// The checksum. public string Checksum { get; set; } + + /// + /// Gets or sets package information for the installation. + /// + /// The package information. + public PackageInfo PackageInfo { get; set; } } } From 3a9fcb6abd249759bd44b2fbcf437beee8f611c2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 12 Feb 2021 17:34:51 +0100 Subject: [PATCH 1088/1930] Rewrite packet writing code for HdHomerun --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 243 +++++------------- MediaBrowser.Common/Crc32.cs | 89 +++++++ tests/Jellyfin.Common.Tests/Crc32Tests.cs | 23 ++ .../LiveTv/HdHomerunManagerTests.cs | 39 +++ 4 files changed, 211 insertions(+), 183 deletions(-) create mode 100644 MediaBrowser.Common/Crc32.cs create mode 100644 tests/Jellyfin.Common.Tests/Crc32Tests.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index f09338330f..188eca1580 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -2,6 +2,7 @@ using System; using System.Buffers; +using System.Buffers.Binary; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -10,6 +11,7 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common; using MediaBrowser.Controller.LiveTv; namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun @@ -120,13 +122,13 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun private static async Task CheckTunerAvailability(NetworkStream stream, int tuner, CancellationToken cancellationToken) { - var lockkeyMsg = CreateGetMessage(tuner, "lockkey"); - await stream.WriteAsync(lockkeyMsg, 0, lockkeyMsg.Length, cancellationToken).ConfigureAwait(false); - byte[] buffer = ArrayPool.Shared.Rent(8192); try { - int receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + var msgLen = WriteGetMessage(buffer, tuner, "lockkey"); + await stream.WriteAsync(buffer.AsMemory(0, msgLen), cancellationToken).ConfigureAwait(false); + + int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); ParseReturnMessage(buffer, receivedBytes, out string returnVal); @@ -166,9 +168,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun _activeTuner = i; var lockKeyString = string.Format(CultureInfo.InvariantCulture, "{0:d}", lockKeyValue); - var lockkeyMsg = CreateSetMessage(i, "lockkey", lockKeyString, null); - await stream.WriteAsync(lockkeyMsg, 0, lockkeyMsg.Length, cancellationToken).ConfigureAwait(false); - int receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + var lockkeyMsgLen = WriteSetMessage(buffer, i, "lockkey", lockKeyString, null); + await stream.WriteAsync(buffer.AsMemory(0, lockkeyMsgLen), cancellationToken).ConfigureAwait(false); + int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked if (!ParseReturnMessage(buffer, receivedBytes, out _)) @@ -178,9 +180,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun foreach (var command in commands.GetCommands()) { - var channelMsg = CreateSetMessage(i, command.Item1, command.Item2, lockKeyValue); - await stream.WriteAsync(channelMsg, 0, channelMsg.Length, cancellationToken).ConfigureAwait(false); - receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + var channelMsgLen = WriteSetMessage(buffer, i, command.Item1, command.Item2, lockKeyValue); + await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false); + receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked if (!ParseReturnMessage(buffer, receivedBytes, out _)) @@ -191,10 +193,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort); - var targetMsg = CreateSetMessage(i, "target", targetValue, lockKeyValue); + var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue); - await stream.WriteAsync(targetMsg, 0, targetMsg.Length, cancellationToken).ConfigureAwait(false); - receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false); + receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked if (!ParseReturnMessage(buffer, receivedBytes, out _)) @@ -232,9 +234,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { foreach (var command in commandList) { - var channelMsg = CreateSetMessage(_activeTuner, command.Item1, command.Item2, _lockkey); - await stream.WriteAsync(channelMsg, 0, channelMsg.Length, cancellationToken).ConfigureAwait(false); - int receivedBytes = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); + var channelMsgLen = WriteSetMessage(buffer, _activeTuner, command.Item1, command.Item2, _lockkey); + await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false); + int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked if (!ParseReturnMessage(buffer, receivedBytes, out _)) @@ -265,17 +267,17 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var stream = client.GetStream(); - var releaseTarget = CreateSetMessage(_activeTuner, "target", "none", lockKeyValue); - await stream.WriteAsync(releaseTarget, 0, releaseTarget.Length).ConfigureAwait(false); - var buffer = ArrayPool.Shared.Rent(8192); try { - await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); - var releaseKeyMsg = CreateSetMessage(_activeTuner, "lockkey", "none", lockKeyValue); + var releaseTargetLen = WriteSetMessage(buffer, _activeTuner, "target", "none", lockKeyValue); + await stream.WriteAsync(buffer.AsMemory(0, releaseTargetLen)).ConfigureAwait(false); + + await stream.ReadAsync(buffer).ConfigureAwait(false); + var releaseKeyMsgLen = WriteSetMessage(buffer, _activeTuner, "lockkey", "none", lockKeyValue); _lockkey = null; - await stream.WriteAsync(releaseKeyMsg, 0, releaseKeyMsg.Length).ConfigureAwait(false); - await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); + await stream.WriteAsync(buffer.AsMemory(0, releaseKeyMsgLen)).ConfigureAwait(false); + await stream.ReadAsync(buffer).ConfigureAwait(false); } finally { @@ -283,105 +285,65 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - private static byte[] CreateGetMessage(int tuner, string name) + internal static int WriteGetMessage(Span buffer, int tuner, string name) { - var byteName = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}\0", tuner, name)); - int messageLength = byteName.Length + 10; // 4 bytes for header + 4 bytes for crc + 2 bytes for tag name and length - - var message = new byte[messageLength]; - - int offset = InsertHeaderAndName(byteName, messageLength, message); - - bool flipEndian = BitConverter.IsLittleEndian; + var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name); + int offset = WriteHeaderAndName(buffer, byteName); // calculate crc and insert at the end of the message - var crcBytes = BitConverter.GetBytes(HdHomerunCrc.GetCrc32(message, messageLength - 4)); - if (flipEndian) - { - Array.Reverse(crcBytes); - } + var crc = Crc32.Compute(buffer.Slice(0, offset)); + BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); - Buffer.BlockCopy(crcBytes, 0, message, offset, 4); - - return message; + return offset + 4; } - private static byte[] CreateSetMessage(int tuner, string name, string value, uint? lockkey) + private static int WriteSetMessage(Span buffer, int tuner, string name, string value, uint? lockkey) { - var byteName = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}\0", tuner, name)); - var byteValue = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}\0", value)); + var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name); + int offset = WriteHeaderAndName(buffer, byteName); + + buffer[offset++] = GetSetValue; + offset += WriteNullTerminatedString(buffer.Slice(offset), value); - int messageLength = byteName.Length + byteValue.Length + 12; if (lockkey.HasValue) { - messageLength += 6; - } - - var message = new byte[messageLength]; - - int offset = InsertHeaderAndName(byteName, messageLength, message); - - bool flipEndian = BitConverter.IsLittleEndian; - - message[offset++] = GetSetValue; - message[offset++] = Convert.ToByte(byteValue.Length); - Buffer.BlockCopy(byteValue, 0, message, offset, byteValue.Length); - offset += byteValue.Length; - if (lockkey.HasValue) - { - message[offset++] = GetSetLockkey; - message[offset++] = 4; - var lockKeyBytes = BitConverter.GetBytes(lockkey.Value); - if (flipEndian) - { - Array.Reverse(lockKeyBytes); - } - - Buffer.BlockCopy(lockKeyBytes, 0, message, offset, 4); + buffer[offset++] = GetSetLockkey; + buffer[offset++] = 4; + BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset), lockkey.Value); offset += 4; } // calculate crc and insert at the end of the message - var crcBytes = BitConverter.GetBytes(HdHomerunCrc.GetCrc32(message, messageLength - 4)); - if (flipEndian) - { - Array.Reverse(crcBytes); - } + var crc = Crc32.Compute(buffer.Slice(0, offset)); + BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); - Buffer.BlockCopy(crcBytes, 0, message, offset, 4); - - return message; + return offset + 4; } - private static int InsertHeaderAndName(byte[] byteName, int messageLength, byte[] message) + internal static int WriteNullTerminatedString(Span buffer, ReadOnlySpan value) { - // check to see if we need to flip endiannes - bool flipEndian = BitConverter.IsLittleEndian; - int offset = 0; + int len = Encoding.UTF8.GetBytes(value, buffer.Slice(1)) + 1; - // create header bytes - var getSetBytes = BitConverter.GetBytes(GetSetRequest); - var msgLenBytes = BitConverter.GetBytes((ushort)(messageLength - 8)); // Subtrace 4 bytes for header and 4 bytes for crc + // Write length in front of value + buffer[0] = Convert.ToByte(len); - if (flipEndian) - { - Array.Reverse(getSetBytes); - Array.Reverse(msgLenBytes); - } + // null-terminate + buffer[len++] = 0; + return len; + } + + private static int WriteHeaderAndName(Span buffer, ReadOnlySpan payload) + { // insert header bytes into message - Buffer.BlockCopy(getSetBytes, 0, message, offset, 2); - offset += 2; - Buffer.BlockCopy(msgLenBytes, 0, message, offset, 2); - offset += 2; + BinaryPrimitives.WriteUInt16BigEndian(buffer, GetSetRequest); + int offset = 2; + // Subtract 4 bytes for header and 4 bytes for crc + BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(offset), (ushort)(payload.Length + 2)); // insert tag name and length - message[offset++] = GetSetName; - message[offset++] = Convert.ToByte(byteName.Length); - - // insert name string - Buffer.BlockCopy(byteName, 0, message, offset, byteName.Length); - offset += byteName.Length; + buffer[offset++] = GetSetName; + offset += WriteNullTerminatedString(buffer.Slice(offset), payload); return offset; } @@ -442,90 +404,5 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun returnVal = Encoding.UTF8.GetString(buf, offset, valueLength - 1); // remove null terminator return true; } - - private static class HdHomerunCrc - { - private static uint[] crc_table = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, - 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, - 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, - 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, - 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, - 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, - 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, - 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, - 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, - 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, - 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, - 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, - 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, - 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, - 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, - 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, - 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, - 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, - 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, - 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, - 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, - 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, - 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, - 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, - 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, - 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, - 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, - 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, - 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, - 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, - 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, - 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, - 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, - 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, - 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; - - public static uint GetCrc32(byte[] bytes, int numBytes) - { - var hash = 0xffffffff; - for (var i = 0; i < numBytes; i++) - { - hash = (hash >> 8) ^ crc_table[(hash ^ bytes[i]) & 0xff]; - } - - var tmp = ~hash & 0xffffffff; - var b0 = tmp & 0xff; - var b1 = (tmp >> 8) & 0xff; - var b2 = (tmp >> 16) & 0xff; - var b3 = (tmp >> 24) & 0xff; - return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; - } - } } } diff --git a/MediaBrowser.Common/Crc32.cs b/MediaBrowser.Common/Crc32.cs new file mode 100644 index 0000000000..599eb4c99a --- /dev/null +++ b/MediaBrowser.Common/Crc32.cs @@ -0,0 +1,89 @@ +#pragma warning disable CS1591 + +using System; + +namespace MediaBrowser.Common +{ + public static class Crc32 + { + private static readonly uint[] _crcTable = + { + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, + 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, + 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, + 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, + 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, + 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, + 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, + 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, + 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, + 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, + 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, + 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, + 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, + 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, + 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, + 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, + 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, + 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, + 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, + 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, + 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, + 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, + 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, + 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, + 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, + 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, + 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d + }; + + public static uint Compute(ReadOnlySpan bytes) + { + var crc = 0xffffffff; + var len = bytes.Length; + for (var i = 0; i < len; i++) + { + crc = (crc >> 8) ^ _crcTable[(bytes[i] ^ crc) & 0xff]; + } + + return ~crc; + } + } +} diff --git a/tests/Jellyfin.Common.Tests/Crc32Tests.cs b/tests/Jellyfin.Common.Tests/Crc32Tests.cs new file mode 100644 index 0000000000..d93fb839c7 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Crc32Tests.cs @@ -0,0 +1,23 @@ +using System; +using System.Text; +using MediaBrowser.Common; +using Xunit; + +namespace Jellyfin.Common.Tests +{ + public static class Crc32Tests + { + [Fact] + public static void Compute_Empty_Zero() + { + Assert.Equal(0, Crc32.Compute(Array.Empty())); + } + + [Theory] + [InlineData(0x414fa339, "The quick brown fox jumps over the lazy dog")] + public static void Compute_Valid_Success(uint expected, string data) + { + Assert.Equal(expected, Crc32.Compute(Encoding.UTF8.GetBytes(data))); + } + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs new file mode 100644 index 0000000000..15cc12d64a --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -0,0 +1,39 @@ +using System; +using Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.LiveTv +{ + public class HdHomerunManagerTests + { + [Fact] + public void WriteNullTerminatedString_Empty_Success() + { + ReadOnlySpan expected = stackalloc byte[] + { + 1, 0 + }; + + Span buffer = stackalloc byte[128]; + int len = HdHomerunManager.WriteNullTerminatedString(buffer, string.Empty); + + Assert.Equal(expected.Length, len); + Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + } + + [Fact] + public void WriteNullTerminatedString_Valid_Success() + { + ReadOnlySpan expected = stackalloc byte[] + { + 10, (byte)'T', (byte)'h', (byte)'e', (byte)' ', (byte)'q', (byte)'u', (byte)'i', (byte)'c', (byte)'k', 0 + }; + + Span buffer = stackalloc byte[128]; + int len = HdHomerunManager.WriteNullTerminatedString(buffer, "The quick"); + + Assert.Equal(expected.Length, len); + Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + } + } +} From e1bc322b709756529759fbb74cb003e133f30ab6 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 12 Feb 2021 18:35:54 +0100 Subject: [PATCH 1089/1930] Add test for WriteGetMessage --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 51 +++++++++++-------- .../LiveTv/HdHomerunManagerTests.cs | 19 +++++++ 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 188eca1580..20a4d87fba 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -288,19 +288,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun internal static int WriteGetMessage(Span buffer, int tuner, string name) { var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name); - int offset = WriteHeaderAndName(buffer, byteName); - - // calculate crc and insert at the end of the message - var crc = Crc32.Compute(buffer.Slice(0, offset)); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); - - return offset + 4; + int offset = WriteHeaderAndPayload(buffer, byteName); + return FinishPacket(buffer, offset); } private static int WriteSetMessage(Span buffer, int tuner, string name, string value, uint? lockkey) { var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name); - int offset = WriteHeaderAndName(buffer, byteName); + int offset = WriteHeaderAndPayload(buffer, byteName); buffer[offset++] = GetSetValue; offset += WriteNullTerminatedString(buffer.Slice(offset), value); @@ -313,17 +308,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun offset += 4; } - // calculate crc and insert at the end of the message - var crc = Crc32.Compute(buffer.Slice(0, offset)); - BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); - - return offset + 4; + return FinishPacket(buffer, offset); } - internal static int WriteNullTerminatedString(Span buffer, ReadOnlySpan value) + internal static int WriteNullTerminatedString(Span buffer, ReadOnlySpan payload) { - int len = Encoding.UTF8.GetBytes(value, buffer.Slice(1)) + 1; + int len = Encoding.UTF8.GetBytes(payload, buffer.Slice(1)) + 1; + // TODO: variable length: this can be 2 bytes if len > 127 // Write length in front of value buffer[0] = Convert.ToByte(len); @@ -333,21 +325,36 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return len; } - private static int WriteHeaderAndName(Span buffer, ReadOnlySpan payload) + private static int WriteHeaderAndPayload(Span buffer, ReadOnlySpan payload) { - // insert header bytes into message + // Packet type BinaryPrimitives.WriteUInt16BigEndian(buffer, GetSetRequest); - int offset = 2; - // Subtract 4 bytes for header and 4 bytes for crc - BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(offset), (ushort)(payload.Length + 2)); - // insert tag name and length + // We write the payload length at the end + int offset = 4; + + // Tag buffer[offset++] = GetSetName; - offset += WriteNullTerminatedString(buffer.Slice(offset), payload); + + // Payload length + data + int strLen = WriteNullTerminatedString(buffer.Slice(offset), payload); + offset += strLen; return offset; } + private static int FinishPacket(Span buffer, int offset) + { + // Payload length + BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(2), (ushort)(offset - 4)); + + // calculate crc and insert at the end of the message + var crc = Crc32.Compute(buffer.Slice(0, offset)); + BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc); + + return offset + 4; + } + private static bool ParseReturnMessage(byte[] buf, int numBytes, out string returnVal) { returnVal = string.Empty; diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index 15cc12d64a..7e04a1ec12 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -35,5 +35,24 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.Equal(expected.Length, len); Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); } + + [Fact] + public void WriteGetMessage_Valid_Success() + { + ReadOnlySpan expected = stackalloc byte[] + { + 0, 4, + 0, 12, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 0xc0, 0xc9, 0x87, 0x33 + }; + + Span buffer = stackalloc byte[128]; + int len = HdHomerunManager.WriteGetMessage(buffer, 0, "N"); + + Assert.Equal(expected.Length, len); + Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + } } } From 0a8587295e85dca553dcb8167b98cc89d4443fa1 Mon Sep 17 00:00:00 2001 From: Dar Donkov Date: Fri, 12 Feb 2021 17:44:59 +0000 Subject: [PATCH 1090/1930] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- .../Localization/Core/bg-BG.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index 7ff30df710..bbc8570894 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -55,26 +55,26 @@ "NotificationOptionPluginInstalled": "Приставката е инсталирана", "NotificationOptionPluginUninstalled": "Приставката е деинсталирана", "NotificationOptionPluginUpdateInstalled": "Обновлението на приставката е инсталирано", - "NotificationOptionServerRestartRequired": "Нужно е повторно пускане на сървъра", + "NotificationOptionServerRestartRequired": "Сървърът трябва да се рестартира", "NotificationOptionTaskFailed": "Грешка в планирана задача", - "NotificationOptionUserLockedOut": "Потребителя е заключен", + "NotificationOptionUserLockedOut": "Потребителят е заключен", "NotificationOptionVideoPlayback": "Възпроизвеждането на видео започна", "NotificationOptionVideoPlaybackStopped": "Възпроизвеждането на видео е спряно", "Photos": "Снимки", "Playlists": "Списъци", "Plugin": "Приставка", - "PluginInstalledWithName": "{0} е инсталирано", - "PluginUninstalledWithName": "{0} е деинсталирано", - "PluginUpdatedWithName": "{0} е обновено", + "PluginInstalledWithName": "{0} е инсталиранa", + "PluginUninstalledWithName": "{0} е деинсталиранa", + "PluginUpdatedWithName": "{0} е обновенa", "ProviderValue": "Доставчик: {0}", "ScheduledTaskFailedWithName": "{0} се провали", "ScheduledTaskStartedWithName": "{0} започна", - "ServerNameNeedsToBeRestarted": "{0} е нужно да се рестартира", + "ServerNameNeedsToBeRestarted": "{0} трябва да се рестартира", "Shows": "Сериали", "Songs": "Песни", "StartupEmbyServerIsLoading": "Сървърът зарежда. Моля, опитайте отново след малко.", "SubtitleDownloadFailureForItem": "Неуспешно изтегляне на субтитри за {0}", - "SubtitleDownloadFailureFromForItem": "Поднадписите за {1} от {0} не можаха да се изтеглят", + "SubtitleDownloadFailureFromForItem": "Субтитрите за {1} от {0} не можаха да бъдат изтеглени", "Sync": "Синхронизиране", "System": "Система", "TvShows": "Телевизионни сериали", From fd7b215c282d53af82ba38ffa8ff7ea1785f4721 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Feb 2021 00:22:58 +0100 Subject: [PATCH 1091/1930] Don't enable case-insensitivity for json by default --- MediaBrowser.Common/Json/JsonDefaults.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 9a2ea68757..2ef24a884a 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -31,7 +31,6 @@ namespace MediaBrowser.Common.Json WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, NumberHandling = JsonNumberHandling.AllowReadingFromString, - PropertyNameCaseInsensitive = true, Converters = { new JsonGuidConverter(), From 65bab55ca09b09f5229d6e9d50f9cfccfeb8f3d0 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Feb 2021 00:39:18 +0100 Subject: [PATCH 1092/1930] Minor improvements --- Emby.Dlna/PlayTo/Device.cs | 2 +- .../AudioBook/AudioBookListResolver.cs | 2 +- .../Data/SqliteExtensions.cs | 6 +- .../Data/SqliteItemRepository.cs | 84 +++++++++---------- .../Data/SqliteUserDataRepository.cs | 2 +- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- .../LiveTv/TunerHosts/M3uParser.cs | 2 +- .../MediaEncoder/EncodingManager.cs | 2 +- .../ScheduledTasks/Tasks/ChapterImagesTask.cs | 2 +- .../Controllers/UniversalAudioController.cs | 4 +- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 4 +- MediaBrowser.Controller/Entities/TV/Series.cs | 2 +- .../MediaEncoding/EncodingHelper.cs | 13 +-- .../Savers/BaseXmlSaver.cs | 2 +- .../Probing/ProbeResultNormalizer.cs | 4 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- MediaBrowser.Model/Dlna/StreamInfo.cs | 14 ++-- MediaBrowser.Model/Entities/MediaStream.cs | 2 +- .../Savers/BaseNfoSaver.cs | 2 +- 20 files changed, 78 insertions(+), 77 deletions(-) diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 938ce5fbf0..9961d15b09 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -990,7 +990,7 @@ namespace Emby.Dlna.PlayTo var deviceProperties = new DeviceInfo() { - Name = string.Join(" ", friendlyNames), + Name = string.Join(' ', friendlyNames), BaseUrl = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", url.Host, url.Port) }; diff --git a/Emby.Naming/AudioBook/AudioBookListResolver.cs b/Emby.Naming/AudioBook/AudioBookListResolver.cs index e9ea9b7a5d..ca53228903 100644 --- a/Emby.Naming/AudioBook/AudioBookListResolver.cs +++ b/Emby.Naming/AudioBook/AudioBookListResolver.cs @@ -73,7 +73,7 @@ namespace Emby.Naming.AudioBook var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber != null || x.PartNumber != null); var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber }); - var nameWithReplacedDots = nameParserResult.Name.Replace(" ", "."); + var nameWithReplacedDots = nameParserResult.Name.Replace(' ', '.'); foreach (var group in groupedBy) { diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index 1af301ceb0..a04d630887 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using SQLitePCL.pretty; @@ -59,7 +60,7 @@ namespace Emby.Server.Implementations.Data connection.RunInTransaction(conn => { - conn.ExecuteAll(string.Join(";", queries)); + conn.ExecuteAll(string.Join(';', queries)); }); } @@ -142,11 +143,10 @@ namespace Emby.Server.Implementations.Data return result[index].ReadGuidFromBlob(); } + [Conditional("DEBUG")] private static void CheckName(string name) { -#if DEBUG throw new ArgumentException("Invalid param name: " + name, nameof(name)); -#endif } public static void TryBind(this IStatement statement, string name, double value) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 6e1f2feae4..dad8bec7b0 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -687,7 +687,7 @@ namespace Emby.Server.Implementations.Data if (item.Genres.Length > 0) { - saveItemStatement.TryBind("@Genres", string.Join("|", item.Genres)); + saveItemStatement.TryBind("@Genres", string.Join('|', item.Genres)); } else { @@ -749,7 +749,7 @@ namespace Emby.Server.Implementations.Data if (item.LockedFields.Length > 0) { - saveItemStatement.TryBind("@LockedFields", string.Join("|", item.LockedFields)); + saveItemStatement.TryBind("@LockedFields", string.Join('|', item.LockedFields)); } else { @@ -758,7 +758,7 @@ namespace Emby.Server.Implementations.Data if (item.Studios.Length > 0) { - saveItemStatement.TryBind("@Studios", string.Join("|", item.Studios)); + saveItemStatement.TryBind("@Studios", string.Join('|', item.Studios)); } else { @@ -785,7 +785,7 @@ namespace Emby.Server.Implementations.Data if (item.Tags.Length > 0) { - saveItemStatement.TryBind("@Tags", string.Join("|", item.Tags)); + saveItemStatement.TryBind("@Tags", string.Join('|', item.Tags)); } else { @@ -807,7 +807,7 @@ namespace Emby.Server.Implementations.Data if (item is Trailer trailer && trailer.TrailerTypes.Length > 0) { - saveItemStatement.TryBind("@TrailerTypes", string.Join("|", trailer.TrailerTypes)); + saveItemStatement.TryBind("@TrailerTypes", string.Join('|', trailer.TrailerTypes)); } else { @@ -902,7 +902,7 @@ namespace Emby.Server.Implementations.Data if (item.ProductionLocations.Length > 0) { - saveItemStatement.TryBind("@ProductionLocations", string.Join("|", item.ProductionLocations)); + saveItemStatement.TryBind("@ProductionLocations", string.Join('|', item.ProductionLocations)); } else { @@ -911,7 +911,7 @@ namespace Emby.Server.Implementations.Data if (item.ExtraIds.Length > 0) { - saveItemStatement.TryBind("@ExtraIds", string.Join("|", item.ExtraIds)); + saveItemStatement.TryBind("@ExtraIds", string.Join('|', item.ExtraIds)); } else { @@ -931,7 +931,7 @@ namespace Emby.Server.Implementations.Data string artists = null; if (item is IHasArtist hasArtists && hasArtists.Artists.Count > 0) { - artists = string.Join("|", hasArtists.Artists); + artists = string.Join('|', hasArtists.Artists); } saveItemStatement.TryBind("@Artists", artists); @@ -940,7 +940,7 @@ namespace Emby.Server.Implementations.Data if (item is IHasAlbumArtist hasAlbumArtists && hasAlbumArtists.AlbumArtists.Count > 0) { - albumArtists = string.Join("|", hasAlbumArtists.AlbumArtists); + albumArtists = string.Join('|', hasAlbumArtists.AlbumArtists); } saveItemStatement.TryBind("@AlbumArtists", albumArtists); @@ -2549,7 +2549,7 @@ namespace Emby.Server.Implementations.Data if (groups.Count > 0) { - return " Group by " + string.Join(",", groups); + return " Group by " + string.Join(',', groups); } return string.Empty; @@ -2578,7 +2578,7 @@ namespace Emby.Server.Implementations.Data } var commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" })) + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" })) + GetFromText() + GetJoinUserDataText(query); @@ -2630,7 +2630,7 @@ namespace Emby.Server.Implementations.Data } var commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, _retriveItemColumns)) + + string.Join(',', GetFinalColumnsToSelect(query, _retriveItemColumns)) + GetFromText() + GetJoinUserDataText(query); @@ -2880,7 +2880,7 @@ namespace Emby.Server.Implementations.Data } var commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, _retriveItemColumns)) + + string.Join(',', GetFinalColumnsToSelect(query, _retriveItemColumns)) + GetFromText() + GetJoinUserDataText(query); @@ -2923,15 +2923,15 @@ namespace Emby.Server.Implementations.Data if (EnableGroupByPresentationUniqueKey(query)) { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); } else if (query.GroupBySeriesPresentationUniqueKey) { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); } else { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); } commandText += GetJoinUserDataText(query) @@ -3039,7 +3039,7 @@ namespace Emby.Server.Implementations.Data return string.Empty; } - return " ORDER BY " + string.Join(",", orderBy.Select(i => + return " ORDER BY " + string.Join(',', orderBy.Select(i => { var columnMap = MapOrderByField(i.Item1, query); @@ -3137,7 +3137,7 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; var commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid" })) + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid" })) + GetFromText() + GetJoinUserDataText(query); @@ -3203,7 +3203,7 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; - var commandText = "select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid", "path" })) + GetFromText(); + var commandText = "select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid", "path" })) + GetFromText(); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) @@ -3284,7 +3284,7 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; var commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, new[] { "guid" })) + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid" })) + GetFromText() + GetJoinUserDataText(query); @@ -3327,15 +3327,15 @@ namespace Emby.Server.Implementations.Data if (EnableGroupByPresentationUniqueKey(query)) { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); } else if (query.GroupBySeriesPresentationUniqueKey) { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); } else { - commandText += " select " + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); } commandText += GetJoinUserDataText(query) @@ -3596,7 +3596,7 @@ namespace Emby.Server.Implementations.Data } else if (excludeTypes.Length > 1) { - var inClause = string.Join(",", excludeTypes.Select(i => "'" + i + "'")); + var inClause = string.Join(',', excludeTypes.Select(i => "'" + i + "'")); whereClauses.Add($"type not in ({inClause})"); } } @@ -3607,7 +3607,7 @@ namespace Emby.Server.Implementations.Data } else if (includeTypes.Length > 1) { - var inClause = string.Join(",", includeTypes.Select(i => "'" + i + "'")); + var inClause = string.Join(',', includeTypes.Select(i => "'" + i + "'")); whereClauses.Add($"type in ({inClause})"); } @@ -3618,7 +3618,7 @@ namespace Emby.Server.Implementations.Data } else if (query.ChannelIds.Count > 1) { - var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); + var inClause = string.Join(',', query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); whereClauses.Add($"ChannelId in ({inClause})"); } @@ -4351,7 +4351,7 @@ namespace Emby.Server.Implementations.Data } else if (query.Years.Length > 1) { - var val = string.Join(",", query.Years); + var val = string.Join(',', query.Years); whereClauses.Add("ProductionYear in (" + val + ")"); } @@ -4401,7 +4401,7 @@ namespace Emby.Server.Implementations.Data } else if (queryMediaTypes.Length > 1) { - var val = string.Join(",", queryMediaTypes.Select(i => "'" + i + "'")); + var val = string.Join(',', queryMediaTypes.Select(i => "'" + i + "'")); whereClauses.Add("MediaType in (" + val + ")"); } @@ -4498,7 +4498,7 @@ namespace Emby.Server.Implementations.Data var paramName = "@HasAnyProviderId" + index; // this is a search for the placeholder - hasProviderIds.Add("ProviderIds like " + paramName + ""); + hasProviderIds.Add("ProviderIds like " + paramName); // this replaces the placeholder with a value, here: %key=val% if (statement != null) @@ -4549,7 +4549,7 @@ namespace Emby.Server.Implementations.Data } else if (enableItemsByName && includedItemByNameTypes.Count > 1) { - var itemByNameTypeVal = string.Join(",", includedItemByNameTypes.Select(i => "'" + i + "'")); + var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))"); } else @@ -4564,7 +4564,7 @@ namespace Emby.Server.Implementations.Data } else if (queryTopParentIds.Length > 1) { - var val = string.Join(",", queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); + var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); if (enableItemsByName && includedItemByNameTypes.Count == 1) { @@ -4576,7 +4576,7 @@ namespace Emby.Server.Implementations.Data } else if (enableItemsByName && includedItemByNameTypes.Count > 1) { - var itemByNameTypeVal = string.Join(",", includedItemByNameTypes.Select(i => "'" + i + "'")); + var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))"); } else @@ -4597,7 +4597,7 @@ namespace Emby.Server.Implementations.Data if (query.AncestorIds.Length > 1) { - var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); + var inClause = string.Join(',', query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause)); } @@ -5148,7 +5148,7 @@ AND Type = @InternalPersonType)"); } else if (queryPersonTypes.Count > 1) { - var val = string.Join(",", queryPersonTypes.Select(i => "'" + i + "'")); + var val = string.Join(',', queryPersonTypes.Select(i => "'" + i + "'")); whereClauses.Add("PersonType in (" + val + ")"); } @@ -5162,7 +5162,7 @@ AND Type = @InternalPersonType)"); } else if (queryExcludePersonTypes.Count > 1) { - var val = string.Join(",", queryExcludePersonTypes.Select(i => "'" + i + "'")); + var val = string.Join(',', queryExcludePersonTypes.Select(i => "'" + i + "'")); whereClauses.Add("PersonType not in (" + val + ")"); } @@ -5308,19 +5308,19 @@ AND Type = @InternalPersonType)"); var typeClause = itemValueTypes.Length == 1 ? ("Type=" + itemValueTypes[0].ToString(CultureInfo.InvariantCulture)) : - ("Type in (" + string.Join(",", itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")"); + ("Type in (" + string.Join(',', itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")"); var commandText = "Select Value From ItemValues where " + typeClause; if (withItemTypes.Count > 0) { - var typeString = string.Join(",", withItemTypes.Select(i => "'" + i + "'")); + var typeString = string.Join(',', withItemTypes.Select(i => "'" + i + "'")); commandText += " AND ItemId In (select guid from typedbaseitems where type in (" + typeString + "))"; } if (excludeItemTypes.Count > 0) { - var typeString = string.Join(",", excludeItemTypes.Select(i => "'" + i + "'")); + var typeString = string.Join(',', excludeItemTypes.Select(i => "'" + i + "'")); commandText += " AND ItemId not In (select guid from typedbaseitems where type in (" + typeString + "))"; } @@ -5363,7 +5363,7 @@ AND Type = @InternalPersonType)"); var typeClause = itemValueTypes.Length == 1 ? ("Type=" + itemValueTypes[0].ToString(CultureInfo.InvariantCulture)) : - ("Type in (" + string.Join(",", itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")"); + ("Type in (" + string.Join(',', itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")"); InternalItemsQuery typeSubQuery = null; @@ -5427,7 +5427,7 @@ AND Type = @InternalPersonType)"); columns = GetFinalColumnsToSelect(query, columns); var commandText = "select " - + string.Join(",", columns) + + string.Join(',', columns) + GetFromText() + GetJoinUserDataText(query); @@ -5504,7 +5504,7 @@ AND Type = @InternalPersonType)"); if (query.EnableTotalRecordCount) { var countText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText() + GetJoinUserDataText(query) + whereText; @@ -5565,7 +5565,7 @@ AND Type = @InternalPersonType)"); if (query.EnableTotalRecordCount) { commandText = "select " - + string.Join(",", GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText() + GetJoinUserDataText(query) + whereText; diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 2c4e8e0fcc..6574db6078 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Data connection.RunInTransaction( db => { - db.ExecuteAll(string.Join(";", new[] { + db.ExecuteAll(string.Join(';', new[] { "create table if not exists UserDatas (key nvarchar not null, userId INT not null, rating float null, played bit not null, playCount int not null, isFavorite bit not null, playbackPositionTicks bigint not null, lastPlayedDate datetime null, AudioStreamIndex INT, SubtitleStreamIndex INT)", diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 7567ea312c..d32b70e03f 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -35,8 +35,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly ICryptoProvider _cryptoProvider; private readonly ConcurrentDictionary _tokens = new ConcurrentDictionary(); - private DateTime _lastErrorResponse; private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private DateTime _lastErrorResponse; public SchedulesDirect( ILogger logger, diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index c82b67b41b..c4f173c7ac 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -155,7 +155,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts if (channelIdValues.Count > 0) { - channel.Id = string.Join("_", channelIdValues); + channel.Id = string.Join('_', channelIdValues); } return channel; diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index f27305cbed..c6e931448d 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -166,7 +166,7 @@ namespace Emby.Server.Implementations.MediaEncoder } catch (Exception ex) { - _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(",", video.Path)); + _logger.LogError(ex, "Error extracting chapter images for {0}", string.Join(',', video.Path)); success = false; break; } diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs index 171e442581..649305fd56 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs @@ -143,7 +143,7 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(parentPath); - string text = string.Join("|", previouslyFailedImages); + string text = string.Join('|', previouslyFailedImages); File.WriteAllText(failHistoryPath, text); } diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index bacd95baca..5aa033ccf4 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -223,7 +223,7 @@ namespace Jellyfin.Api.Controllers DeInterlace = true, RequireNonAnamorphic = true, EnableMpegtsM2TsMode = true, - TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()), + TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(',', mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()), Context = EncodingContext.Static, StreamOptions = new Dictionary(), EnableAdaptiveBitrateStreaming = true @@ -254,7 +254,7 @@ namespace Jellyfin.Api.Controllers CopyTimestamps = true, StartTimeTicks = startTimeTicks, SubtitleMethod = SubtitleDeliveryMethod.Embed, - TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()), + TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(',', mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()), Context = EncodingContext.Static }; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 92ff42b49f..8a47f7461d 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -222,7 +222,7 @@ namespace Jellyfin.Api.Helpers { // Force HEVC Main Profile and disable video stream copy. state.OutputVideoCodec = "hevc"; - var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(",", requestedVideoProfiles), "main"); + var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(',', requestedVideoProfiles), "main"); sdrVideoUrl += "&AllowVideoStreamCopy=false"; EncodingHelper encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 7598b29e6e..53d45261e6 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1243,7 +1243,7 @@ namespace MediaBrowser.Controller.Entities } } - return string.Join("/", terms.ToArray()); + return string.Join('/', terms.ToArray()); } /// @@ -2795,7 +2795,7 @@ namespace MediaBrowser.Controller.Entities { var list = GetEtagValues(user); - return string.Join("|", list).GetMD5().ToString("N", CultureInfo.InvariantCulture); + return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture); } protected virtual List GetEtagValues(User user) diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 1a379074dc..a410c1b66f 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -107,7 +107,7 @@ namespace MediaBrowser.Controller.Entities.TV return key; } - return key + "-" + string.Join("-", folders); + return key + "-" + string.Join('-', folders); } private static string GetUniqueSeriesKey(BaseItem series) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 07a9f5ba61..53a78a0273 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -592,7 +592,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (state.IsVideoRequest && ((string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isSwDecoder)) - || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) + || (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder)))) { if (isTonemappingSupported) @@ -1381,7 +1381,8 @@ namespace MediaBrowser.Controller.MediaEncoding var requestedProfile = requestedProfiles[0]; // strip spaces because they may be stripped out on the query string as well - if (!string.IsNullOrEmpty(videoStream.Profile) && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", ""), StringComparer.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(videoStream.Profile) + && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", "", StringComparison.Ordinal), StringComparer.OrdinalIgnoreCase)) { var currentScore = GetVideoProfileScore(videoStream.Profile); var requestedScore = GetVideoProfileScore(requestedProfile); @@ -1710,7 +1711,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (filters.Count > 0) { - return " -af \"" + string.Join(",", filters) + "\""; + return " -af \"" + string.Join(',', filters) + "\""; } return string.Empty; @@ -2888,7 +2889,7 @@ namespace MediaBrowser.Controller.MediaEncoding output += string.Format( CultureInfo.InvariantCulture, "{0}", - string.Join(",", filters)); + string.Join(',', filters)); } return output; @@ -2914,7 +2915,7 @@ namespace MediaBrowser.Controller.MediaEncoding if (threads <= 0) { return 0; - } + } else if (threads >= Environment.ProcessorCount) { return Environment.ProcessorCount; @@ -3864,7 +3865,7 @@ namespace MediaBrowser.Controller.MediaEncoding GetInputArgument(state, encodingOptions), threads, " -vn", - string.Join(" ", audioTranscodeParams), + string.Join(' ', audioTranscodeParams), outputPath, string.Empty, string.Empty, diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index 396206658d..a337521c62 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -214,7 +214,7 @@ namespace MediaBrowser.LocalMetadata.Savers if (item.LockedFields.Length > 0) { - writer.WriteElementString("LockedFields", string.Join("|", item.LockedFields)); + writer.WriteElementString("LockedFields", string.Join('|', item.LockedFields)); } if (item.CriticRating.HasValue) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index bd026bce15..b5291b5609 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1496,7 +1496,7 @@ namespace MediaBrowser.MediaEncoding.Probing video.IndexNumber = int.Parse(numbers[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/')[0], CultureInfo.InvariantCulture); int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", string.Empty, StringComparison.Ordinal).Split('/')[1], CultureInfo.InvariantCulture); - description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it + description = string.Join(' ', numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it } else { @@ -1508,7 +1508,7 @@ namespace MediaBrowser.MediaEncoding.Probing if (subtitle.Contains('.', StringComparison.Ordinal)) { // skip the comment, keep the subtitle - description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first + description = string.Join('.', subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first } else { diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 431cf0bafa..a3983afe5f 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -1733,7 +1733,7 @@ namespace MediaBrowser.Model.Dlna if (condition.Condition == ProfileConditionType.Equals || condition.Condition == ProfileConditionType.EqualsAny) { - item.SetOption(qualifier, "profile", string.Join(",", values)); + item.SetOption(qualifier, "profile", string.Join(',', values)); } } diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 55b12ae810..4765052d59 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -193,12 +193,12 @@ namespace MediaBrowser.Model.Dlna continue; } - var encodedValue = pair.Value.Replace(" ", "%20"); + var encodedValue = pair.Value.Replace(" ", "%20", StringComparison.Ordinal); list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", pair.Name, encodedValue)); } - string queryString = string.Join("&", list.ToArray()); + string queryString = string.Join('&', list); return GetUrl(baseUrl, queryString); } @@ -238,11 +238,11 @@ namespace MediaBrowser.Model.Dlna string audioCodecs = item.AudioCodecs.Length == 0 ? string.Empty : - string.Join(",", item.AudioCodecs); + string.Join(',', item.AudioCodecs); string videoCodecs = item.VideoCodecs.Length == 0 ? string.Empty : - string.Join(",", item.VideoCodecs); + string.Join(',', item.VideoCodecs); list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty)); list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty)); @@ -322,7 +322,7 @@ namespace MediaBrowser.Model.Dlna string subtitleCodecs = item.SubtitleCodecs.Length == 0 ? string.Empty : - string.Join(",", item.SubtitleCodecs); + string.Join(',', item.SubtitleCodecs); list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty)); @@ -351,12 +351,12 @@ namespace MediaBrowser.Model.Dlna } // strip spaces to avoid having to encode h264 profile names - list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", ""))); + list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty, StringComparison.Ordinal))); } if (!item.IsDirectStream) { - list.Add(new NameValuePair("TranscodeReasons", string.Join(",", item.TranscodeReasons.Distinct().Select(i => i.ToString())))); + list.Add(new NameValuePair("TranscodeReasons", string.Join(',', item.TranscodeReasons.Distinct().Select(i => i.ToString())))); } return list; diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index ca0b93c30f..d85a8cde95 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -211,7 +211,7 @@ namespace MediaBrowser.Model.Entities return result.ToString(); } - return string.Join(" ", attributes); + return string.Join(' ', attributes); } case MediaStreamType.Subtitle: diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 9f22e618ef..0edab37878 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -465,7 +465,7 @@ namespace MediaBrowser.XbmcMetadata.Savers if (item.LockedFields.Length > 0) { - writer.WriteElementString("lockedfields", string.Join("|", item.LockedFields)); + writer.WriteElementString("lockedfields", string.Join('|', item.LockedFields)); } writer.WriteElementString("dateadded", item.DateCreated.ToLocalTime().ToString(DateAddedFormat, CultureInfo.InvariantCulture)); From cd612edbf063f1378890e693193400e7a0c02a17 Mon Sep 17 00:00:00 2001 From: Dar Donkov Date: Fri, 12 Feb 2021 18:01:22 +0000 Subject: [PATCH 1093/1930] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index bbc8570894..9db3b50d91 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -92,12 +92,12 @@ "ValueHasBeenAddedToLibrary": "{0} беше добавен във Вашата библиотека", "ValueSpecialEpisodeName": "Специални - {0}", "VersionNumber": "Версия {0}", - "TaskDownloadMissingSubtitlesDescription": "Търси Интернет за липсващи поднадписи, на база конфигурацията за мета-данни.", - "TaskDownloadMissingSubtitles": "Изтегляне на липсващи поднадписи", + "TaskDownloadMissingSubtitlesDescription": "Търси Интернет за липсващи субтитри, на база конфигурацията за мета-данни.", + "TaskDownloadMissingSubtitles": "Изтегляне на липсващи субтитри", "TaskRefreshChannelsDescription": "Обновява информацията за интернет канала.", "TaskRefreshChannels": "Обновяване на Канали", - "TaskCleanTranscodeDescription": "Изтрива прекодирани файлове по-стари от един ден.", - "TaskCleanTranscode": "Изчиства директорията за прекодиране", + "TaskCleanTranscodeDescription": "Изтрива транскодирани файлове по-стари от един ден.", + "TaskCleanTranscode": "Изчиства директорията за транскодиране", "TaskUpdatePluginsDescription": "Изтегля и инсталира актуализации за добавките, които са настроени за автоматична актуализация.", "TaskUpdatePlugins": "Актуализира добавките", "TaskRefreshPeopleDescription": "Актуализира мета-данните за артистите и режисьорите за Вашата медийна библиотека.", From 8a6242826f3cca6aa12b475ad948cd298c8a2996 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Feb 2021 11:38:17 +0100 Subject: [PATCH 1094/1930] 100% branch coverage for Emby.Naming --- Emby.Naming/TV/SeasonPathParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/TV/SeasonPathParser.cs b/Emby.Naming/TV/SeasonPathParser.cs index d11c7c99e8..6236f86c43 100644 --- a/Emby.Naming/TV/SeasonPathParser.cs +++ b/Emby.Naming/TV/SeasonPathParser.cs @@ -60,7 +60,7 @@ namespace Emby.Naming.TV bool supportSpecialAliases, bool supportNumericSeasonFolders) { - var filename = Path.GetFileName(path) ?? string.Empty; + string filename = Path.GetFileName(path); if (supportSpecialAliases) { From dc9e2ad1a4a21677cb22d3a2c76dee40859462bb Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Feb 2021 11:46:38 +0100 Subject: [PATCH 1095/1930] Add some more Crc32 tests --- tests/Jellyfin.Common.Tests/Crc32Tests.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/Jellyfin.Common.Tests/Crc32Tests.cs b/tests/Jellyfin.Common.Tests/Crc32Tests.cs index d93fb839c7..e95a2867fd 100644 --- a/tests/Jellyfin.Common.Tests/Crc32Tests.cs +++ b/tests/Jellyfin.Common.Tests/Crc32Tests.cs @@ -19,5 +19,15 @@ namespace Jellyfin.Common.Tests { Assert.Equal(expected, Crc32.Compute(Encoding.UTF8.GetBytes(data))); } + + [Theory] + [InlineData(0x414fa339, "54686520717569636B2062726F776E20666F78206A756D7073206F76657220746865206C617A7920646F67")] + [InlineData(0x190a55ad, "0000000000000000000000000000000000000000000000000000000000000000")] + [InlineData(0xff6cab0b, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")] + [InlineData(0x91267e8a, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F")] + public static void Compute_ValidHex_Success(uint expected, string data) + { + Assert.Equal(expected, Crc32.Compute(Convert.FromHexString(data))); + } } } From b718eed314236ca3d3315c87087dfae147606c2f Mon Sep 17 00:00:00 2001 From: Orry Verducci Date: Sat, 13 Feb 2021 15:27:19 +0000 Subject: [PATCH 1096/1930] Use average frame rate when determining deinterlace mode --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 07a9f5ba61..3b7ae4c32d 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2530,7 +2530,7 @@ namespace MediaBrowser.Controller.MediaEncoding var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode; // If double rate deinterlacing is enabled and the input framerate is 30fps or below, otherwise the output framerate will be too high for many devices - var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.RealFrameRate ?? 60) <= 30; + var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.AverageFrameRate ?? 60) <= 30; var isScalingInAdvance = false; var isCudaDeintInAdvance = false; @@ -3080,7 +3080,7 @@ namespace MediaBrowser.Controller.MediaEncoding { inputModifier += " -deint 1"; - if (!encodingOptions.DeinterlaceDoubleRate || (videoStream?.RealFrameRate ?? 60) > 30) + if (!encodingOptions.DeinterlaceDoubleRate || (videoStream?.AverageFrameRate ?? 60) > 30) { inputModifier += " -drop_second_field 1"; } From eecdc3c11023ffb06beec3414600de6849124869 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 13 Feb 2021 22:41:12 +0100 Subject: [PATCH 1097/1930] Add more tags to nfo tests --- .../Parsers/EpisodeNfoProviderTests.cs | 4 ++ .../Parsers/MovieNfoParserTests.cs | 40 ++++++++++++++++--- .../Parsers/SeriesNfoParserTests.cs | 20 ++++++++++ .../Test Data/American Gods.nfo | 6 ++- .../Test Data/Justice League.nfo | 14 +++++-- .../Test Data/The Bone Orchard.nfo | 4 ++ 6 files changed, 78 insertions(+), 10 deletions(-) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs index 67b4b969a3..b087e522e8 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs @@ -56,6 +56,10 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal(2017, item.ProductionYear); Assert.Single(item.Studios); Assert.Contains("Starz", item.Studios); + Assert.Equal(1, item.IndexNumberEnd); + Assert.Equal(2, item.AirsAfterSeasonNumber); + Assert.Equal(3, item.AirsBeforeSeasonNumber); + Assert.Equal(1, item.AirsBeforeEpisodeNumber); // Credits var writers = result.People.Where(x => x.Type == PersonType.Writer).ToArray(); diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 765464eced..7d31a3ec6f 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; @@ -34,11 +35,11 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers { var result = new MetadataResult /// The instance. /// The name. - /// System.String. - public static string? GetProviderId(this IHasProviderIds instance, string name) + /// The provider id. + /// true if a provider id with the given name was found; otherwise false. + public static bool TryGetProviderId(this IHasProviderIds instance, string name, [MaybeNullWhen(false)] out string id) { if (instance == null) { @@ -45,11 +47,35 @@ namespace MediaBrowser.Model.Entities if (instance.ProviderIds == null) { - return null; + id = string.Empty; + return false; } - instance.ProviderIds.TryGetValue(name, out string? id); - return string.IsNullOrEmpty(id) ? null : id; + return instance.ProviderIds.TryGetValue(name, out id); + } + + /// + /// Gets a provider id. + /// + /// The instance. + /// The provider. + /// The provider id. + /// true if a provider id with the given name was found; otherwise false. + public static bool TryGetProviderId(this IHasProviderIds instance, MetadataProvider provider, [MaybeNullWhen(false)] out string id) + { + return instance.TryGetProviderId(provider.ToString(), out id); + } + + /// + /// Gets a provider id. + /// + /// The instance. + /// The name. + /// System.String. + public static string? GetProviderId(this IHasProviderIds instance, string name) + { + instance.TryGetProviderId(name, out string? id); + return id; } /// diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index f6926d680d..9a3e3d5fad 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using TMDbLib.Objects.Find; +using TMDbLib.Objects.Search; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -43,64 +45,89 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies public async Task> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken) { - var tmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture); - - if (tmdbId == 0) + if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var id)) { - var movieResults = await _tmdbClientManager - .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationToken) + var movie = await _tmdbClientManager + .GetMovieAsync( + int.Parse(id, CultureInfo.InvariantCulture), + searchInfo.MetadataLanguage, + TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), + cancellationToken) .ConfigureAwait(false); - var remoteSearchResults = new List(); - for (var i = 0; i < movieResults.Count; i++) + var remoteResult = new RemoteSearchResult { - var movieResult = movieResults[i]; - var remoteSearchResult = new RemoteSearchResult - { - Name = movieResult.Title ?? movieResult.OriginalTitle, - ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath), - Overview = movieResult.Overview, - SearchProviderName = Name - }; + Name = movie.Title ?? movie.OriginalTitle, + SearchProviderName = Name, + ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath), + Overview = movie.Overview + }; - var releaseDate = movieResult.ReleaseDate?.ToUniversalTime(); - remoteSearchResult.PremiereDate = releaseDate; - remoteSearchResult.ProductionYear = releaseDate?.Year; - - remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture)); - remoteSearchResults.Add(remoteSearchResult); + if (movie.ReleaseDate != null) + { + var releaseDate = movie.ReleaseDate.Value.ToUniversalTime(); + remoteResult.PremiereDate = releaseDate; + remoteResult.ProductionYear = releaseDate.Year; } - return remoteSearchResults; + remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture)); + + if (!string.IsNullOrWhiteSpace(movie.ImdbId)) + { + remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId); + } + + return new[] { remoteResult }; } - var movie = await _tmdbClientManager - .GetMovieAsync(tmdbId, searchInfo.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), cancellationToken) - .ConfigureAwait(false); - - var remoteResult = new RemoteSearchResult + IReadOnlyList movieResults; + if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out id)) { - Name = movie.Title ?? movie.OriginalTitle, - SearchProviderName = Name, - ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath), - Overview = movie.Overview - }; - - if (movie.ReleaseDate != null) + var result = await _tmdbClientManager.FindByExternalIdAsync( + id, + FindExternalSource.Imdb, + TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), + cancellationToken).ConfigureAwait(false); + movieResults = result.MovieResults; + } + else if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out id)) { - var releaseDate = movie.ReleaseDate.Value.ToUniversalTime(); - remoteResult.PremiereDate = releaseDate; - remoteResult.ProductionYear = releaseDate.Year; + var result = await _tmdbClientManager.FindByExternalIdAsync( + id, + FindExternalSource.TvDb, + TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), + cancellationToken).ConfigureAwait(false); + movieResults = result.MovieResults; + } + else + { + movieResults = await _tmdbClientManager + .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationToken) + .ConfigureAwait(false); } - remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture)); - - if (!string.IsNullOrWhiteSpace(movie.ImdbId)) + var len = movieResults.Count; + var remoteSearchResults = new RemoteSearchResult[len]; + for (var i = 0; i < len; i++) { - remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId); + var movieResult = movieResults[i]; + var remoteSearchResult = new RemoteSearchResult + { + Name = movieResult.Title ?? movieResult.OriginalTitle, + ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath), + Overview = movieResult.Overview, + SearchProviderName = Name + }; + + var releaseDate = movieResult.ReleaseDate?.ToUniversalTime(); + remoteSearchResult.PremiereDate = releaseDate; + remoteSearchResult.ProductionYear = releaseDate?.Year; + + remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture)); + remoteSearchResults[i] = remoteSearchResult; } - return new[] { remoteResult }; + return remoteSearchResults; } public async Task> GetMetadata(MovieInfo info, CancellationToken cancellationToken) From 941d3f621708089f8ca2feb89bb7e8de1bbf7d6d Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 19 Feb 2021 17:01:52 +0100 Subject: [PATCH 1114/1930] Add tests for ProviderIdsExtensions --- .../Entities/ProviderIdsExtensions.cs | 43 ++---- .../Entities/ProviderIdsExtensionsTests.cs | 127 ++++++++++++++++++ 2 files changed, 140 insertions(+), 30 deletions(-) create mode 100644 tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index c643f1ecd1..4aff6e3a4f 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -9,28 +9,6 @@ namespace MediaBrowser.Model.Entities /// public static class ProviderIdsExtensions { - /// - /// Determines whether [has provider identifier] [the specified instance]. - /// - /// The instance. - /// The provider. - /// true if [has provider identifier] [the specified instance]; otherwise, false. - public static bool HasProviderId(this IHasProviderIds instance, MetadataProvider provider) - { - return !string.IsNullOrEmpty(instance.GetProviderId(provider.ToString())); - } - - /// - /// Gets a provider id. - /// - /// The instance. - /// The provider. - /// System.String. - public static string? GetProviderId(this IHasProviderIds instance, MetadataProvider provider) - { - return instance.GetProviderId(provider.ToString()); - } - /// /// Gets a provider id. /// @@ -47,7 +25,7 @@ namespace MediaBrowser.Model.Entities if (instance.ProviderIds == null) { - id = string.Empty; + id = null; return false; } @@ -78,6 +56,17 @@ namespace MediaBrowser.Model.Entities return id; } + /// + /// Gets a provider id. + /// + /// The instance. + /// The provider. + /// System.String. + public static string? GetProviderId(this IHasProviderIds instance, MetadataProvider provider) + { + return instance.GetProviderId(provider.ToString()); + } + /// /// Sets a provider id. /// @@ -94,13 +83,7 @@ namespace MediaBrowser.Model.Entities // If it's null remove the key from the dictionary if (string.IsNullOrEmpty(value)) { - if (instance.ProviderIds != null) - { - if (instance.ProviderIds.ContainsKey(name)) - { - instance.ProviderIds.Remove(name); - } - } + instance.ProviderIds?.Remove(name); } else { diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs new file mode 100644 index 0000000000..912fe74ec4 --- /dev/null +++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using MediaBrowser.Model.Entities; +using Xunit; + +namespace Jellyfin.Model.Tests.Entities +{ + public class ProviderIdsExtensionsTests + { + private const string ExampleImdbId = "tt0113375"; + + [Fact] + public void GetProviderId_NullInstance_ThrowsArgumentNullException() + { + Assert.Throws(() => ProviderIdsExtensions.GetProviderId(null!, MetadataProvider.Imdb)); + } + + [Fact] + public void GetProviderId_NullName_ThrowsArgumentNullException() + { + Assert.Throws(() => ProviderIdsExtensionsTestsObject.Empty.GetProviderId(null!)); + } + + [Fact] + public void GetProviderId_NotFoundName_Null() + { + Assert.Null(ProviderIdsExtensionsTestsObject.Empty.GetProviderId(MetadataProvider.Imdb)); + } + + [Fact] + public void GetProviderId_NullProvider_Null() + { + var nullProvider = new ProviderIdsExtensionsTestsObject() + { + ProviderIds = null! + }; + + Assert.Null(nullProvider.GetProviderId(MetadataProvider.Imdb)); + } + + [Fact] + public void TryGetProviderId_NotFoundName_False() + { + Assert.False(ProviderIdsExtensionsTestsObject.Empty.TryGetProviderId(MetadataProvider.Imdb, out _)); + } + + [Fact] + public void TryGetProviderId_NullProvider_False() + { + var nullProvider = new ProviderIdsExtensionsTestsObject() + { + ProviderIds = null! + }; + + Assert.False(nullProvider.TryGetProviderId(MetadataProvider.Imdb, out _)); + } + + [Fact] + public void GetProviderId_FoundName_Id() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId; + + Assert.Equal(ExampleImdbId, provider.GetProviderId(MetadataProvider.Imdb)); + } + + [Fact] + public void TryGetProviderId_FoundName_True() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId; + + Assert.True(provider.TryGetProviderId(MetadataProvider.Imdb, out var id)); + Assert.Equal(ExampleImdbId, id); + } + + [Fact] + public void SetProviderId_NullInstance_ThrowsArgumentNullException() + { + Assert.Throws(() => ProviderIdsExtensions.SetProviderId(null!, MetadataProvider.Imdb, ExampleImdbId)); + } + + [Fact] + public void SetProviderId_Null_Remove() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.SetProviderId(MetadataProvider.Imdb, null!); + Assert.Empty(provider.ProviderIds); + } + + [Fact] + public void SetProviderId_EmptyName_Remove() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId; + provider.SetProviderId(MetadataProvider.Imdb, string.Empty); + Assert.Empty(provider.ProviderIds); + } + + [Fact] + public void SetProviderId_NonEmptyId_Success() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.SetProviderId(MetadataProvider.Imdb, ExampleImdbId); + Assert.Single(provider.ProviderIds); + } + + [Fact] + public void SetProviderId_NullProvider_Success() + { + var nullProvider = new ProviderIdsExtensionsTestsObject() + { + ProviderIds = null! + }; + + nullProvider.SetProviderId(MetadataProvider.Imdb, ExampleImdbId); + Assert.Single(nullProvider.ProviderIds); + } + + private class ProviderIdsExtensionsTestsObject : IHasProviderIds + { + public static readonly ProviderIdsExtensionsTestsObject Empty = new ProviderIdsExtensionsTestsObject(); + + public Dictionary ProviderIds { get; set; } = new Dictionary(); + } + } +} From 2b131ddaac922eb7bb9f154afbb3ff2d283cbf0f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 19 Feb 2021 17:26:34 +0100 Subject: [PATCH 1115/1930] Cover all branches --- .../Entities/ProviderIdsExtensionsTests.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs index 912fe74ec4..c1a1525bad 100644 --- a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs +++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs @@ -117,6 +117,18 @@ namespace Jellyfin.Model.Tests.Entities Assert.Single(nullProvider.ProviderIds); } + [Fact] + public void SetProviderId_NullProviderAndEmptyName_Success() + { + var nullProvider = new ProviderIdsExtensionsTestsObject() + { + ProviderIds = null! + }; + + nullProvider.SetProviderId(MetadataProvider.Imdb, string.Empty); + Assert.Null(nullProvider.ProviderIds); + } + private class ProviderIdsExtensionsTestsObject : IHasProviderIds { public static readonly ProviderIdsExtensionsTestsObject Empty = new ProviderIdsExtensionsTestsObject(); From 141efafd3dbbef3dc64824a89fd3fdc77da0b25e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 20 Feb 2021 23:13:04 +0100 Subject: [PATCH 1116/1930] Enable TreatWarningsAsErrors for MediaBrowser.Model --- Emby.Dlna/ContentDirectory/StubType.cs | 2 +- Emby.Dlna/DlnaManager.cs | 2 +- Emby.Dlna/PlayTo/TransportState.cs | 2 +- .../Data/SqliteItemRepository.cs | 6 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 2 +- Jellyfin.Api/Helpers/StreamingHelpers.cs | 2 +- .../Probing/ProbeResultNormalizer.cs | 6 +- .../Channels/ChannelFeatures.cs | 18 +- MediaBrowser.Model/Channels/ChannelQuery.cs | 6 +- .../Configuration/EncodingOptions.cs | 74 +- .../Configuration/ImageOption.cs | 10 +- .../Configuration/LibraryOptions.cs | 403 +------- .../Configuration/MediaPathInfo.cs | 12 + .../Configuration/MetadataConfiguration.cs | 4 +- .../Configuration/MetadataOptions.cs | 20 +- .../Configuration/MetadataPluginSummary.cs | 12 +- .../Configuration/TypeOptions.cs | 365 +++++++ .../Configuration/UserConfiguration.cs | 36 +- .../Configuration/XbmcMetadataOptions.cs | 16 +- MediaBrowser.Model/Dlna/AudioOptions.cs | 9 +- MediaBrowser.Model/Dlna/CodecProfile.cs | 12 +- MediaBrowser.Model/Dlna/ConditionProcessor.cs | 2 +- MediaBrowser.Model/Dlna/ContainerProfile.cs | 10 +- .../Dlna/ContentFeatureBuilder.cs | 34 +- MediaBrowser.Model/Dlna/IDeviceDiscovery.cs | 1 + .../Dlna/MediaFormatProfileResolver.cs | 4 +- .../Dlna/ResolutionConfiguration.cs | 8 +- MediaBrowser.Model/Dlna/ResponseProfile.cs | 10 +- MediaBrowser.Model/Dlna/SearchCriteria.cs | 80 +- MediaBrowser.Model/Dlna/SortCriteria.cs | 4 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 14 +- MediaBrowser.Model/Dlna/StreamInfo.cs | 938 +++++++++--------- MediaBrowser.Model/Dto/BaseItemDto.cs | 10 +- MediaBrowser.Model/Dto/MediaSourceInfo.cs | 67 +- MediaBrowser.Model/Dto/MetadataEditorInfo.cs | 18 +- MediaBrowser.Model/Dto/NameGuidPair.cs | 14 + MediaBrowser.Model/Dto/NameIdPair.cs | 7 - MediaBrowser.Model/Dto/UserDto.cs | 18 +- MediaBrowser.Model/Entities/CollectionType.cs | 32 - MediaBrowser.Model/Entities/MediaStream.cs | 197 ++-- .../Entities/PackageReviewInfo.cs | 40 - MediaBrowser.Model/Entities/SpecialFolder.cs | 36 + .../Entities/VirtualFolderInfo.cs | 16 +- .../Globalization/CultureDto.cs | 12 +- MediaBrowser.Model/IO/IFileSystem.cs | 7 +- MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs | 16 +- .../LiveTv/ListingsProviderInfo.cs | 58 ++ .../LiveTv/LiveTvChannelQuery.cs | 26 +- MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 97 +- .../LiveTv/LiveTvServiceInfo.cs | 10 +- MediaBrowser.Model/LiveTv/RecordingQuery.cs | 16 +- .../LiveTv/SeriesTimerInfoDto.cs | 16 +- MediaBrowser.Model/LiveTv/TunerHostInfo.cs | 38 + MediaBrowser.Model/MediaBrowser.Model.csproj | 4 +- MediaBrowser.Model/MediaInfo/MediaInfo.cs | 22 +- .../MediaInfo/PlaybackInfoRequest.cs | 22 +- .../MediaInfo/PlaybackInfoResponse.cs | 16 +- .../MediaInfo/SubtitleTrackInfo.cs | 4 +- MediaBrowser.Model/Net/ISocket.cs | 6 + MediaBrowser.Model/Net/ISocketFactory.cs | 3 + MediaBrowser.Model/Net/MimeTypes.cs | 21 +- MediaBrowser.Model/Net/NetworkShare.cs | 33 - MediaBrowser.Model/Net/SocketReceiveResult.cs | 4 +- MediaBrowser.Model/Net/WebSocketMessage.cs | 2 +- .../Notifications/NotificationOptions.cs | 10 +- .../Notifications/NotificationRequest.cs | 14 +- .../Providers/ExternalIdInfo.cs | 4 +- .../Providers/RemoteImageInfo.cs | 2 +- .../Providers/SubtitleOptions.cs | 16 +- MediaBrowser.Model/Querying/EpisodeQuery.cs | 10 +- .../Querying/LatestItemsQuery.cs | 9 +- .../Querying/MovieRecommendationQuery.cs | 14 +- MediaBrowser.Model/Querying/NextUpQuery.cs | 20 +- MediaBrowser.Model/Querying/QueryFilters.cs | 27 +- .../Querying/QueryFiltersLegacy.cs | 26 + MediaBrowser.Model/Querying/QueryResult.cs | 36 +- .../Querying/UpcomingEpisodesQuery.cs | 16 +- MediaBrowser.Model/Search/SearchQuery.cs | 32 +- MediaBrowser.Model/Session/BrowseRequest.cs | 1 + .../Session/ClientCapabilities.cs | 14 +- MediaBrowser.Model/Session/GeneralCommand.cs | 13 +- .../Session/PlaybackProgressInfo.cs | 14 - .../Session/PlaystateCommand.cs | 6 +- MediaBrowser.Model/Session/QueueItem.cs | 14 + MediaBrowser.Model/Session/RepeatMode.cs | 11 + MediaBrowser.Model/Session/TranscodeReason.cs | 31 + MediaBrowser.Model/Session/TranscodingInfo.cs | 37 +- MediaBrowser.Model/Sync/SyncJob.cs | 10 +- MediaBrowser.Model/System/SystemInfo.cs | 18 +- MediaBrowser.Model/System/WakeOnLanInfo.cs | 2 +- .../Tasks/IScheduledTaskWorker.cs | 5 +- MediaBrowser.Model/Tasks/ITaskManager.cs | 20 +- MediaBrowser.Model/Tasks/ITaskTrigger.cs | 4 + MediaBrowser.Model/Tasks/TaskInfo.cs | 16 +- MediaBrowser.Model/Tasks/TaskTriggerInfo.cs | 12 +- MediaBrowser.Model/Users/UserPolicy.cs | 100 +- jellyfin.ruleset | 2 + .../ModelBinders/TestType.cs | 6 - 98 files changed, 1800 insertions(+), 1784 deletions(-) create mode 100644 MediaBrowser.Model/Configuration/MediaPathInfo.cs create mode 100644 MediaBrowser.Model/Configuration/TypeOptions.cs create mode 100644 MediaBrowser.Model/Dto/NameGuidPair.cs delete mode 100644 MediaBrowser.Model/Entities/PackageReviewInfo.cs create mode 100644 MediaBrowser.Model/Entities/SpecialFolder.cs create mode 100644 MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs create mode 100644 MediaBrowser.Model/LiveTv/TunerHostInfo.cs delete mode 100644 MediaBrowser.Model/Net/NetworkShare.cs create mode 100644 MediaBrowser.Model/Querying/QueryFiltersLegacy.cs create mode 100644 MediaBrowser.Model/Session/QueueItem.cs create mode 100644 MediaBrowser.Model/Session/RepeatMode.cs create mode 100644 MediaBrowser.Model/Session/TranscodeReason.cs diff --git a/Emby.Dlna/ContentDirectory/StubType.cs b/Emby.Dlna/ContentDirectory/StubType.cs index 982ae5d68e..a5116055d1 100644 --- a/Emby.Dlna/ContentDirectory/StubType.cs +++ b/Emby.Dlna/ContentDirectory/StubType.cs @@ -1,5 +1,5 @@ #pragma warning disable CS1591 -#pragma warning disable SA1602 + namespace Emby.Dlna.ContentDirectory { diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 21ba1c7552..9ab3240388 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -553,7 +553,7 @@ namespace Emby.Dlna private void DumpProfiles() { - DeviceProfile[] list = new [] + DeviceProfile[] list = new[] { new SamsungSmartTvProfile(), new XboxOneProfile(), diff --git a/Emby.Dlna/PlayTo/TransportState.cs b/Emby.Dlna/PlayTo/TransportState.cs index 7068a5d24d..1ca71283a8 100644 --- a/Emby.Dlna/PlayTo/TransportState.cs +++ b/Emby.Dlna/PlayTo/TransportState.cs @@ -1,5 +1,5 @@ #pragma warning disable CS1591 -#pragma warning disable SA1602 + namespace Emby.Dlna.PlayTo { diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index dad8bec7b0..d78b93bd78 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -6207,9 +6207,9 @@ AND Type = @InternalPersonType)"); if (item.Type == MediaStreamType.Subtitle) { - item.localizedUndefined = _localization.GetLocalizedString("Undefined"); - item.localizedDefault = _localization.GetLocalizedString("Default"); - item.localizedForced = _localization.GetLocalizedString("Forced"); + item.LocalizedUndefined = _localization.GetLocalizedString("Undefined"); + item.LocalizedDefault = _localization.GetLocalizedString("Default"); + item.LocalizedForced = _localization.GetLocalizedString("Forced"); } return item; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 0d8315dee1..ce6740fc99 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -523,7 +523,7 @@ namespace Jellyfin.Api.Helpers /// Dlna profile type. public void NormalizeMediaSourceContainer(MediaSourceInfo mediaSource, DeviceProfile profile, DlnaProfileType type) { - mediaSource.Container = StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(mediaSource.Container, mediaSource.Path, profile, type); + mediaSource.Container = StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(mediaSource.Container, profile, type); } private void SetDeviceSpecificSubtitleInfo(StreamInfo info, MediaSourceInfo mediaSource, string accessToken) diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 4957ee8b8d..8df1f5c272 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -183,7 +183,7 @@ namespace Jellyfin.Api.Helpers if (string.IsNullOrEmpty(containerInternal)) { containerInternal = streamingRequest.Static ? - StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, state.MediaPath, null, DlnaProfileType.Audio) + StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, null, DlnaProfileType.Audio) : GetOutputFileExtension(state); } diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index b5291b5609..b9cb49cf2f 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -681,9 +681,9 @@ namespace MediaBrowser.MediaEncoding.Probing { stream.Type = MediaStreamType.Subtitle; stream.Codec = NormalizeSubtitleCodec(stream.Codec); - stream.localizedUndefined = _localization.GetLocalizedString("Undefined"); - stream.localizedDefault = _localization.GetLocalizedString("Default"); - stream.localizedForced = _localization.GetLocalizedString("Forced"); + stream.LocalizedUndefined = _localization.GetLocalizedString("Undefined"); + stream.LocalizedDefault = _localization.GetLocalizedString("Default"); + stream.LocalizedForced = _localization.GetLocalizedString("Forced"); } else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Model/Channels/ChannelFeatures.cs b/MediaBrowser.Model/Channels/ChannelFeatures.cs index a55754eddc..d925b78b6d 100644 --- a/MediaBrowser.Model/Channels/ChannelFeatures.cs +++ b/MediaBrowser.Model/Channels/ChannelFeatures.cs @@ -7,6 +7,13 @@ namespace MediaBrowser.Model.Channels { public class ChannelFeatures { + public ChannelFeatures() + { + MediaTypes = Array.Empty(); + ContentTypes = Array.Empty(); + DefaultSortFields = Array.Empty(); + } + /// /// Gets or sets the name. /// @@ -38,7 +45,7 @@ namespace MediaBrowser.Model.Channels public ChannelMediaContentType[] ContentTypes { get; set; } /// - /// Represents the maximum number of records the channel allows retrieving at a time. + /// Gets or sets the maximum number of records the channel allows retrieving at a time. /// public int? MaxPageSize { get; set; } @@ -55,7 +62,7 @@ namespace MediaBrowser.Model.Channels public ChannelItemSortField[] DefaultSortFields { get; set; } /// - /// Indicates if a sort ascending/descending toggle is supported or not. + /// Gets or sets a value indicating whether a sort ascending/descending toggle is supported. /// public bool SupportsSortOrderToggle { get; set; } @@ -76,12 +83,5 @@ namespace MediaBrowser.Model.Channels /// /// true if [supports content downloading]; otherwise, false. public bool SupportsContentDownloading { get; set; } - - public ChannelFeatures() - { - MediaTypes = Array.Empty(); - ContentTypes = Array.Empty(); - DefaultSortFields = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Channels/ChannelQuery.cs b/MediaBrowser.Model/Channels/ChannelQuery.cs index fd90e7f062..59966127fb 100644 --- a/MediaBrowser.Model/Channels/ChannelQuery.cs +++ b/MediaBrowser.Model/Channels/ChannelQuery.cs @@ -10,7 +10,7 @@ namespace MediaBrowser.Model.Channels public class ChannelQuery { /// - /// Fields to return within the items, in addition to basic information. + /// Gets or sets the fields to return within the items, in addition to basic information. /// /// The fields. public ItemFields[] Fields { get; set; } @@ -28,13 +28,13 @@ namespace MediaBrowser.Model.Channels public Guid UserId { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Use for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index da467e133f..a9b2803017 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -5,6 +5,41 @@ namespace MediaBrowser.Model.Configuration { public class EncodingOptions { + public EncodingOptions() + { + EnableFallbackFont = false; + DownMixAudioBoost = 2; + MaxMuxingQueueSize = 2048; + EnableThrottling = false; + ThrottleDelaySeconds = 180; + EncodingThreadCount = -1; + // This is a DRM device that is almost guaranteed to be there on every intel platform, + // plus it's the default one in ffmpeg if you don't specify anything + VaapiDevice = "/dev/dri/renderD128"; + // This is the OpenCL device that is used for tonemapping. + // The left side of the dot is the platform number, and the right side is the device number on the platform. + OpenclDevice = "0.0"; + EnableTonemapping = false; + EnableVppTonemapping = false; + TonemappingAlgorithm = "hable"; + TonemappingRange = "auto"; + TonemappingDesat = 0; + TonemappingThreshold = 0.8; + TonemappingPeak = 100; + TonemappingParam = 0; + H264Crf = 23; + H265Crf = 28; + DeinterlaceDoubleRate = false; + DeinterlaceMethod = "yadif"; + EnableDecodingColorDepth10Hevc = true; + EnableDecodingColorDepth10Vp9 = true; + EnableEnhancedNvdecDecoder = true; + EnableHardwareEncoding = true; + AllowHevcEncoding = true; + EnableSubtitleExtraction = true; + HardwareDecodingCodecs = new string[] { "h264", "vc1" }; + } + public int EncodingThreadCount { get; set; } public string TranscodingTempPath { get; set; } @@ -24,12 +59,12 @@ namespace MediaBrowser.Model.Configuration public string HardwareAccelerationType { get; set; } /// - /// FFmpeg path as set by the user via the UI. + /// Gets or sets the FFmpeg path as set by the user via the UI. /// public string EncoderAppPath { get; set; } /// - /// The current FFmpeg path being used by the system and displayed on the transcode page. + /// Gets or sets the current FFmpeg path being used by the system and displayed on the transcode page. /// public string EncoderAppPathDisplay { get; set; } @@ -76,40 +111,5 @@ namespace MediaBrowser.Model.Configuration public bool EnableSubtitleExtraction { get; set; } public string[] HardwareDecodingCodecs { get; set; } - - public EncodingOptions() - { - EnableFallbackFont = false; - DownMixAudioBoost = 2; - MaxMuxingQueueSize = 2048; - EnableThrottling = false; - ThrottleDelaySeconds = 180; - EncodingThreadCount = -1; - // This is a DRM device that is almost guaranteed to be there on every intel platform, - // plus it's the default one in ffmpeg if you don't specify anything - VaapiDevice = "/dev/dri/renderD128"; - // This is the OpenCL device that is used for tonemapping. - // The left side of the dot is the platform number, and the right side is the device number on the platform. - OpenclDevice = "0.0"; - EnableTonemapping = false; - EnableVppTonemapping = false; - TonemappingAlgorithm = "hable"; - TonemappingRange = "auto"; - TonemappingDesat = 0; - TonemappingThreshold = 0.8; - TonemappingPeak = 100; - TonemappingParam = 0; - H264Crf = 23; - H265Crf = 28; - DeinterlaceDoubleRate = false; - DeinterlaceMethod = "yadif"; - EnableDecodingColorDepth10Hevc = true; - EnableDecodingColorDepth10Vp9 = true; - EnableEnhancedNvdecDecoder = true; - EnableHardwareEncoding = true; - AllowHevcEncoding = true; - EnableSubtitleExtraction = true; - HardwareDecodingCodecs = new string[] { "h264", "vc1" }; - } } } diff --git a/MediaBrowser.Model/Configuration/ImageOption.cs b/MediaBrowser.Model/Configuration/ImageOption.cs index 2b1268c743..0af7b7e146 100644 --- a/MediaBrowser.Model/Configuration/ImageOption.cs +++ b/MediaBrowser.Model/Configuration/ImageOption.cs @@ -6,6 +6,11 @@ namespace MediaBrowser.Model.Configuration { public class ImageOption { + public ImageOption() + { + Limit = 1; + } + /// /// Gets or sets the type. /// @@ -23,10 +28,5 @@ namespace MediaBrowser.Model.Configuration /// /// The minimum width. public int MinWidth { get; set; } - - public ImageOption() - { - Limit = 1; - } } } diff --git a/MediaBrowser.Model/Configuration/LibraryOptions.cs b/MediaBrowser.Model/Configuration/LibraryOptions.cs index 77ac11d69f..24698360ec 100644 --- a/MediaBrowser.Model/Configuration/LibraryOptions.cs +++ b/MediaBrowser.Model/Configuration/LibraryOptions.cs @@ -2,13 +2,30 @@ #pragma warning disable CS1591 using System; -using System.Collections.Generic; -using MediaBrowser.Model.Entities; namespace MediaBrowser.Model.Configuration { public class LibraryOptions { + public LibraryOptions() + { + TypeOptions = Array.Empty(); + DisabledSubtitleFetchers = Array.Empty(); + SubtitleFetcherOrder = Array.Empty(); + DisabledLocalMetadataReaders = Array.Empty(); + + SkipSubtitlesIfAudioTrackMatches = true; + RequirePerfectSubtitleMatch = true; + + EnablePhotos = true; + SaveSubtitlesWithMedia = true; + EnableRealtimeMonitor = true; + PathInfos = Array.Empty(); + EnableInternetProviders = true; + EnableAutomaticSeriesGrouping = true; + SeasonZeroDisplayName = "Specials"; + } + public bool EnablePhotos { get; set; } public bool EnableRealtimeMonitor { get; set; } @@ -79,387 +96,5 @@ namespace MediaBrowser.Model.Configuration return null; } - - public LibraryOptions() - { - TypeOptions = Array.Empty(); - DisabledSubtitleFetchers = Array.Empty(); - SubtitleFetcherOrder = Array.Empty(); - DisabledLocalMetadataReaders = Array.Empty(); - - SkipSubtitlesIfAudioTrackMatches = true; - RequirePerfectSubtitleMatch = true; - - EnablePhotos = true; - SaveSubtitlesWithMedia = true; - EnableRealtimeMonitor = true; - PathInfos = Array.Empty(); - EnableInternetProviders = true; - EnableAutomaticSeriesGrouping = true; - SeasonZeroDisplayName = "Specials"; - } - } - - public class MediaPathInfo - { - public string Path { get; set; } - - public string NetworkPath { get; set; } - } - - public class TypeOptions - { - public string Type { get; set; } - - public string[] MetadataFetchers { get; set; } - - public string[] MetadataFetcherOrder { get; set; } - - public string[] ImageFetchers { get; set; } - - public string[] ImageFetcherOrder { get; set; } - - public ImageOption[] ImageOptions { get; set; } - - public ImageOption GetImageOptions(ImageType type) - { - foreach (var i in ImageOptions) - { - if (i.Type == type) - { - return i; - } - } - - if (DefaultImageOptions.TryGetValue(Type, out ImageOption[] options)) - { - foreach (var i in options) - { - if (i.Type == type) - { - return i; - } - } - } - - return DefaultInstance; - } - - public int GetLimit(ImageType type) - { - return GetImageOptions(type).Limit; - } - - public int GetMinWidth(ImageType type) - { - return GetImageOptions(type).MinWidth; - } - - public bool IsEnabled(ImageType type) - { - return GetLimit(type) > 0; - } - - public TypeOptions() - { - MetadataFetchers = Array.Empty(); - MetadataFetcherOrder = Array.Empty(); - ImageFetchers = Array.Empty(); - ImageFetcherOrder = Array.Empty(); - ImageOptions = Array.Empty(); - } - - public static Dictionary DefaultImageOptions = new Dictionary - { - { - "Movie", new [] - { - new ImageOption - { - Limit = 1, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Art - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Disc - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - }, - - new ImageOption - { - Limit = 0, - Type = ImageType.Banner - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Thumb - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Logo - } - } - }, - { - "MusicVideo", new [] - { - new ImageOption - { - Limit = 1, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Art - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Disc - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - }, - - new ImageOption - { - Limit = 0, - Type = ImageType.Banner - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Thumb - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Logo - } - } - }, - { - "Series", new [] - { - new ImageOption - { - Limit = 1, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Art - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Banner - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Thumb - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Logo - } - } - }, - { - "MusicAlbum", new [] - { - new ImageOption - { - Limit = 0, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Disc - } - } - }, - { - "MusicArtist", new [] - { - new ImageOption - { - Limit = 1, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - // Don't download this by default - // They do look great, but most artists won't have them, which means a banner view isn't really possible - new ImageOption - { - Limit = 0, - Type = ImageType.Banner - }, - - // Don't download this by default - // Generally not used - new ImageOption - { - Limit = 0, - Type = ImageType.Art - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Logo - } - } - }, - { - "BoxSet", new [] - { - new ImageOption - { - Limit = 1, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Thumb - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Logo - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Art - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Disc - }, - - // Don't download this by default as it's rarely used. - new ImageOption - { - Limit = 0, - Type = ImageType.Banner - } - } - }, - { - "Season", new [] - { - new ImageOption - { - Limit = 0, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - }, - - new ImageOption - { - Limit = 0, - Type = ImageType.Banner - }, - - new ImageOption - { - Limit = 0, - Type = ImageType.Thumb - } - } - }, - { - "Episode", new [] - { - new ImageOption - { - Limit = 0, - MinWidth = 1280, - Type = ImageType.Backdrop - }, - - new ImageOption - { - Limit = 1, - Type = ImageType.Primary - } - } - } - }; - - public static ImageOption DefaultInstance = new ImageOption(); } } diff --git a/MediaBrowser.Model/Configuration/MediaPathInfo.cs b/MediaBrowser.Model/Configuration/MediaPathInfo.cs new file mode 100644 index 0000000000..4f311c58f0 --- /dev/null +++ b/MediaBrowser.Model/Configuration/MediaPathInfo.cs @@ -0,0 +1,12 @@ +#nullable disable +#pragma warning disable CS1591 + +namespace MediaBrowser.Model.Configuration +{ + public class MediaPathInfo + { + public string Path { get; set; } + + public string NetworkPath { get; set; } + } +} diff --git a/MediaBrowser.Model/Configuration/MetadataConfiguration.cs b/MediaBrowser.Model/Configuration/MetadataConfiguration.cs index 706831bddc..be044243dd 100644 --- a/MediaBrowser.Model/Configuration/MetadataConfiguration.cs +++ b/MediaBrowser.Model/Configuration/MetadataConfiguration.cs @@ -4,11 +4,11 @@ namespace MediaBrowser.Model.Configuration { public class MetadataConfiguration { - public bool UseFileCreationTimeForDateAdded { get; set; } - public MetadataConfiguration() { UseFileCreationTimeForDateAdded = true; } + + public bool UseFileCreationTimeForDateAdded { get; set; } } } diff --git a/MediaBrowser.Model/Configuration/MetadataOptions.cs b/MediaBrowser.Model/Configuration/MetadataOptions.cs index e7dc3da3cb..76b72bd08e 100644 --- a/MediaBrowser.Model/Configuration/MetadataOptions.cs +++ b/MediaBrowser.Model/Configuration/MetadataOptions.cs @@ -10,6 +10,16 @@ namespace MediaBrowser.Model.Configuration /// public class MetadataOptions { + public MetadataOptions() + { + DisabledMetadataSavers = Array.Empty(); + LocalMetadataReaderOrder = Array.Empty(); + DisabledMetadataFetchers = Array.Empty(); + MetadataFetcherOrder = Array.Empty(); + DisabledImageFetchers = Array.Empty(); + ImageFetcherOrder = Array.Empty(); + } + public string ItemType { get; set; } public string[] DisabledMetadataSavers { get; set; } @@ -23,15 +33,5 @@ namespace MediaBrowser.Model.Configuration public string[] DisabledImageFetchers { get; set; } public string[] ImageFetcherOrder { get; set; } - - public MetadataOptions() - { - DisabledMetadataSavers = Array.Empty(); - LocalMetadataReaderOrder = Array.Empty(); - DisabledMetadataFetchers = Array.Empty(); - MetadataFetcherOrder = Array.Empty(); - DisabledImageFetchers = Array.Empty(); - ImageFetcherOrder = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs index 0c197ee021..aa07d66237 100644 --- a/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs +++ b/MediaBrowser.Model/Configuration/MetadataPluginSummary.cs @@ -8,6 +8,12 @@ namespace MediaBrowser.Model.Configuration { public class MetadataPluginSummary { + public MetadataPluginSummary() + { + SupportedImageTypes = Array.Empty(); + Plugins = Array.Empty(); + } + /// /// Gets or sets the type of the item. /// @@ -25,11 +31,5 @@ namespace MediaBrowser.Model.Configuration /// /// The supported image types. public ImageType[] SupportedImageTypes { get; set; } - - public MetadataPluginSummary() - { - SupportedImageTypes = Array.Empty(); - Plugins = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Configuration/TypeOptions.cs b/MediaBrowser.Model/Configuration/TypeOptions.cs new file mode 100644 index 0000000000..d0179e5aab --- /dev/null +++ b/MediaBrowser.Model/Configuration/TypeOptions.cs @@ -0,0 +1,365 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; +using System.Collections.Generic; +using MediaBrowser.Model.Entities; + +namespace MediaBrowser.Model.Configuration +{ + public class TypeOptions + { + public static readonly ImageOption DefaultInstance = new ImageOption(); + + public static readonly Dictionary DefaultImageOptions = new Dictionary + { + { + "Movie", new[] + { + new ImageOption + { + Limit = 1, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Art + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Disc + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + }, + + new ImageOption + { + Limit = 0, + Type = ImageType.Banner + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Thumb + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Logo + } + } + }, + { + "MusicVideo", new[] + { + new ImageOption + { + Limit = 1, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Art + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Disc + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + }, + + new ImageOption + { + Limit = 0, + Type = ImageType.Banner + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Thumb + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Logo + } + } + }, + { + "Series", new[] + { + new ImageOption + { + Limit = 1, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Art + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Banner + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Thumb + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Logo + } + } + }, + { + "MusicAlbum", new[] + { + new ImageOption + { + Limit = 0, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Disc + } + } + }, + { + "MusicArtist", new[] + { + new ImageOption + { + Limit = 1, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + // Don't download this by default + // They do look great, but most artists won't have them, which means a banner view isn't really possible + new ImageOption + { + Limit = 0, + Type = ImageType.Banner + }, + + // Don't download this by default + // Generally not used + new ImageOption + { + Limit = 0, + Type = ImageType.Art + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Logo + } + } + }, + { + "BoxSet", new[] + { + new ImageOption + { + Limit = 1, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Thumb + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Logo + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Art + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Disc + }, + + // Don't download this by default as it's rarely used. + new ImageOption + { + Limit = 0, + Type = ImageType.Banner + } + } + }, + { + "Season", new[] + { + new ImageOption + { + Limit = 0, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + }, + + new ImageOption + { + Limit = 0, + Type = ImageType.Banner + }, + + new ImageOption + { + Limit = 0, + Type = ImageType.Thumb + } + } + }, + { + "Episode", new[] + { + new ImageOption + { + Limit = 0, + MinWidth = 1280, + Type = ImageType.Backdrop + }, + + new ImageOption + { + Limit = 1, + Type = ImageType.Primary + } + } + } + }; + + public TypeOptions() + { + MetadataFetchers = Array.Empty(); + MetadataFetcherOrder = Array.Empty(); + ImageFetchers = Array.Empty(); + ImageFetcherOrder = Array.Empty(); + ImageOptions = Array.Empty(); + } + + public string Type { get; set; } + + public string[] MetadataFetchers { get; set; } + + public string[] MetadataFetcherOrder { get; set; } + + public string[] ImageFetchers { get; set; } + + public string[] ImageFetcherOrder { get; set; } + + public ImageOption[] ImageOptions { get; set; } + + public ImageOption GetImageOptions(ImageType type) + { + foreach (var i in ImageOptions) + { + if (i.Type == type) + { + return i; + } + } + + if (DefaultImageOptions.TryGetValue(Type, out ImageOption[] options)) + { + foreach (var i in options) + { + if (i.Type == type) + { + return i; + } + } + } + + return DefaultInstance; + } + + public int GetLimit(ImageType type) + { + return GetImageOptions(type).Limit; + } + + public int GetMinWidth(ImageType type) + { + return GetImageOptions(type).MinWidth; + } + + public bool IsEnabled(ImageType type) + { + return GetLimit(type) > 0; + } + } +} diff --git a/MediaBrowser.Model/Configuration/UserConfiguration.cs b/MediaBrowser.Model/Configuration/UserConfiguration.cs index cc0e0c4681..935e6cbe10 100644 --- a/MediaBrowser.Model/Configuration/UserConfiguration.cs +++ b/MediaBrowser.Model/Configuration/UserConfiguration.cs @@ -11,6 +11,24 @@ namespace MediaBrowser.Model.Configuration /// public class UserConfiguration { + /// + /// Initializes a new instance of the class. + /// + public UserConfiguration() + { + EnableNextEpisodeAutoPlay = true; + RememberAudioSelections = true; + RememberSubtitleSelections = true; + + HidePlayedInLatest = true; + PlayDefaultAudioTrack = true; + + LatestItemsExcludes = Array.Empty(); + OrderedViews = Array.Empty(); + MyMediaExcludes = Array.Empty(); + GroupedFolders = Array.Empty(); + } + /// /// Gets or sets the audio language preference. /// @@ -52,23 +70,5 @@ namespace MediaBrowser.Model.Configuration public bool RememberSubtitleSelections { get; set; } public bool EnableNextEpisodeAutoPlay { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public UserConfiguration() - { - EnableNextEpisodeAutoPlay = true; - RememberAudioSelections = true; - RememberSubtitleSelections = true; - - HidePlayedInLatest = true; - PlayDefaultAudioTrack = true; - - LatestItemsExcludes = Array.Empty(); - OrderedViews = Array.Empty(); - MyMediaExcludes = Array.Empty(); - GroupedFolders = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs b/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs index 4d5f996f84..8ad070dcbf 100644 --- a/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs +++ b/MediaBrowser.Model/Configuration/XbmcMetadataOptions.cs @@ -5,6 +5,14 @@ namespace MediaBrowser.Model.Configuration { public class XbmcMetadataOptions { + public XbmcMetadataOptions() + { + ReleaseDateFormat = "yyyy-MM-dd"; + + SaveImagePathsInNfo = true; + EnablePathSubstitution = true; + } + public string UserId { get; set; } public string ReleaseDateFormat { get; set; } @@ -14,13 +22,5 @@ namespace MediaBrowser.Model.Configuration public bool EnablePathSubstitution { get; set; } public bool EnableExtraThumbsDuplication { get; set; } - - public XbmcMetadataOptions() - { - ReleaseDateFormat = "yyyy-MM-dd"; - - SaveImagePathsInNfo = true; - EnablePathSubstitution = true; - } } } diff --git a/MediaBrowser.Model/Dlna/AudioOptions.cs b/MediaBrowser.Model/Dlna/AudioOptions.cs index bbb8bf4263..4d4d8d78cb 100644 --- a/MediaBrowser.Model/Dlna/AudioOptions.cs +++ b/MediaBrowser.Model/Dlna/AudioOptions.cs @@ -34,20 +34,20 @@ namespace MediaBrowser.Model.Dlna public DeviceProfile Profile { get; set; } /// - /// Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested. + /// Gets or sets a media source id. Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested. /// public string MediaSourceId { get; set; } public string DeviceId { get; set; } /// - /// Allows an override of supported number of audio channels - /// Example: DeviceProfile supports five channel, but user only has stereo speakers + /// Gets or sets an override of supported number of audio channels + /// Example: DeviceProfile supports five channel, but user only has stereo speakers. /// public int? MaxAudioChannels { get; set; } /// - /// The application's configured quality setting. + /// Gets or sets the application's configured quality setting. /// public int? MaxBitrate { get; set; } @@ -66,6 +66,7 @@ namespace MediaBrowser.Model.Dlna /// /// Gets the maximum bitrate. /// + /// Whether or not this is audio. /// System.Nullable<System.Int32>. public int? GetMaxBitrate(bool isAudio) { diff --git a/MediaBrowser.Model/Dlna/CodecProfile.cs b/MediaBrowser.Model/Dlna/CodecProfile.cs index d4fd3e6730..8343cf028b 100644 --- a/MediaBrowser.Model/Dlna/CodecProfile.cs +++ b/MediaBrowser.Model/Dlna/CodecProfile.cs @@ -9,6 +9,12 @@ namespace MediaBrowser.Model.Dlna { public class CodecProfile { + public CodecProfile() + { + Conditions = Array.Empty(); + ApplyConditions = Array.Empty(); + } + [XmlAttribute("type")] public CodecType Type { get; set; } @@ -22,12 +28,6 @@ namespace MediaBrowser.Model.Dlna [XmlAttribute("container")] public string Container { get; set; } - public CodecProfile() - { - Conditions = Array.Empty(); - ApplyConditions = Array.Empty(); - } - public string[] GetCodecs() { return ContainerProfile.SplitValue(Codec); diff --git a/MediaBrowser.Model/Dlna/ConditionProcessor.cs b/MediaBrowser.Model/Dlna/ConditionProcessor.cs index faf1ee41be..55c4dd0742 100644 --- a/MediaBrowser.Model/Dlna/ConditionProcessor.cs +++ b/MediaBrowser.Model/Dlna/ConditionProcessor.cs @@ -1,8 +1,8 @@ #pragma warning disable CS1591 using System; -using System.Linq; using System.Globalization; +using System.Linq; using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Model.Dlna diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index 56c89d854f..d83c8f2f3c 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -9,6 +9,11 @@ namespace MediaBrowser.Model.Dlna { public class ContainerProfile { + public ContainerProfile() + { + Conditions = Array.Empty(); + } + [XmlAttribute("type")] public DlnaProfileType Type { get; set; } @@ -17,11 +22,6 @@ namespace MediaBrowser.Model.Dlna [XmlAttribute("container")] public string Container { get; set; } - public ContainerProfile() - { - Conditions = Array.Empty(); - } - public string[] GetContainers() { return SplitValue(Container); diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index 50e3374f77..ec106f1054 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -81,13 +81,13 @@ namespace MediaBrowser.Model.Dlna DlnaFlags.DlnaV15; // if (isDirectStream) - //{ - // flagValue = flagValue | DlnaFlags.ByteBasedSeek; - //} - // else if (runtimeTicks.HasValue) - //{ - // flagValue = flagValue | DlnaFlags.TimeBasedSeek; - //} + // { + // flagValue = flagValue | DlnaFlags.ByteBasedSeek; + // } + // else if (runtimeTicks.HasValue) + // { + // flagValue = flagValue | DlnaFlags.TimeBasedSeek; + // } string dlnaflags = string.Format( CultureInfo.InvariantCulture, @@ -150,16 +150,18 @@ namespace MediaBrowser.Model.Dlna DlnaFlags.DlnaV15; // if (isDirectStream) - //{ - // flagValue = flagValue | DlnaFlags.ByteBasedSeek; - //} - // else if (runtimeTicks.HasValue) - //{ - // flagValue = flagValue | DlnaFlags.TimeBasedSeek; - //} + // { + // flagValue = flagValue | DlnaFlags.ByteBasedSeek; + // } + // else if (runtimeTicks.HasValue) + // { + // flagValue = flagValue | DlnaFlags.TimeBasedSeek; + // } - string dlnaflags = string.Format(CultureInfo.InvariantCulture, ";DLNA.ORG_FLAGS={0}", - DlnaMaps.FlagsToString(flagValue)); + string dlnaflags = string.Format( + CultureInfo.InvariantCulture, + ";DLNA.ORG_FLAGS={0}", + DlnaMaps.FlagsToString(flagValue)); ResponseProfile mediaProfile = _profile.GetVideoMediaProfile( container, diff --git a/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs b/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs index 05209e53d0..086088deae 100644 --- a/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs +++ b/MediaBrowser.Model/Dlna/IDeviceDiscovery.cs @@ -8,6 +8,7 @@ namespace MediaBrowser.Model.Dlna public interface IDeviceDiscovery { event EventHandler> DeviceDiscovered; + event EventHandler> DeviceLeft; } } diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs index 3c955989a1..f61b8d59e8 100644 --- a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs +++ b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs @@ -57,7 +57,6 @@ namespace MediaBrowser.Model.Dlna string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase)) { - return ResolveVideoMPEG2TSFormat(videoCodec, audioCodec, width, height, timestampType); } @@ -323,7 +322,6 @@ namespace MediaBrowser.Model.Dlna if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase) && (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "wmapro", StringComparison.OrdinalIgnoreCase))) { - if (width.HasValue && height.HasValue) { if ((width.Value <= 720) && (height.Value <= 576)) @@ -479,7 +477,9 @@ namespace MediaBrowser.Model.Dlna { if (string.Equals(container, "jpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "jpg", StringComparison.OrdinalIgnoreCase)) + { return ResolveImageJPGFormat(width, height); + } if (string.Equals(container, "png", StringComparison.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs b/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs index 30c44fbe0e..f8f76c69d8 100644 --- a/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs +++ b/MediaBrowser.Model/Dlna/ResolutionConfiguration.cs @@ -4,14 +4,14 @@ namespace MediaBrowser.Model.Dlna { public class ResolutionConfiguration { - public int MaxWidth { get; set; } - - public int MaxBitrate { get; set; } - public ResolutionConfiguration(int maxWidth, int maxBitrate) { MaxWidth = maxWidth; MaxBitrate = maxBitrate; } + + public int MaxWidth { get; set; } + + public int MaxBitrate { get; set; } } } diff --git a/MediaBrowser.Model/Dlna/ResponseProfile.cs b/MediaBrowser.Model/Dlna/ResponseProfile.cs index 48f53f06c2..bf9661f7f3 100644 --- a/MediaBrowser.Model/Dlna/ResponseProfile.cs +++ b/MediaBrowser.Model/Dlna/ResponseProfile.cs @@ -8,6 +8,11 @@ namespace MediaBrowser.Model.Dlna { public class ResponseProfile { + public ResponseProfile() + { + Conditions = Array.Empty(); + } + [XmlAttribute("container")] public string Container { get; set; } @@ -28,11 +33,6 @@ namespace MediaBrowser.Model.Dlna public ProfileCondition[] Conditions { get; set; } - public ResponseProfile() - { - Conditions = Array.Empty(); - } - public string[] GetContainers() { return ContainerProfile.SplitValue(Container); diff --git a/MediaBrowser.Model/Dlna/SearchCriteria.cs b/MediaBrowser.Model/Dlna/SearchCriteria.cs index 94f5bd3dbe..b1fc48c087 100644 --- a/MediaBrowser.Model/Dlna/SearchCriteria.cs +++ b/MediaBrowser.Model/Dlna/SearchCriteria.cs @@ -7,6 +7,46 @@ namespace MediaBrowser.Model.Dlna { public class SearchCriteria { + public SearchCriteria(string search) + { + if (search.Length == 0) + { + throw new ArgumentException("String can't be empty.", nameof(search)); + } + + SearchType = SearchType.Unknown; + + string[] factors = RegexSplit(search, "(and|or)"); + foreach (string factor in factors) + { + string[] subFactors = RegexSplit(factor.Trim().Trim('(').Trim(')').Trim(), "\\s", 3); + + if (subFactors.Length == 3) + { + if (string.Equals("upnp:class", subFactors[0], StringComparison.OrdinalIgnoreCase) + && (string.Equals("=", subFactors[1], StringComparison.Ordinal) || string.Equals("derivedfrom", subFactors[1], StringComparison.OrdinalIgnoreCase))) + { + if (string.Equals("\"object.item.imageItem\"", subFactors[2], StringComparison.Ordinal) || string.Equals("\"object.item.imageItem.photo\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) + { + SearchType = SearchType.Image; + } + else if (string.Equals("\"object.item.videoItem\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) + { + SearchType = SearchType.Video; + } + else if (string.Equals("\"object.container.playlistContainer\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) + { + SearchType = SearchType.Playlist; + } + else if (string.Equals("\"object.container.album.musicAlbum\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) + { + SearchType = SearchType.MusicAlbum; + } + } + } + } + } + public SearchType SearchType { get; set; } /// @@ -31,45 +71,5 @@ namespace MediaBrowser.Model.Dlna { return Regex.Split(str, term, RegexOptions.IgnoreCase); } - - public SearchCriteria(string search) - { - if (search.Length == 0) - { - throw new ArgumentException("String can't be empty.", nameof(search)); - } - - SearchType = SearchType.Unknown; - - string[] factors = RegexSplit(search, "(and|or)"); - foreach (string factor in factors) - { - string[] subFactors = RegexSplit(factor.Trim().Trim('(').Trim(')').Trim(), "\\s", 3); - - if (subFactors.Length == 3) - { - if (string.Equals("upnp:class", subFactors[0], StringComparison.OrdinalIgnoreCase) && - (string.Equals("=", subFactors[1], StringComparison.Ordinal) || string.Equals("derivedfrom", subFactors[1], StringComparison.OrdinalIgnoreCase))) - { - if (string.Equals("\"object.item.imageItem\"", subFactors[2], StringComparison.Ordinal) || string.Equals("\"object.item.imageItem.photo\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) - { - SearchType = SearchType.Image; - } - else if (string.Equals("\"object.item.videoItem\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) - { - SearchType = SearchType.Video; - } - else if (string.Equals("\"object.container.playlistContainer\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) - { - SearchType = SearchType.Playlist; - } - else if (string.Equals("\"object.container.album.musicAlbum\"", subFactors[2], StringComparison.OrdinalIgnoreCase)) - { - SearchType = SearchType.MusicAlbum; - } - } - } - } - } } } diff --git a/MediaBrowser.Model/Dlna/SortCriteria.cs b/MediaBrowser.Model/Dlna/SortCriteria.cs index 53e4540cbb..7769d0bd3e 100644 --- a/MediaBrowser.Model/Dlna/SortCriteria.cs +++ b/MediaBrowser.Model/Dlna/SortCriteria.cs @@ -6,10 +6,10 @@ namespace MediaBrowser.Model.Dlna { public class SortCriteria { - public SortOrder SortOrder => SortOrder.Ascending; - public SortCriteria(string value) { } + + public SortOrder SortOrder => SortOrder.Ascending; } } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index a3983afe5f..bf33691c77 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -227,7 +227,7 @@ namespace MediaBrowser.Model.Dlna } } - public static string NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, string _, DeviceProfile profile, DlnaProfileType type) + public static string NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, DeviceProfile profile, DlnaProfileType type) { if (string.IsNullOrEmpty(inputContainer)) { @@ -274,14 +274,14 @@ namespace MediaBrowser.Model.Dlna if (options.ForceDirectPlay) { playlistItem.PlayMethod = PlayMethod.DirectPlay; - playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio); + playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio); return playlistItem; } if (options.ForceDirectStream) { playlistItem.PlayMethod = PlayMethod.DirectStream; - playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio); + playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio); return playlistItem; } @@ -349,7 +349,7 @@ namespace MediaBrowser.Model.Dlna playlistItem.PlayMethod = PlayMethod.DirectStream; } - playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Audio); + playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Audio); return playlistItem; } @@ -698,7 +698,7 @@ namespace MediaBrowser.Model.Dlna if (directPlay != null) { playlistItem.PlayMethod = directPlay.Value; - playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, item.Path, options.Profile, DlnaProfileType.Video); + playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileType.Video); if (subtitleStream != null) { @@ -1404,7 +1404,9 @@ namespace MediaBrowser.Model.Dlna { _logger.LogInformation( "Bitrate exceeds {PlayBackMethod} limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}", - playMethod, itemBitrate, requestedMaxBitrate); + playMethod, + itemBitrate, + requestedMaxBitrate); return false; } diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 4765052d59..f7010dcd0f 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -27,45 +27,6 @@ namespace MediaBrowser.Model.Dlna StreamOptions = new Dictionary(StringComparer.OrdinalIgnoreCase); } - public void SetOption(string qualifier, string name, string value) - { - if (string.IsNullOrEmpty(qualifier)) - { - SetOption(name, value); - } - else - { - SetOption(qualifier + "-" + name, value); - } - } - - public void SetOption(string name, string value) - { - StreamOptions[name] = value; - } - - public string GetOption(string qualifier, string name) - { - var value = GetOption(qualifier + "-" + name); - - if (string.IsNullOrEmpty(value)) - { - value = GetOption(name); - } - - return value; - } - - public string GetOption(string name) - { - if (StreamOptions.TryGetValue(name, out var value)) - { - return value; - } - - return null; - } - public Guid ItemId { get; set; } public PlayMethod PlayMethod { get; set; } @@ -152,342 +113,8 @@ namespace MediaBrowser.Model.Dlna PlayMethod == PlayMethod.DirectStream || PlayMethod == PlayMethod.DirectPlay; - public string ToUrl(string baseUrl, string accessToken) - { - if (PlayMethod == PlayMethod.DirectPlay) - { - return MediaSource.Path; - } - - if (string.IsNullOrEmpty(baseUrl)) - { - throw new ArgumentNullException(nameof(baseUrl)); - } - - var list = new List(); - foreach (NameValuePair pair in BuildParams(this, accessToken)) - { - if (string.IsNullOrEmpty(pair.Value)) - { - continue; - } - - // Try to keep the url clean by omitting defaults - if (string.Equals(pair.Name, "StartTimeTicks", StringComparison.OrdinalIgnoreCase) && - string.Equals(pair.Value, "0", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (string.Equals(pair.Name, "SubtitleStreamIndex", StringComparison.OrdinalIgnoreCase) && - string.Equals(pair.Value, "-1", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - // Be careful, IsDirectStream==true by default (Static != false or not in query). - // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. - if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && - string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - var encodedValue = pair.Value.Replace(" ", "%20", StringComparison.Ordinal); - - list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", pair.Name, encodedValue)); - } - - string queryString = string.Join('&', list); - - return GetUrl(baseUrl, queryString); - } - - private string GetUrl(string baseUrl, string queryString) - { - if (string.IsNullOrEmpty(baseUrl)) - { - throw new ArgumentNullException(nameof(baseUrl)); - } - - string extension = string.IsNullOrEmpty(Container) ? string.Empty : "." + Container; - - baseUrl = baseUrl.TrimEnd('/'); - - if (MediaType == DlnaProfileType.Audio) - { - if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) - { - return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); - } - - return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString); - } - - if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) - { - return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); - } - - return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString); - } - - private static List BuildParams(StreamInfo item, string accessToken) - { - var list = new List(); - - string audioCodecs = item.AudioCodecs.Length == 0 ? - string.Empty : - string.Join(',', item.AudioCodecs); - - string videoCodecs = item.VideoCodecs.Length == 0 ? - string.Empty : - string.Join(',', item.VideoCodecs); - - list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty)); - list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty)); - list.Add(new NameValuePair("MediaSourceId", item.MediaSourceId ?? string.Empty)); - list.Add(new NameValuePair("Static", item.IsDirectStream.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - list.Add(new NameValuePair("VideoCodec", videoCodecs)); - list.Add(new NameValuePair("AudioCodec", audioCodecs)); - list.Add(new NameValuePair("AudioStreamIndex", item.AudioStreamIndex.HasValue ? item.AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - - list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? item.MaxHeight.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - - long startPositionTicks = item.StartPositionTicks; - - var isHls = string.Equals(item.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase); - - if (isHls) - { - list.Add(new NameValuePair("StartTimeTicks", string.Empty)); - } - else - { - list.Add(new NameValuePair("StartTimeTicks", startPositionTicks.ToString(CultureInfo.InvariantCulture))); - } - - list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty)); - list.Add(new NameValuePair("api_key", accessToken ?? string.Empty)); - - string liveStreamId = item.MediaSource?.LiveStreamId; - list.Add(new NameValuePair("LiveStreamId", liveStreamId ?? string.Empty)); - - list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty)); - - if (!item.IsDirectStream) - { - if (item.RequireNonAnamorphic) - { - list.Add(new NameValuePair("RequireNonAnamorphic", item.RequireNonAnamorphic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - list.Add(new NameValuePair("TranscodingMaxAudioChannels", item.TranscodingMaxAudioChannels.HasValue ? item.TranscodingMaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); - - if (item.EnableSubtitlesInManifest) - { - list.Add(new NameValuePair("EnableSubtitlesInManifest", item.EnableSubtitlesInManifest.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - if (item.EnableMpegtsM2TsMode) - { - list.Add(new NameValuePair("EnableMpegtsM2TsMode", item.EnableMpegtsM2TsMode.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - if (item.EstimateContentLength) - { - list.Add(new NameValuePair("EstimateContentLength", item.EstimateContentLength.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - if (item.TranscodeSeekInfo != TranscodeSeekInfo.Auto) - { - list.Add(new NameValuePair("TranscodeSeekInfo", item.TranscodeSeekInfo.ToString().ToLowerInvariant())); - } - - if (item.CopyTimestamps) - { - list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); - } - - list.Add(new NameValuePair("Tag", item.MediaSource.ETag ?? string.Empty)); - - string subtitleCodecs = item.SubtitleCodecs.Length == 0 ? - string.Empty : - string.Join(',', item.SubtitleCodecs); - - list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty)); - - if (isHls) - { - list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty)); - - if (item.SegmentLength.HasValue) - { - list.Add(new NameValuePair("SegmentLength", item.SegmentLength.Value.ToString(CultureInfo.InvariantCulture))); - } - - if (item.MinSegments.HasValue) - { - list.Add(new NameValuePair("MinSegments", item.MinSegments.Value.ToString(CultureInfo.InvariantCulture))); - } - - list.Add(new NameValuePair("BreakOnNonKeyFrames", item.BreakOnNonKeyFrames.ToString(CultureInfo.InvariantCulture))); - } - - foreach (var pair in item.StreamOptions) - { - if (string.IsNullOrEmpty(pair.Value)) - { - continue; - } - - // strip spaces to avoid having to encode h264 profile names - list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty, StringComparison.Ordinal))); - } - - if (!item.IsDirectStream) - { - list.Add(new NameValuePair("TranscodeReasons", string.Join(',', item.TranscodeReasons.Distinct().Select(i => i.ToString())))); - } - - return list; - } - - public List GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken) - { - return GetExternalSubtitles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken); - } - - public List GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken) - { - var list = GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, enableAllProfiles, baseUrl, accessToken); - var newList = new List(); - - // First add the selected track - foreach (SubtitleStreamInfo stream in list) - { - if (stream.DeliveryMethod == SubtitleDeliveryMethod.External) - { - newList.Add(stream); - } - } - - return newList; - } - - public List GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken) - { - return GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken); - } - - public List GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken) - { - var list = new List(); - - // HLS will preserve timestamps so we can just grab the full subtitle stream - long startPositionTicks = string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase) - ? 0 - : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0); - - // First add the selected track - if (SubtitleStreamIndex.HasValue) - { - foreach (var stream in MediaSource.MediaStreams) - { - if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value) - { - AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks); - } - } - } - - if (!includeSelectedTrackOnly) - { - foreach (var stream in MediaSource.MediaStreams) - { - if (stream.Type == MediaStreamType.Subtitle && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value)) - { - AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks); - } - } - } - - return list; - } - - private void AddSubtitleProfiles(List list, MediaStream stream, ITranscoderSupport transcoderSupport, bool enableAllProfiles, string baseUrl, string accessToken, long startPositionTicks) - { - if (enableAllProfiles) - { - foreach (var profile in DeviceProfile.SubtitleProfiles) - { - var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, new[] { profile }, transcoderSupport); - - list.Add(info); - } - } - else - { - var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, DeviceProfile.SubtitleProfiles, transcoderSupport); - - list.Add(info); - } - } - - private SubtitleStreamInfo GetSubtitleStreamInfo(MediaStream stream, string baseUrl, string accessToken, long startPositionTicks, SubtitleProfile[] subtitleProfiles, ITranscoderSupport transcoderSupport) - { - var subtitleProfile = StreamBuilder.GetSubtitleProfile(MediaSource, stream, subtitleProfiles, PlayMethod, transcoderSupport, Container, SubProtocol); - var info = new SubtitleStreamInfo - { - IsForced = stream.IsForced, - Language = stream.Language, - Name = stream.Language ?? "Unknown", - Format = subtitleProfile.Format, - Index = stream.Index, - DeliveryMethod = subtitleProfile.Method, - DisplayTitle = stream.DisplayTitle - }; - - if (info.DeliveryMethod == SubtitleDeliveryMethod.External) - { - if (MediaSource.Protocol == MediaProtocol.File || !string.Equals(stream.Codec, subtitleProfile.Format, StringComparison.OrdinalIgnoreCase) || !stream.IsExternal) - { - info.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}", - baseUrl, - ItemId, - MediaSourceId, - stream.Index.ToString(CultureInfo.InvariantCulture), - startPositionTicks.ToString(CultureInfo.InvariantCulture), - subtitleProfile.Format); - - if (!string.IsNullOrEmpty(accessToken)) - { - info.Url += "?api_key=" + accessToken; - } - - info.IsExternalUrl = false; - } - else - { - info.Url = stream.Path; - info.IsExternalUrl = true; - } - } - - return info; - } - /// - /// Returns the audio stream that will be used. + /// Gets the audio stream that will be used. /// public MediaStream TargetAudioStream { @@ -503,7 +130,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Returns the video stream that will be used. + /// Gets the video stream that will be used. /// public MediaStream TargetVideoStream { @@ -519,7 +146,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public int? TargetAudioSampleRate { @@ -533,7 +160,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public int? TargetAudioBitDepth { @@ -556,7 +183,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public int? TargetVideoBitDepth { @@ -603,7 +230,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public float? TargetFramerate { @@ -617,7 +244,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public double? TargetVideoLevel { @@ -639,72 +266,8 @@ namespace MediaBrowser.Model.Dlna } } - public int? GetTargetVideoBitDepth(string codec) - { - var value = GetOption(codec, "videobitdepth"); - if (string.IsNullOrEmpty(value)) - { - return null; - } - - if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) - { - return result; - } - - return null; - } - - public int? GetTargetAudioBitDepth(string codec) - { - var value = GetOption(codec, "audiobitdepth"); - if (string.IsNullOrEmpty(value)) - { - return null; - } - - if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) - { - return result; - } - - return null; - } - - public double? GetTargetVideoLevel(string codec) - { - var value = GetOption(codec, "level"); - if (string.IsNullOrEmpty(value)) - { - return null; - } - - if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) - { - return result; - } - - return null; - } - - public int? GetTargetRefFrames(string codec) - { - var value = GetOption(codec, "maxrefframes"); - if (string.IsNullOrEmpty(value)) - { - return null; - } - - if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) - { - return result; - } - - return null; - } - /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public int? TargetPacketLength { @@ -718,7 +281,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the audio sample rate that will be in the output stream. /// public string TargetVideoProfile { @@ -756,7 +319,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio bitrate that will be in the output stream. + /// Gets the audio bitrate that will be in the output stream. /// public int? TargetAudioBitrate { @@ -770,7 +333,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio channels that will be in the output stream. + /// Gets the audio channels that will be in the output stream. /// public int? TargetAudioChannels { @@ -792,26 +355,8 @@ namespace MediaBrowser.Model.Dlna } } - public int? GetTargetAudioChannels(string codec) - { - var defaultValue = GlobalMaxAudioChannels ?? TranscodingMaxAudioChannels; - - var value = GetOption(codec, "audiochannels"); - if (string.IsNullOrEmpty(value)) - { - return defaultValue; - } - - if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) - { - return Math.Min(result, defaultValue ?? result); - } - - return defaultValue; - } - /// - /// Predicts the audio codec that will be in the output stream. + /// Gets the audio codec that will be in the output stream. /// public string[] TargetAudioCodec { @@ -864,7 +409,7 @@ namespace MediaBrowser.Model.Dlna } /// - /// Predicts the audio channels that will be in the output stream. + /// Gets the audio channels that will be in the output stream. /// public long? TargetSize { @@ -1035,6 +580,463 @@ namespace MediaBrowser.Model.Dlna } } + public void SetOption(string qualifier, string name, string value) + { + if (string.IsNullOrEmpty(qualifier)) + { + SetOption(name, value); + } + else + { + SetOption(qualifier + "-" + name, value); + } + } + + public void SetOption(string name, string value) + { + StreamOptions[name] = value; + } + + public string GetOption(string qualifier, string name) + { + var value = GetOption(qualifier + "-" + name); + + if (string.IsNullOrEmpty(value)) + { + value = GetOption(name); + } + + return value; + } + + public string GetOption(string name) + { + if (StreamOptions.TryGetValue(name, out var value)) + { + return value; + } + + return null; + } + + public string ToUrl(string baseUrl, string accessToken) + { + if (PlayMethod == PlayMethod.DirectPlay) + { + return MediaSource.Path; + } + + if (string.IsNullOrEmpty(baseUrl)) + { + throw new ArgumentNullException(nameof(baseUrl)); + } + + var list = new List(); + foreach (NameValuePair pair in BuildParams(this, accessToken)) + { + if (string.IsNullOrEmpty(pair.Value)) + { + continue; + } + + // Try to keep the url clean by omitting defaults + if (string.Equals(pair.Name, "StartTimeTicks", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "0", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (string.Equals(pair.Name, "SubtitleStreamIndex", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "-1", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // Be careful, IsDirectStream==true by default (Static != false or not in query). + // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. + if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && + string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var encodedValue = pair.Value.Replace(" ", "%20"); + + list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", pair.Name, encodedValue)); + } + + string queryString = string.Join("&", list.ToArray()); + + return GetUrl(baseUrl, queryString); + } + + private string GetUrl(string baseUrl, string queryString) + { + if (string.IsNullOrEmpty(baseUrl)) + { + throw new ArgumentNullException(nameof(baseUrl)); + } + + string extension = string.IsNullOrEmpty(Container) ? string.Empty : "." + Container; + + baseUrl = baseUrl.TrimEnd('/'); + + if (MediaType == DlnaProfileType.Audio) + { + if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) + { + return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); + } + + return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString); + } + + if (string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase)) + { + return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString); + } + + return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString); + } + + private static List BuildParams(StreamInfo item, string accessToken) + { + var list = new List(); + + string audioCodecs = item.AudioCodecs.Length == 0 ? + string.Empty : + string.Join(",", item.AudioCodecs); + + string videoCodecs = item.VideoCodecs.Length == 0 ? + string.Empty : + string.Join(",", item.VideoCodecs); + + list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty)); + list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty)); + list.Add(new NameValuePair("MediaSourceId", item.MediaSourceId ?? string.Empty)); + list.Add(new NameValuePair("Static", item.IsDirectStream.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + list.Add(new NameValuePair("VideoCodec", videoCodecs)); + list.Add(new NameValuePair("AudioCodec", audioCodecs)); + list.Add(new NameValuePair("AudioStreamIndex", item.AudioStreamIndex.HasValue ? item.AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + + list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? item.MaxHeight.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + + long startPositionTicks = item.StartPositionTicks; + + var isHls = string.Equals(item.SubProtocol, "hls", StringComparison.OrdinalIgnoreCase); + + if (isHls) + { + list.Add(new NameValuePair("StartTimeTicks", string.Empty)); + } + else + { + list.Add(new NameValuePair("StartTimeTicks", startPositionTicks.ToString(CultureInfo.InvariantCulture))); + } + + list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty)); + list.Add(new NameValuePair("api_key", accessToken ?? string.Empty)); + + string liveStreamId = item.MediaSource?.LiveStreamId; + list.Add(new NameValuePair("LiveStreamId", liveStreamId ?? string.Empty)); + + list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty)); + + if (!item.IsDirectStream) + { + if (item.RequireNonAnamorphic) + { + list.Add(new NameValuePair("RequireNonAnamorphic", item.RequireNonAnamorphic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + list.Add(new NameValuePair("TranscodingMaxAudioChannels", item.TranscodingMaxAudioChannels.HasValue ? item.TranscodingMaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : string.Empty)); + + if (item.EnableSubtitlesInManifest) + { + list.Add(new NameValuePair("EnableSubtitlesInManifest", item.EnableSubtitlesInManifest.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + if (item.EnableMpegtsM2TsMode) + { + list.Add(new NameValuePair("EnableMpegtsM2TsMode", item.EnableMpegtsM2TsMode.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + if (item.EstimateContentLength) + { + list.Add(new NameValuePair("EstimateContentLength", item.EstimateContentLength.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + if (item.TranscodeSeekInfo != TranscodeSeekInfo.Auto) + { + list.Add(new NameValuePair("TranscodeSeekInfo", item.TranscodeSeekInfo.ToString().ToLowerInvariant())); + } + + if (item.CopyTimestamps) + { + list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant())); + } + + list.Add(new NameValuePair("Tag", item.MediaSource.ETag ?? string.Empty)); + + string subtitleCodecs = item.SubtitleCodecs.Length == 0 ? + string.Empty : + string.Join(",", item.SubtitleCodecs); + + list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty)); + + if (isHls) + { + list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty)); + + if (item.SegmentLength.HasValue) + { + list.Add(new NameValuePair("SegmentLength", item.SegmentLength.Value.ToString(CultureInfo.InvariantCulture))); + } + + if (item.MinSegments.HasValue) + { + list.Add(new NameValuePair("MinSegments", item.MinSegments.Value.ToString(CultureInfo.InvariantCulture))); + } + + list.Add(new NameValuePair("BreakOnNonKeyFrames", item.BreakOnNonKeyFrames.ToString(CultureInfo.InvariantCulture))); + } + + foreach (var pair in item.StreamOptions) + { + if (string.IsNullOrEmpty(pair.Value)) + { + continue; + } + + // strip spaces to avoid having to encode h264 profile names + list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty))); + } + + if (!item.IsDirectStream) + { + list.Add(new NameValuePair("TranscodeReasons", string.Join(',', item.TranscodeReasons.Distinct()))); + } + + return list; + } + + public List GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken) + { + return GetExternalSubtitles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken); + } + + public List GetExternalSubtitles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken) + { + var list = GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, enableAllProfiles, baseUrl, accessToken); + var newList = new List(); + + // First add the selected track + foreach (SubtitleStreamInfo stream in list) + { + if (stream.DeliveryMethod == SubtitleDeliveryMethod.External) + { + newList.Add(stream); + } + } + + return newList; + } + + public List GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string accessToken) + { + return GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken); + } + + public List GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string accessToken) + { + var list = new List(); + + // HLS will preserve timestamps so we can just grab the full subtitle stream + long startPositionTicks = string.Equals(SubProtocol, "hls", StringComparison.OrdinalIgnoreCase) + ? 0 + : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0); + + // First add the selected track + if (SubtitleStreamIndex.HasValue) + { + foreach (var stream in MediaSource.MediaStreams) + { + if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value) + { + AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks); + } + } + } + + if (!includeSelectedTrackOnly) + { + foreach (var stream in MediaSource.MediaStreams) + { + if (stream.Type == MediaStreamType.Subtitle && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value)) + { + AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks); + } + } + } + + return list; + } + + private void AddSubtitleProfiles(List list, MediaStream stream, ITranscoderSupport transcoderSupport, bool enableAllProfiles, string baseUrl, string accessToken, long startPositionTicks) + { + if (enableAllProfiles) + { + foreach (var profile in DeviceProfile.SubtitleProfiles) + { + var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, new[] { profile }, transcoderSupport); + + list.Add(info); + } + } + else + { + var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, DeviceProfile.SubtitleProfiles, transcoderSupport); + + list.Add(info); + } + } + + private SubtitleStreamInfo GetSubtitleStreamInfo(MediaStream stream, string baseUrl, string accessToken, long startPositionTicks, SubtitleProfile[] subtitleProfiles, ITranscoderSupport transcoderSupport) + { + var subtitleProfile = StreamBuilder.GetSubtitleProfile(MediaSource, stream, subtitleProfiles, PlayMethod, transcoderSupport, Container, SubProtocol); + var info = new SubtitleStreamInfo + { + IsForced = stream.IsForced, + Language = stream.Language, + Name = stream.Language ?? "Unknown", + Format = subtitleProfile.Format, + Index = stream.Index, + DeliveryMethod = subtitleProfile.Method, + DisplayTitle = stream.DisplayTitle + }; + + if (info.DeliveryMethod == SubtitleDeliveryMethod.External) + { + if (MediaSource.Protocol == MediaProtocol.File || !string.Equals(stream.Codec, subtitleProfile.Format, StringComparison.OrdinalIgnoreCase) || !stream.IsExternal) + { + info.Url = string.Format( + CultureInfo.InvariantCulture, + "{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}", + baseUrl, + ItemId, + MediaSourceId, + stream.Index.ToString(CultureInfo.InvariantCulture), + startPositionTicks.ToString(CultureInfo.InvariantCulture), + subtitleProfile.Format); + + if (!string.IsNullOrEmpty(accessToken)) + { + info.Url += "?api_key=" + accessToken; + } + + info.IsExternalUrl = false; + } + else + { + info.Url = stream.Path; + info.IsExternalUrl = true; + } + } + + return info; + } + + public int? GetTargetVideoBitDepth(string codec) + { + var value = GetOption(codec, "videobitdepth"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) + { + return result; + } + + return null; + } + + public int? GetTargetAudioBitDepth(string codec) + { + var value = GetOption(codec, "audiobitdepth"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) + { + return result; + } + + return null; + } + + public double? GetTargetVideoLevel(string codec) + { + var value = GetOption(codec, "level"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + if (double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) + { + return result; + } + + return null; + } + + public int? GetTargetRefFrames(string codec) + { + var value = GetOption(codec, "maxrefframes"); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) + { + return result; + } + + return null; + } + + public int? GetTargetAudioChannels(string codec) + { + var defaultValue = GlobalMaxAudioChannels ?? TranscodingMaxAudioChannels; + + var value = GetOption(codec, "audiochannels"); + if (string.IsNullOrEmpty(value)) + { + return defaultValue; + } + + if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) + { + return Math.Min(result, defaultValue ?? result); + } + + return defaultValue; + } + private int? GetMediaStreamCount(MediaStreamType type, int limit) { var count = MediaSource.GetStreamCount(type); diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs index 2f9f9d3cdb..a784025e3d 100644 --- a/MediaBrowser.Model/Dto/BaseItemDto.cs +++ b/MediaBrowser.Model/Dto/BaseItemDto.cs @@ -294,13 +294,13 @@ namespace MediaBrowser.Model.Dto public NameGuidPair[] GenreItems { get; set; } /// - /// If the item does not have a logo, this will hold the Id of the Parent that has one. + /// Gets or sets wether the item has a logo, this will hold the Id of the Parent that has one. /// /// The parent logo item id. public string ParentLogoItemId { get; set; } /// - /// If the item does not have any backdrops, this will hold the Id of the Parent that has one. + /// Gets or sets wether the item has any backdrops, this will hold the Id of the Parent that has one. /// /// The parent backdrop item id. public string ParentBackdropItemId { get; set; } @@ -318,7 +318,7 @@ namespace MediaBrowser.Model.Dto public int? LocalTrailerCount { get; set; } /// - /// User data for this item based on the user it's being requested for. + /// Gets or sets the user data for this item based on the user it's being requested for. /// /// The user data. public UserItemDataDto UserData { get; set; } @@ -506,7 +506,7 @@ namespace MediaBrowser.Model.Dto public string ParentLogoImageTag { get; set; } /// - /// If the item does not have a art, this will hold the Id of the Parent that has one. + /// Gets or sets wether the item has fan art, this will hold the Id of the Parent that has one. /// /// The parent art item id. public string ParentArtItemId { get; set; } @@ -695,7 +695,7 @@ namespace MediaBrowser.Model.Dto public string ChannelPrimaryImageTag { get; set; } /// - /// The start date of the recording, in UTC. + /// Gets or sets the start date of the recording, in UTC. /// public DateTime? StartDate { get; set; } diff --git a/MediaBrowser.Model/Dto/MediaSourceInfo.cs b/MediaBrowser.Model/Dto/MediaSourceInfo.cs index be682be23c..ec3b37efa3 100644 --- a/MediaBrowser.Model/Dto/MediaSourceInfo.cs +++ b/MediaBrowser.Model/Dto/MediaSourceInfo.cs @@ -12,6 +12,18 @@ namespace MediaBrowser.Model.Dto { public class MediaSourceInfo { + public MediaSourceInfo() + { + Formats = Array.Empty(); + MediaStreams = new List(); + MediaAttachments = Array.Empty(); + RequiredHttpHeaders = new Dictionary(); + SupportsTranscoding = true; + SupportsDirectStream = true; + SupportsDirectPlay = true; + SupportsProbing = true; + } + public MediaProtocol Protocol { get; set; } public string Id { get; set; } @@ -31,6 +43,7 @@ namespace MediaBrowser.Model.Dto public string Name { get; set; } /// + /// Gets or sets a value indicating whether the media is remote. /// Differentiate internet url vs local network. /// public bool IsRemote { get; set; } @@ -95,16 +108,28 @@ namespace MediaBrowser.Model.Dto public int? AnalyzeDurationMs { get; set; } - public MediaSourceInfo() + [JsonIgnore] + public TranscodeReason[] TranscodeReasons { get; set; } + + public int? DefaultAudioStreamIndex { get; set; } + + public int? DefaultSubtitleStreamIndex { get; set; } + + [JsonIgnore] + public MediaStream VideoStream { - Formats = Array.Empty(); - MediaStreams = new List(); - MediaAttachments = Array.Empty(); - RequiredHttpHeaders = new Dictionary(); - SupportsTranscoding = true; - SupportsDirectStream = true; - SupportsDirectPlay = true; - SupportsProbing = true; + get + { + foreach (var i in MediaStreams) + { + if (i.Type == MediaStreamType.Video) + { + return i; + } + } + + return null; + } } public void InferTotalBitrate(bool force = false) @@ -134,13 +159,6 @@ namespace MediaBrowser.Model.Dto } } - [JsonIgnore] - public TranscodeReason[] TranscodeReasons { get; set; } - - public int? DefaultAudioStreamIndex { get; set; } - - public int? DefaultSubtitleStreamIndex { get; set; } - public MediaStream GetDefaultAudioStream(int? defaultIndex) { if (defaultIndex.HasValue) @@ -175,23 +193,6 @@ namespace MediaBrowser.Model.Dto return null; } - [JsonIgnore] - public MediaStream VideoStream - { - get - { - foreach (var i in MediaStreams) - { - if (i.Type == MediaStreamType.Video) - { - return i; - } - } - - return null; - } - } - public MediaStream GetMediaStream(MediaStreamType type, int index) { foreach (var i in MediaStreams) diff --git a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs index e4f38d6af3..e0e889f7d0 100644 --- a/MediaBrowser.Model/Dto/MetadataEditorInfo.cs +++ b/MediaBrowser.Model/Dto/MetadataEditorInfo.cs @@ -10,6 +10,15 @@ namespace MediaBrowser.Model.Dto { public class MetadataEditorInfo { + public MetadataEditorInfo() + { + ParentalRatingOptions = Array.Empty(); + Countries = Array.Empty(); + Cultures = Array.Empty(); + ExternalIdInfos = Array.Empty(); + ContentTypeOptions = Array.Empty(); + } + public ParentalRating[] ParentalRatingOptions { get; set; } public CountryInfo[] Countries { get; set; } @@ -21,14 +30,5 @@ namespace MediaBrowser.Model.Dto public string ContentType { get; set; } public NameValuePair[] ContentTypeOptions { get; set; } - - public MetadataEditorInfo() - { - ParentalRatingOptions = Array.Empty(); - Countries = Array.Empty(); - Cultures = Array.Empty(); - ExternalIdInfos = Array.Empty(); - ContentTypeOptions = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Dto/NameGuidPair.cs b/MediaBrowser.Model/Dto/NameGuidPair.cs new file mode 100644 index 0000000000..71166df979 --- /dev/null +++ b/MediaBrowser.Model/Dto/NameGuidPair.cs @@ -0,0 +1,14 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; + +namespace MediaBrowser.Model.Dto +{ + public class NameGuidPair + { + public string Name { get; set; } + + public Guid Id { get; set; } + } +} diff --git a/MediaBrowser.Model/Dto/NameIdPair.cs b/MediaBrowser.Model/Dto/NameIdPair.cs index 45c2fb35db..7f18b45028 100644 --- a/MediaBrowser.Model/Dto/NameIdPair.cs +++ b/MediaBrowser.Model/Dto/NameIdPair.cs @@ -19,11 +19,4 @@ namespace MediaBrowser.Model.Dto /// The identifier. public string Id { get; set; } } - - public class NameGuidPair - { - public string Name { get; set; } - - public Guid Id { get; set; } - } } diff --git a/MediaBrowser.Model/Dto/UserDto.cs b/MediaBrowser.Model/Dto/UserDto.cs index 40222c9dca..256d7b10f1 100644 --- a/MediaBrowser.Model/Dto/UserDto.cs +++ b/MediaBrowser.Model/Dto/UserDto.cs @@ -10,6 +10,15 @@ namespace MediaBrowser.Model.Dto /// public class UserDto : IItemDto, IHasServerId { + /// + /// Initializes a new instance of the class. + /// + public UserDto() + { + Configuration = new UserConfiguration(); + Policy = new UserPolicy(); + } + /// /// Gets or sets the name. /// @@ -94,15 +103,6 @@ namespace MediaBrowser.Model.Dto /// The primary image aspect ratio. public double? PrimaryImageAspectRatio { get; set; } - /// - /// Initializes a new instance of the class. - /// - public UserDto() - { - Configuration = new UserConfiguration(); - Policy = new UserPolicy(); - } - /// public override string ToString() { diff --git a/MediaBrowser.Model/Entities/CollectionType.cs b/MediaBrowser.Model/Entities/CollectionType.cs index 3540387129..60b69d4b01 100644 --- a/MediaBrowser.Model/Entities/CollectionType.cs +++ b/MediaBrowser.Model/Entities/CollectionType.cs @@ -24,36 +24,4 @@ namespace MediaBrowser.Model.Entities public const string Playlists = "playlists"; public const string Folders = "folders"; } - - public static class SpecialFolder - { - public const string TvShowSeries = "TvShowSeries"; - public const string TvGenres = "TvGenres"; - public const string TvGenre = "TvGenre"; - public const string TvLatest = "TvLatest"; - public const string TvNextUp = "TvNextUp"; - public const string TvResume = "TvResume"; - public const string TvFavoriteSeries = "TvFavoriteSeries"; - public const string TvFavoriteEpisodes = "TvFavoriteEpisodes"; - - public const string MovieLatest = "MovieLatest"; - public const string MovieResume = "MovieResume"; - public const string MovieMovies = "MovieMovies"; - public const string MovieCollections = "MovieCollections"; - public const string MovieFavorites = "MovieFavorites"; - public const string MovieGenres = "MovieGenres"; - public const string MovieGenre = "MovieGenre"; - - public const string MusicArtists = "MusicArtists"; - public const string MusicAlbumArtists = "MusicAlbumArtists"; - public const string MusicAlbums = "MusicAlbums"; - public const string MusicGenres = "MusicGenres"; - public const string MusicLatest = "MusicLatest"; - public const string MusicPlaylists = "MusicPlaylists"; - public const string MusicSongs = "MusicSongs"; - public const string MusicFavorites = "MusicFavorites"; - public const string MusicFavoriteArtists = "MusicFavoriteArtists"; - public const string MusicFavoriteAlbums = "MusicFavoriteAlbums"; - public const string MusicFavoriteSongs = "MusicFavoriteSongs"; - } } diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index d85a8cde95..ade9d7e8dd 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -84,7 +84,7 @@ namespace MediaBrowser.Model.Entities public string Title { get; set; } /// - /// Gets or sets the video range. + /// Gets the video range. /// /// The video range. public string VideoRange @@ -108,11 +108,11 @@ namespace MediaBrowser.Model.Entities } } - public string localizedUndefined { get; set; } + public string LocalizedUndefined { get; set; } - public string localizedDefault { get; set; } + public string LocalizedDefault { get; set; } - public string localizedForced { get; set; } + public string LocalizedForced { get; set; } public string DisplayTitle { @@ -154,7 +154,7 @@ namespace MediaBrowser.Model.Entities if (IsDefault) { - attributes.Add(string.IsNullOrEmpty(localizedDefault) ? "Default" : localizedDefault); + attributes.Add(string.IsNullOrEmpty(LocalizedDefault) ? "Default" : LocalizedDefault); } if (!string.IsNullOrEmpty(Title)) @@ -229,17 +229,17 @@ namespace MediaBrowser.Model.Entities } else { - attributes.Add(string.IsNullOrEmpty(localizedUndefined) ? "Und" : localizedUndefined); + attributes.Add(string.IsNullOrEmpty(LocalizedUndefined) ? "Und" : LocalizedUndefined); } if (IsDefault) { - attributes.Add(string.IsNullOrEmpty(localizedDefault) ? "Default" : localizedDefault); + attributes.Add(string.IsNullOrEmpty(LocalizedDefault) ? "Default" : LocalizedDefault); } if (IsForced) { - attributes.Add(string.IsNullOrEmpty(localizedForced) ? "Forced" : localizedForced); + attributes.Add(string.IsNullOrEmpty(LocalizedForced) ? "Forced" : LocalizedForced); } if (!string.IsNullOrEmpty(Title)) @@ -266,67 +266,6 @@ namespace MediaBrowser.Model.Entities } } - private string GetResolutionText() - { - var i = this; - - if (i.Width.HasValue && i.Height.HasValue) - { - var width = i.Width.Value; - var height = i.Height.Value; - - if (width >= 3800 || height >= 2000) - { - return "4K"; - } - - if (width >= 2500) - { - if (i.IsInterlaced) - { - return "1440i"; - } - - return "1440p"; - } - - if (width >= 1900 || height >= 1000) - { - if (i.IsInterlaced) - { - return "1080i"; - } - - return "1080p"; - } - - if (width >= 1260 || height >= 700) - { - if (i.IsInterlaced) - { - return "720i"; - } - - return "720p"; - } - - if (width >= 700 || height >= 440) - { - - if (i.IsInterlaced) - { - return "480i"; - } - - return "480p"; - } - - return "SD"; - } - - return null; - } - public string NalLengthSize { get; set; } /// @@ -487,6 +426,96 @@ namespace MediaBrowser.Model.Entities } } + /// + /// Gets or sets a value indicating whether [supports external stream]. + /// + /// true if [supports external stream]; otherwise, false. + public bool SupportsExternalStream { get; set; } + + /// + /// Gets or sets the filename. + /// + /// The filename. + public string Path { get; set; } + + /// + /// Gets or sets the pixel format. + /// + /// The pixel format. + public string PixelFormat { get; set; } + + /// + /// Gets or sets the level. + /// + /// The level. + public double? Level { get; set; } + + /// + /// Gets or sets whether this instance is anamorphic. + /// + /// true if this instance is anamorphic; otherwise, false. + public bool? IsAnamorphic { get; set; } + + private string GetResolutionText() + { + var i = this; + + if (i.Width.HasValue && i.Height.HasValue) + { + var width = i.Width.Value; + var height = i.Height.Value; + + if (width >= 3800 || height >= 2000) + { + return "4K"; + } + + if (width >= 2500) + { + if (i.IsInterlaced) + { + return "1440i"; + } + + return "1440p"; + } + + if (width >= 1900 || height >= 1000) + { + if (i.IsInterlaced) + { + return "1080i"; + } + + return "1080p"; + } + + if (width >= 1260 || height >= 700) + { + if (i.IsInterlaced) + { + return "720i"; + } + + return "720p"; + } + + if (width >= 700 || height >= 440) + { + if (i.IsInterlaced) + { + return "480i"; + } + + return "480p"; + } + + return "SD"; + } + + return null; + } + public static bool IsTextFormat(string format) { string codec = format ?? string.Empty; @@ -533,35 +562,5 @@ namespace MediaBrowser.Model.Entities return true; } - - /// - /// Gets or sets a value indicating whether [supports external stream]. - /// - /// true if [supports external stream]; otherwise, false. - public bool SupportsExternalStream { get; set; } - - /// - /// Gets or sets the filename. - /// - /// The filename. - public string Path { get; set; } - - /// - /// Gets or sets the pixel format. - /// - /// The pixel format. - public string PixelFormat { get; set; } - - /// - /// Gets or sets the level. - /// - /// The level. - public double? Level { get; set; } - - /// - /// Gets a value indicating whether this instance is anamorphic. - /// - /// true if this instance is anamorphic; otherwise, false. - public bool? IsAnamorphic { get; set; } } } diff --git a/MediaBrowser.Model/Entities/PackageReviewInfo.cs b/MediaBrowser.Model/Entities/PackageReviewInfo.cs deleted file mode 100644 index 5b22b34ace..0000000000 --- a/MediaBrowser.Model/Entities/PackageReviewInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; - -namespace MediaBrowser.Model.Entities -{ - public class PackageReviewInfo - { - /// - /// Gets or sets the package id (database key) for this review. - /// - public int id { get; set; } - - /// - /// Gets or sets the rating value. - /// - public int rating { get; set; } - - /// - /// Gets or sets whether or not this review recommends this item. - /// - public bool recommend { get; set; } - - /// - /// Gets or sets a short description of the review. - /// - public string title { get; set; } - - /// - /// Gets or sets the full review. - /// - public string review { get; set; } - - /// - /// Gets or sets the time of review. - /// - public DateTime timestamp { get; set; } - } -} diff --git a/MediaBrowser.Model/Entities/SpecialFolder.cs b/MediaBrowser.Model/Entities/SpecialFolder.cs new file mode 100644 index 0000000000..2250c5dffb --- /dev/null +++ b/MediaBrowser.Model/Entities/SpecialFolder.cs @@ -0,0 +1,36 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Model.Entities +{ + public static class SpecialFolder + { + public const string TvShowSeries = "TvShowSeries"; + public const string TvGenres = "TvGenres"; + public const string TvGenre = "TvGenre"; + public const string TvLatest = "TvLatest"; + public const string TvNextUp = "TvNextUp"; + public const string TvResume = "TvResume"; + public const string TvFavoriteSeries = "TvFavoriteSeries"; + public const string TvFavoriteEpisodes = "TvFavoriteEpisodes"; + + public const string MovieLatest = "MovieLatest"; + public const string MovieResume = "MovieResume"; + public const string MovieMovies = "MovieMovies"; + public const string MovieCollections = "MovieCollections"; + public const string MovieFavorites = "MovieFavorites"; + public const string MovieGenres = "MovieGenres"; + public const string MovieGenre = "MovieGenre"; + + public const string MusicArtists = "MusicArtists"; + public const string MusicAlbumArtists = "MusicAlbumArtists"; + public const string MusicAlbums = "MusicAlbums"; + public const string MusicGenres = "MusicGenres"; + public const string MusicLatest = "MusicLatest"; + public const string MusicPlaylists = "MusicPlaylists"; + public const string MusicSongs = "MusicSongs"; + public const string MusicFavorites = "MusicFavorites"; + public const string MusicFavoriteArtists = "MusicFavoriteArtists"; + public const string MusicFavoriteAlbums = "MusicFavoriteAlbums"; + public const string MusicFavoriteSongs = "MusicFavoriteSongs"; + } +} diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs index f2bc6f25e0..1b0e592401 100644 --- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs +++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs @@ -11,6 +11,14 @@ namespace MediaBrowser.Model.Entities /// public class VirtualFolderInfo { + /// + /// Initializes a new instance of the class. + /// + public VirtualFolderInfo() + { + Locations = Array.Empty(); + } + /// /// Gets or sets the name. /// @@ -31,14 +39,6 @@ namespace MediaBrowser.Model.Entities public LibraryOptions LibraryOptions { get; set; } - /// - /// Initializes a new instance of the class. - /// - public VirtualFolderInfo() - { - Locations = Array.Empty(); - } - /// /// Gets or sets the item identifier. /// diff --git a/MediaBrowser.Model/Globalization/CultureDto.cs b/MediaBrowser.Model/Globalization/CultureDto.cs index 6af4a872ce..5246f87d92 100644 --- a/MediaBrowser.Model/Globalization/CultureDto.cs +++ b/MediaBrowser.Model/Globalization/CultureDto.cs @@ -10,6 +10,11 @@ namespace MediaBrowser.Model.Globalization /// public class CultureDto { + public CultureDto() + { + ThreeLetterISOLanguageNames = Array.Empty(); + } + /// /// Gets or sets the name. /// @@ -29,7 +34,7 @@ namespace MediaBrowser.Model.Globalization public string TwoLetterISOLanguageName { get; set; } /// - /// Gets or sets the name of the three letter ISO language. + /// Gets the name of the three letter ISO language. /// /// The name of the three letter ISO language. public string ThreeLetterISOLanguageName @@ -47,10 +52,5 @@ namespace MediaBrowser.Model.Globalization } public string[] ThreeLetterISOLanguageNames { get; set; } - - public CultureDto() - { - ThreeLetterISOLanguageNames = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index dc65497876..ef08ecec66 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -155,13 +155,16 @@ namespace MediaBrowser.Model.IO /// Gets the directories. /// /// The path. - /// if set to true [recursive]. - /// IEnumerable<DirectoryInfo>. + /// If set to true also searches in subdirectiories. + /// All found directories. IEnumerable GetDirectories(string path, bool recursive = false); /// /// Gets the files. /// + /// The path in which to search. + /// If set to true also searches in subdirectiories. + /// All found files. IEnumerable GetFiles(string path, bool recursive = false); IEnumerable GetFiles(string path, IReadOnlyList extensions, bool enableCaseSensitiveExtensions, bool recursive); diff --git a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs index 07e76d9600..c6de4c1ab8 100644 --- a/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs +++ b/MediaBrowser.Model/LiveTv/BaseTimerInfoDto.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Model.LiveTv public class BaseTimerInfoDto : IHasServerId { /// - /// Id of the recording. + /// Gets or sets the Id of the recording. /// public string Id { get; set; } @@ -28,7 +28,7 @@ namespace MediaBrowser.Model.LiveTv public string ExternalId { get; set; } /// - /// ChannelId of the recording. + /// Gets or sets the channel id of the recording. /// public Guid ChannelId { get; set; } @@ -39,7 +39,7 @@ namespace MediaBrowser.Model.LiveTv public string ExternalChannelId { get; set; } /// - /// ChannelName of the recording. + /// Gets or sets the channel name of the recording. /// public string ChannelName { get; set; } @@ -58,22 +58,22 @@ namespace MediaBrowser.Model.LiveTv public string ExternalProgramId { get; set; } /// - /// Name of the recording. + /// Gets or sets the name of the recording. /// public string Name { get; set; } /// - /// Description of the recording. + /// Gets or sets the description of the recording. /// public string Overview { get; set; } /// - /// The start date of the recording, in UTC. + /// Gets or sets the start date of the recording, in UTC. /// public DateTime StartDate { get; set; } /// - /// The end date of the recording, in UTC. + /// Gets or sets the end date of the recording, in UTC. /// public DateTime EndDate { get; set; } @@ -108,7 +108,7 @@ namespace MediaBrowser.Model.LiveTv public bool IsPrePaddingRequired { get; set; } /// - /// If the item does not have any backdrops, this will hold the Id of the Parent that has one. + /// Gets or sets the Id of the Parent that has a backdrop if the item does not have one. /// /// The parent backdrop item id. public string ParentBackdropItemId { get; set; } diff --git a/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs b/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs new file mode 100644 index 0000000000..082daeb51b --- /dev/null +++ b/MediaBrowser.Model/LiveTv/ListingsProviderInfo.cs @@ -0,0 +1,58 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; +using MediaBrowser.Model.Dto; + +namespace MediaBrowser.Model.LiveTv +{ + public class ListingsProviderInfo + { + public ListingsProviderInfo() + { + NewsCategories = new[] { "news", "journalism", "documentary", "current affairs" }; + SportsCategories = new[] { "sports", "basketball", "baseball", "football" }; + KidsCategories = new[] { "kids", "family", "children", "childrens", "disney" }; + MovieCategories = new[] { "movie" }; + EnabledTuners = Array.Empty(); + EnableAllTuners = true; + ChannelMappings = Array.Empty(); + } + + public string Id { get; set; } + + public string Type { get; set; } + + public string Username { get; set; } + + public string Password { get; set; } + + public string ListingsId { get; set; } + + public string ZipCode { get; set; } + + public string Country { get; set; } + + public string Path { get; set; } + + public string[] EnabledTuners { get; set; } + + public bool EnableAllTuners { get; set; } + + public string[] NewsCategories { get; set; } + + public string[] SportsCategories { get; set; } + + public string[] KidsCategories { get; set; } + + public string[] MovieCategories { get; set; } + + public NameValuePair[] ChannelMappings { get; set; } + + public string MoviePrefix { get; set; } + + public string PreferredLanguage { get; set; } + + public string UserAgent { get; set; } + } +} diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs index bcba344cc5..ca8defd8ba 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs @@ -11,6 +11,12 @@ namespace MediaBrowser.Model.LiveTv /// public class LiveTvChannelQuery { + public LiveTvChannelQuery() + { + EnableUserData = true; + SortBy = Array.Empty(); + } + /// /// Gets or sets the type of the channel. /// @@ -48,13 +54,13 @@ namespace MediaBrowser.Model.LiveTv public Guid UserId { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// gets or sets the start index. Used for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } @@ -68,15 +74,15 @@ namespace MediaBrowser.Model.LiveTv public bool EnableUserData { get; set; } /// - /// Used to specific whether to return news or not. + /// Gets or sets a value whether to return news or not. /// - /// If set to null, all programs will be returned + /// If set to null, all programs will be returned. public bool? IsNews { get; set; } /// - /// Used to specific whether to return movies or not. + /// Gets or sets a value whether to return movies or not. /// - /// If set to null, all programs will be returned + /// If set to null, all programs will be returned. public bool? IsMovie { get; set; } /// @@ -96,15 +102,9 @@ namespace MediaBrowser.Model.LiveTv public string[] SortBy { get; set; } /// - /// The sort order to return results with. + /// Gets or sets the sort order to return results with. /// /// The sort order. public SortOrder? SortOrder { get; set; } - - public LiveTvChannelQuery() - { - EnableUserData = true; - SortBy = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index 789de3198a..4cece941cf 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -2,12 +2,19 @@ #pragma warning disable CS1591 using System; -using MediaBrowser.Model.Dto; namespace MediaBrowser.Model.LiveTv { public class LiveTvOptions { + public LiveTvOptions() + { + TunerHosts = Array.Empty(); + ListingProviders = Array.Empty(); + MediaLocationsCreated = Array.Empty(); + RecordingPostProcessorArguments = "\"{path}\""; + } + public int? GuideDays { get; set; } public string RecordingPath { get; set; } @@ -33,93 +40,5 @@ namespace MediaBrowser.Model.LiveTv public string RecordingPostProcessor { get; set; } public string RecordingPostProcessorArguments { get; set; } - - public LiveTvOptions() - { - TunerHosts = Array.Empty(); - ListingProviders = Array.Empty(); - MediaLocationsCreated = Array.Empty(); - RecordingPostProcessorArguments = "\"{path}\""; - } - } - - public class TunerHostInfo - { - public string Id { get; set; } - - public string Url { get; set; } - - public string Type { get; set; } - - public string DeviceId { get; set; } - - public string FriendlyName { get; set; } - - public bool ImportFavoritesOnly { get; set; } - - public bool AllowHWTranscoding { get; set; } - - public bool EnableStreamLooping { get; set; } - - public string Source { get; set; } - - public int TunerCount { get; set; } - - public string UserAgent { get; set; } - - public TunerHostInfo() - { - AllowHWTranscoding = true; - } - } - - public class ListingsProviderInfo - { - public string Id { get; set; } - - public string Type { get; set; } - - public string Username { get; set; } - - public string Password { get; set; } - - public string ListingsId { get; set; } - - public string ZipCode { get; set; } - - public string Country { get; set; } - - public string Path { get; set; } - - public string[] EnabledTuners { get; set; } - - public bool EnableAllTuners { get; set; } - - public string[] NewsCategories { get; set; } - - public string[] SportsCategories { get; set; } - - public string[] KidsCategories { get; set; } - - public string[] MovieCategories { get; set; } - - public NameValuePair[] ChannelMappings { get; set; } - - public string MoviePrefix { get; set; } - - public string PreferredLanguage { get; set; } - - public string UserAgent { get; set; } - - public ListingsProviderInfo() - { - NewsCategories = new[] { "news", "journalism", "documentary", "current affairs" }; - SportsCategories = new[] { "sports", "basketball", "baseball", "football" }; - KidsCategories = new[] { "kids", "family", "children", "childrens", "disney" }; - MovieCategories = new[] { "movie" }; - EnabledTuners = Array.Empty(); - EnableAllTuners = true; - ChannelMappings = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs index 856f638c5c..ef5c5d2f31 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvServiceInfo.cs @@ -10,6 +10,11 @@ namespace MediaBrowser.Model.LiveTv /// public class LiveTvServiceInfo { + public LiveTvServiceInfo() + { + Tuners = Array.Empty(); + } + /// /// Gets or sets the name. /// @@ -53,10 +58,5 @@ namespace MediaBrowser.Model.LiveTv public bool IsVisible { get; set; } public string[] Tuners { get; set; } - - public LiveTvServiceInfo() - { - Tuners = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/LiveTv/RecordingQuery.cs b/MediaBrowser.Model/LiveTv/RecordingQuery.cs index 69e7db4708..99bb1603c3 100644 --- a/MediaBrowser.Model/LiveTv/RecordingQuery.cs +++ b/MediaBrowser.Model/LiveTv/RecordingQuery.cs @@ -12,6 +12,11 @@ namespace MediaBrowser.Model.LiveTv /// public class RecordingQuery { + public RecordingQuery() + { + EnableTotalRecordCount = true; + } + /// /// Gets or sets the channel identifier. /// @@ -31,13 +36,13 @@ namespace MediaBrowser.Model.LiveTv public string Id { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Use for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } @@ -61,7 +66,7 @@ namespace MediaBrowser.Model.LiveTv public string SeriesTimerId { get; set; } /// - /// Fields to return within the items, in addition to basic information. + /// Gets or sets the fields to return within the items, in addition to basic information. /// /// The fields. public ItemFields[] Fields { get; set; } @@ -85,10 +90,5 @@ namespace MediaBrowser.Model.LiveTv public ImageType[] EnableImageTypes { get; set; } public bool EnableTotalRecordCount { get; set; } - - public RecordingQuery() - { - EnableTotalRecordCount = true; - } } } diff --git a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs index 90422d19c3..b26f5f45fe 100644 --- a/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs +++ b/MediaBrowser.Model/LiveTv/SeriesTimerInfoDto.cs @@ -7,6 +7,14 @@ using MediaBrowser.Model.Entities; namespace MediaBrowser.Model.LiveTv { + public enum KeepUntil + { + UntilDeleted, + UntilSpaceNeeded, + UntilWatched, + UntilDate + } + /// /// Class SeriesTimerInfoDto. /// @@ -83,12 +91,4 @@ namespace MediaBrowser.Model.LiveTv /// The parent primary image tag. public string ParentPrimaryImageTag { get; set; } } - - public enum KeepUntil - { - UntilDeleted, - UntilSpaceNeeded, - UntilWatched, - UntilDate - } } diff --git a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs new file mode 100644 index 0000000000..7d4bbb2d07 --- /dev/null +++ b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs @@ -0,0 +1,38 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; +using MediaBrowser.Model.Dto; + +namespace MediaBrowser.Model.LiveTv +{ + public class TunerHostInfo + { + public TunerHostInfo() + { + AllowHWTranscoding = true; + } + + public string Id { get; set; } + + public string Url { get; set; } + + public string Type { get; set; } + + public string DeviceId { get; set; } + + public string FriendlyName { get; set; } + + public bool ImportFavoritesOnly { get; set; } + + public bool AllowHWTranscoding { get; set; } + + public bool EnableStreamLooping { get; set; } + + public string Source { get; set; } + + public int TunerCount { get; set; } + + public string UserAgent { get; set; } + } +} diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index c534286510..b6d9169139 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -17,7 +17,7 @@ net5.0 false true - true + true enable latest true @@ -44,7 +44,7 @@ - + diff --git a/MediaBrowser.Model/MediaInfo/MediaInfo.cs b/MediaBrowser.Model/MediaInfo/MediaInfo.cs index 472055c22c..a268a4fa66 100644 --- a/MediaBrowser.Model/MediaInfo/MediaInfo.cs +++ b/MediaBrowser.Model/MediaInfo/MediaInfo.cs @@ -10,6 +10,17 @@ namespace MediaBrowser.Model.MediaInfo { public class MediaInfo : MediaSourceInfo, IHasProviderIds { + public MediaInfo() + { + Chapters = Array.Empty(); + Artists = Array.Empty(); + AlbumArtists = Array.Empty(); + Studios = Array.Empty(); + Genres = Array.Empty(); + People = Array.Empty(); + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + public ChapterInfo[] Chapters { get; set; } /// @@ -69,16 +80,5 @@ namespace MediaBrowser.Model.MediaInfo /// /// The overview. public string Overview { get; set; } - - public MediaInfo() - { - Chapters = Array.Empty(); - Artists = Array.Empty(); - AlbumArtists = Array.Empty(); - Studios = Array.Empty(); - Genres = Array.Empty(); - People = Array.Empty(); - ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } } } diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs index 3216856777..ecd9b8834e 100644 --- a/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs +++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoRequest.cs @@ -8,6 +8,17 @@ namespace MediaBrowser.Model.MediaInfo { public class PlaybackInfoRequest { + public PlaybackInfoRequest() + { + EnableDirectPlay = true; + EnableDirectStream = true; + EnableTranscoding = true; + AllowVideoStreamCopy = true; + AllowAudioStreamCopy = true; + IsPlayback = true; + DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; + } + public Guid Id { get; set; } public Guid UserId { get; set; } @@ -43,16 +54,5 @@ namespace MediaBrowser.Model.MediaInfo public bool AutoOpenLiveStream { get; set; } public MediaProtocol[] DirectPlayProtocols { get; set; } - - public PlaybackInfoRequest() - { - EnableDirectPlay = true; - EnableDirectStream = true; - EnableTranscoding = true; - AllowVideoStreamCopy = true; - AllowAudioStreamCopy = true; - IsPlayback = true; - DirectPlayProtocols = new MediaProtocol[] { MediaProtocol.Http }; - } } } diff --git a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs index 2733501822..32971b108f 100644 --- a/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs +++ b/MediaBrowser.Model/MediaInfo/PlaybackInfoResponse.cs @@ -10,6 +10,14 @@ namespace MediaBrowser.Model.MediaInfo /// public class PlaybackInfoResponse { + /// + /// Initializes a new instance of the class. + /// + public PlaybackInfoResponse() + { + MediaSources = Array.Empty(); + } + /// /// Gets or sets the media sources. /// @@ -27,13 +35,5 @@ namespace MediaBrowser.Model.MediaInfo /// /// The error code. public PlaybackErrorCode? ErrorCode { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public PlaybackInfoResponse() - { - MediaSources = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs b/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs index 37f5c55da6..d5c3a6aec5 100644 --- a/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs +++ b/MediaBrowser.Model/MediaInfo/SubtitleTrackInfo.cs @@ -7,11 +7,11 @@ namespace MediaBrowser.Model.MediaInfo { public class SubtitleTrackInfo { - public IReadOnlyList TrackEvents { get; set; } - public SubtitleTrackInfo() { TrackEvents = Array.Empty(); } + + public IReadOnlyList TrackEvents { get; set; } } } diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs index 5b6ed92df1..3de41d565a 100644 --- a/MediaBrowser.Model/Net/ISocket.cs +++ b/MediaBrowser.Model/Net/ISocket.cs @@ -23,6 +23,12 @@ namespace MediaBrowser.Model.Net /// /// Sends a UDP message to a particular end point (uni or multicast). /// + /// An array of type that contains the data to send. + /// The zero-based position in buffer at which to begin sending data. + /// The number of bytes to send. + /// An that represents the remote device. + /// The cancellation token to cancel operation. + /// The task object representing the asynchronous operation. Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index 363abefc19..1527ef595c 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -14,6 +14,9 @@ namespace MediaBrowser.Model.Net /// /// Creates a new unicast socket using the specified local port number. /// + /// The local IP address to bind to. + /// The local port to bind to. + /// A new unicast socket using the specified local port number. ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort); /// diff --git a/MediaBrowser.Model/Net/MimeTypes.cs b/MediaBrowser.Model/Net/MimeTypes.cs index 902db1e9e5..96f5ab51ae 100644 --- a/MediaBrowser.Model/Net/MimeTypes.cs +++ b/MediaBrowser.Model/Net/MimeTypes.cs @@ -91,9 +91,9 @@ namespace MediaBrowser.Model.Net { ".webp", "image/webp" }, // Type font - { ".ttf" , "font/ttf" }, - { ".woff" , "font/woff" }, - { ".woff2" , "font/woff2" }, + { ".ttf", "font/ttf" }, + { ".woff", "font/woff" }, + { ".woff2", "font/woff2" }, // Type text { ".ass", "text/x-ssa" }, @@ -168,14 +168,17 @@ namespace MediaBrowser.Model.Net /// /// Gets the type of the MIME. /// - public static string? GetMimeType(string path, bool enableStreamDefault) + /// The filename to find the MIME type of. + /// Whether of not to return a default value if no fitting MIME type is found. + /// The worrect MIME type for the given filename, or `null` if it wasn't found and is false. + public static string? GetMimeType(string filename, bool enableStreamDefault) { - if (path.Length == 0) + if (filename.Length == 0) { - throw new ArgumentException("String can't be empty.", nameof(path)); + throw new ArgumentException("String can't be empty.", nameof(filename)); } - var ext = Path.GetExtension(path); + var ext = Path.GetExtension(filename); if (_mimeTypeLookup.TryGetValue(ext, out string? result)) { @@ -210,9 +213,9 @@ namespace MediaBrowser.Model.Net return enableStreamDefault ? "application/octet-stream" : null; } - public static string? ToExtension(string? mimeType) + public static string? ToExtension(string mimeType) { - if (string.IsNullOrEmpty(mimeType)) + if (mimeType.Length == 0) { throw new ArgumentException("String can't be empty.", nameof(mimeType)); } diff --git a/MediaBrowser.Model/Net/NetworkShare.cs b/MediaBrowser.Model/Net/NetworkShare.cs deleted file mode 100644 index 6344cbe21e..0000000000 --- a/MediaBrowser.Model/Net/NetworkShare.cs +++ /dev/null @@ -1,33 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -namespace MediaBrowser.Model.Net -{ - public class NetworkShare - { - /// - /// The name of the computer that this share belongs to. - /// - public string Server { get; set; } - - /// - /// Share name. - /// - public string Name { get; set; } - - /// - /// Local path. - /// - public string Path { get; set; } - - /// - /// Share type. - /// - public NetworkShareType ShareType { get; set; } - - /// - /// Comment. - /// - public string Remark { get; set; } - } -} diff --git a/MediaBrowser.Model/Net/SocketReceiveResult.cs b/MediaBrowser.Model/Net/SocketReceiveResult.cs index 54139fe9c5..1524786ea7 100644 --- a/MediaBrowser.Model/Net/SocketReceiveResult.cs +++ b/MediaBrowser.Model/Net/SocketReceiveResult.cs @@ -20,12 +20,12 @@ namespace MediaBrowser.Model.Net public int ReceivedBytes { get; set; } /// - /// The the data was received from. + /// Gets or sets the the data was received from. /// public IPEndPoint RemoteEndPoint { get; set; } /// - /// The local . + /// Gets or sets the local . /// public IPAddress LocalIPAddress { get; set; } } diff --git a/MediaBrowser.Model/Net/WebSocketMessage.cs b/MediaBrowser.Model/Net/WebSocketMessage.cs index bffbbe612d..b00158cb33 100644 --- a/MediaBrowser.Model/Net/WebSocketMessage.cs +++ b/MediaBrowser.Model/Net/WebSocketMessage.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Model.Net /// /// Class WebSocketMessage. /// - /// + /// The type of the data. public class WebSocketMessage { /// diff --git a/MediaBrowser.Model/Notifications/NotificationOptions.cs b/MediaBrowser.Model/Notifications/NotificationOptions.cs index 239a3777e1..94bb5d6e35 100644 --- a/MediaBrowser.Model/Notifications/NotificationOptions.cs +++ b/MediaBrowser.Model/Notifications/NotificationOptions.cs @@ -2,18 +2,16 @@ #pragma warning disable CS1591 using System; -using Jellyfin.Data.Enums; -using MediaBrowser.Model.Extensions; using System.Linq; using Jellyfin.Data.Entities; +using Jellyfin.Data.Enums; +using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Users; namespace MediaBrowser.Model.Notifications { public class NotificationOptions { - public NotificationOption[] Options { get; set; } - public NotificationOptions() { Options = new[] @@ -71,6 +69,8 @@ namespace MediaBrowser.Model.Notifications }; } + public NotificationOption[] Options { get; set; } + public NotificationOption GetOptions(string type) { foreach (NotificationOption i in Options) @@ -104,7 +104,7 @@ namespace MediaBrowser.Model.Notifications NotificationOption opt = GetOptions(type); return opt != null && opt.Enabled && - !opt.DisabledMonitorUsers.Contains(userId.ToString(""), StringComparer.OrdinalIgnoreCase); + !opt.DisabledMonitorUsers.Contains(userId.ToString(string.Empty), StringComparer.OrdinalIgnoreCase); } public bool IsEnabledToSendToUser(string type, string userId, User user) diff --git a/MediaBrowser.Model/Notifications/NotificationRequest.cs b/MediaBrowser.Model/Notifications/NotificationRequest.cs index febc2bc099..622c50cd88 100644 --- a/MediaBrowser.Model/Notifications/NotificationRequest.cs +++ b/MediaBrowser.Model/Notifications/NotificationRequest.cs @@ -7,6 +7,12 @@ namespace MediaBrowser.Model.Notifications { public class NotificationRequest { + public NotificationRequest() + { + UserIds = Array.Empty(); + Date = DateTime.UtcNow; + } + public string Name { get; set; } public string Description { get; set; } @@ -20,16 +26,10 @@ namespace MediaBrowser.Model.Notifications public DateTime Date { get; set; } /// - /// The corresponding type name used in configuration. Not for display. + /// Gets or sets the corresponding type name used in configuration. Not for display. /// public string NotificationType { get; set; } public SendToUserType? SendToUserMode { get; set; } - - public NotificationRequest() - { - UserIds = Array.Empty(); - Date = DateTime.UtcNow; - } } } diff --git a/MediaBrowser.Model/Providers/ExternalIdInfo.cs b/MediaBrowser.Model/Providers/ExternalIdInfo.cs index afe95e6eee..0ea3e96cae 100644 --- a/MediaBrowser.Model/Providers/ExternalIdInfo.cs +++ b/MediaBrowser.Model/Providers/ExternalIdInfo.cs @@ -6,11 +6,11 @@ namespace MediaBrowser.Model.Providers public class ExternalIdInfo { /// - /// Represents the external id information for serialization to the client. + /// Initializes a new instance of the class. /// /// Name of the external id provider (IE: IMDB, MusicBrainz, etc). /// Key for this id. This key should be unique across all providers. - /// Specific media type for this id + /// Specific media type for this id. /// URL format string. public ExternalIdInfo(string name, string key, ExternalIdMediaType? type, string urlFormatString) { diff --git a/MediaBrowser.Model/Providers/RemoteImageInfo.cs b/MediaBrowser.Model/Providers/RemoteImageInfo.cs index fb25999e0a..48207d2d41 100644 --- a/MediaBrowser.Model/Providers/RemoteImageInfo.cs +++ b/MediaBrowser.Model/Providers/RemoteImageInfo.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.Model.Providers public string Url { get; set; } /// - /// Gets a url used for previewing a smaller version. + /// Gets or sets a url used for previewing a smaller version. /// public string ThumbnailUrl { get; set; } diff --git a/MediaBrowser.Model/Providers/SubtitleOptions.cs b/MediaBrowser.Model/Providers/SubtitleOptions.cs index 5702c460b0..6ea1e14862 100644 --- a/MediaBrowser.Model/Providers/SubtitleOptions.cs +++ b/MediaBrowser.Model/Providers/SubtitleOptions.cs @@ -7,6 +7,14 @@ namespace MediaBrowser.Model.Providers { public class SubtitleOptions { + public SubtitleOptions() + { + DownloadLanguages = Array.Empty(); + + SkipIfAudioTrackMatches = true; + RequirePerfectMatch = true; + } + public bool SkipIfEmbeddedSubtitlesPresent { get; set; } public bool SkipIfAudioTrackMatches { get; set; } @@ -24,13 +32,5 @@ namespace MediaBrowser.Model.Providers public bool IsOpenSubtitleVipAccount { get; set; } public bool RequirePerfectMatch { get; set; } - - public SubtitleOptions() - { - DownloadLanguages = Array.Empty(); - - SkipIfAudioTrackMatches = true; - RequirePerfectMatch = true; - } } } diff --git a/MediaBrowser.Model/Querying/EpisodeQuery.cs b/MediaBrowser.Model/Querying/EpisodeQuery.cs index 13b1a0dcbf..56a7f33201 100644 --- a/MediaBrowser.Model/Querying/EpisodeQuery.cs +++ b/MediaBrowser.Model/Querying/EpisodeQuery.cs @@ -7,6 +7,11 @@ namespace MediaBrowser.Model.Querying { public class EpisodeQuery { + public EpisodeQuery() + { + Fields = Array.Empty(); + } + /// /// Gets or sets the user identifier. /// @@ -66,10 +71,5 @@ namespace MediaBrowser.Model.Querying /// /// The start item identifier. public string StartItemId { get; set; } - - public EpisodeQuery() - { - Fields = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Querying/LatestItemsQuery.cs b/MediaBrowser.Model/Querying/LatestItemsQuery.cs index 7954ef4b43..f555ffb36d 100644 --- a/MediaBrowser.Model/Querying/LatestItemsQuery.cs +++ b/MediaBrowser.Model/Querying/LatestItemsQuery.cs @@ -14,31 +14,32 @@ namespace MediaBrowser.Model.Querying } /// - /// The user to localize search results for. + /// Gets or sets the user to localize search results for. /// /// The user id. public Guid UserId { get; set; } /// + /// Gets or sets the parent id. /// Specify this to localize the search to a specific item or folder. Omit to use the root. /// /// The parent id. public Guid ParentId { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Used for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } /// - /// Fields to return within the items, in addition to basic information. + /// Gets or sets the fields to return within the items, in addition to basic information. /// /// The fields. public ItemFields[] Fields { get; set; } diff --git a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs b/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs index 1c8875890a..b800f5de5f 100644 --- a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs +++ b/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs @@ -7,6 +7,13 @@ namespace MediaBrowser.Model.Querying { public class MovieRecommendationQuery { + public MovieRecommendationQuery() + { + ItemLimit = 10; + CategoryLimit = 6; + Fields = Array.Empty(); + } + /// /// Gets or sets the user identifier. /// @@ -36,12 +43,5 @@ namespace MediaBrowser.Model.Querying /// /// The fields. public ItemFields[] Fields { get; set; } - - public MovieRecommendationQuery() - { - ItemLimit = 10; - CategoryLimit = 6; - Fields = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index 001d0623cc..0555afc00d 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -8,6 +8,13 @@ namespace MediaBrowser.Model.Querying { public class NextUpQuery { + public NextUpQuery() + { + EnableImageTypes = Array.Empty(); + EnableTotalRecordCount = true; + DisableFirstEpisode = false; + } + /// /// Gets or sets the user id. /// @@ -27,19 +34,19 @@ namespace MediaBrowser.Model.Querying public string SeriesId { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Use for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } /// - /// Fields to return within the items, in addition to basic information. + /// gets or sets the fields to return within the items, in addition to basic information. /// /// The fields. public ItemFields[] Fields { get; set; } @@ -68,12 +75,5 @@ namespace MediaBrowser.Model.Querying /// Gets or sets a value indicating whether do disable sending first episode as next up. /// public bool DisableFirstEpisode { get; set; } - - public NextUpQuery() - { - EnableImageTypes = Array.Empty(); - EnableTotalRecordCount = true; - DisableFirstEpisode = false; - } } } diff --git a/MediaBrowser.Model/Querying/QueryFilters.cs b/MediaBrowser.Model/Querying/QueryFilters.cs index 6e4d251818..73b27a7b06 100644 --- a/MediaBrowser.Model/Querying/QueryFilters.cs +++ b/MediaBrowser.Model/Querying/QueryFilters.cs @@ -6,35 +6,16 @@ using MediaBrowser.Model.Dto; namespace MediaBrowser.Model.Querying { - public class QueryFiltersLegacy - { - public string[] Genres { get; set; } - - public string[] Tags { get; set; } - - public string[] OfficialRatings { get; set; } - - public int[] Years { get; set; } - - public QueryFiltersLegacy() - { - Genres = Array.Empty(); - Tags = Array.Empty(); - OfficialRatings = Array.Empty(); - Years = Array.Empty(); - } - } - public class QueryFilters { - public NameGuidPair[] Genres { get; set; } - - public string[] Tags { get; set; } - public QueryFilters() { Tags = Array.Empty(); Genres = Array.Empty(); } + + public NameGuidPair[] Genres { get; set; } + + public string[] Tags { get; set; } } } diff --git a/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs b/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs new file mode 100644 index 0000000000..fcb450ed30 --- /dev/null +++ b/MediaBrowser.Model/Querying/QueryFiltersLegacy.cs @@ -0,0 +1,26 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; + +namespace MediaBrowser.Model.Querying +{ + public class QueryFiltersLegacy + { + public QueryFiltersLegacy() + { + Genres = Array.Empty(); + Tags = Array.Empty(); + OfficialRatings = Array.Empty(); + Years = Array.Empty(); + } + + public string[] Genres { get; set; } + + public string[] Tags { get; set; } + + public string[] OfficialRatings { get; set; } + + public int[] Years { get; set; } + } +} diff --git a/MediaBrowser.Model/Querying/QueryResult.cs b/MediaBrowser.Model/Querying/QueryResult.cs index 490f48b84b..8ce794800b 100644 --- a/MediaBrowser.Model/Querying/QueryResult.cs +++ b/MediaBrowser.Model/Querying/QueryResult.cs @@ -8,24 +8,6 @@ namespace MediaBrowser.Model.Querying { public class QueryResult { - /// - /// Gets or sets the items. - /// - /// The items. - public IReadOnlyList Items { get; set; } - - /// - /// The total number of records available. - /// - /// The total record count. - public int TotalRecordCount { get; set; } - - /// - /// The index of the first record in Items. - /// - /// First record index. - public int StartIndex { get; set; } - public QueryResult() { Items = Array.Empty(); @@ -36,5 +18,23 @@ namespace MediaBrowser.Model.Querying Items = items; TotalRecordCount = items.Count; } + + /// + /// Gets or sets the items. + /// + /// The items. + public IReadOnlyList Items { get; set; } + + /// + /// Gets or sets the total number of records available. + /// + /// The total record count. + public int TotalRecordCount { get; set; } + + /// + /// Gets or sets the index of the first record in Items. + /// + /// First record index. + public int StartIndex { get; set; } } } diff --git a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs index eb62394605..2cf0f0d5f8 100644 --- a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs +++ b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs @@ -8,6 +8,11 @@ namespace MediaBrowser.Model.Querying { public class UpcomingEpisodesQuery { + public UpcomingEpisodesQuery() + { + EnableImageTypes = Array.Empty(); + } + /// /// Gets or sets the user id. /// @@ -21,19 +26,19 @@ namespace MediaBrowser.Model.Querying public string ParentId { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Use for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } /// - /// Fields to return within the items, in addition to basic information. + /// Gets or sets the fields to return within the items, in addition to basic information. /// /// The fields. public ItemFields[] Fields { get; set; } @@ -55,10 +60,5 @@ namespace MediaBrowser.Model.Querying /// /// The enable image types. public ImageType[] EnableImageTypes { get; set; } - - public UpcomingEpisodesQuery() - { - EnableImageTypes = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Search/SearchQuery.cs b/MediaBrowser.Model/Search/SearchQuery.cs index ce60062cd3..aedfa4d363 100644 --- a/MediaBrowser.Model/Search/SearchQuery.cs +++ b/MediaBrowser.Model/Search/SearchQuery.cs @@ -7,8 +7,21 @@ namespace MediaBrowser.Model.Search { public class SearchQuery { + public SearchQuery() + { + IncludeArtists = true; + IncludeGenres = true; + IncludeMedia = true; + IncludePeople = true; + IncludeStudios = true; + + MediaTypes = Array.Empty(); + IncludeItemTypes = Array.Empty(); + ExcludeItemTypes = Array.Empty(); + } + /// - /// The user to localize search results for. + /// Gets or sets the user to localize search results for. /// /// The user id. public Guid UserId { get; set; } @@ -20,13 +33,13 @@ namespace MediaBrowser.Model.Search public string SearchTerm { get; set; } /// - /// Skips over a given number of items within the results. Use for paging. + /// Gets or sets the start index. Used for paging. /// /// The start index. public int? StartIndex { get; set; } /// - /// The maximum number of items to return. + /// Gets or sets the maximum number of items to return. /// /// The limit. public int? Limit { get; set; } @@ -58,18 +71,5 @@ namespace MediaBrowser.Model.Search public bool? IsKids { get; set; } public bool? IsSports { get; set; } - - public SearchQuery() - { - IncludeArtists = true; - IncludeGenres = true; - IncludeMedia = true; - IncludePeople = true; - IncludeStudios = true; - - MediaTypes = Array.Empty(); - IncludeItemTypes = Array.Empty(); - ExcludeItemTypes = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Session/BrowseRequest.cs b/MediaBrowser.Model/Session/BrowseRequest.cs index 1c997d5846..65afe5cf34 100644 --- a/MediaBrowser.Model/Session/BrowseRequest.cs +++ b/MediaBrowser.Model/Session/BrowseRequest.cs @@ -7,6 +7,7 @@ namespace MediaBrowser.Model.Session public class BrowseRequest { /// + /// Gets or sets the item type. /// Artist, Genre, Studio, Person, or any kind of BaseItem. /// /// The type of the item. diff --git a/MediaBrowser.Model/Session/ClientCapabilities.cs b/MediaBrowser.Model/Session/ClientCapabilities.cs index 5852f4e37a..d692906c64 100644 --- a/MediaBrowser.Model/Session/ClientCapabilities.cs +++ b/MediaBrowser.Model/Session/ClientCapabilities.cs @@ -9,6 +9,13 @@ namespace MediaBrowser.Model.Session { public class ClientCapabilities { + public ClientCapabilities() + { + PlayableMediaTypes = Array.Empty(); + SupportedCommands = Array.Empty(); + SupportsPersistentIdentifier = true; + } + public IReadOnlyList PlayableMediaTypes { get; set; } public IReadOnlyList SupportedCommands { get; set; } @@ -28,12 +35,5 @@ namespace MediaBrowser.Model.Session public string AppStoreUrl { get; set; } public string IconUrl { get; set; } - - public ClientCapabilities() - { - PlayableMediaTypes = Array.Empty(); - SupportedCommands = Array.Empty(); - SupportsPersistentIdentifier = true; - } } } diff --git a/MediaBrowser.Model/Session/GeneralCommand.cs b/MediaBrowser.Model/Session/GeneralCommand.cs index 77bb6bcf77..29528c1106 100644 --- a/MediaBrowser.Model/Session/GeneralCommand.cs +++ b/MediaBrowser.Model/Session/GeneralCommand.cs @@ -1,4 +1,3 @@ -#nullable disable #pragma warning disable CS1591 using System; @@ -8,15 +7,15 @@ namespace MediaBrowser.Model.Session { public class GeneralCommand { - public GeneralCommandType Name { get; set; } - - public Guid ControllingUserId { get; set; } - - public Dictionary Arguments { get; set; } - public GeneralCommand() { Arguments = new Dictionary(); } + + public GeneralCommandType Name { get; set; } + + public Guid ControllingUserId { get; set; } + + public Dictionary Arguments { get; } } } diff --git a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs index 73dbe6a2da..a6e7efcb0c 100644 --- a/MediaBrowser.Model/Session/PlaybackProgressInfo.cs +++ b/MediaBrowser.Model/Session/PlaybackProgressInfo.cs @@ -111,18 +111,4 @@ namespace MediaBrowser.Model.Session public string PlaylistItemId { get; set; } } - - public enum RepeatMode - { - RepeatNone = 0, - RepeatAll = 1, - RepeatOne = 2 - } - - public class QueueItem - { - public Guid Id { get; set; } - - public string PlaylistItemId { get; set; } - } } diff --git a/MediaBrowser.Model/Session/PlaystateCommand.cs b/MediaBrowser.Model/Session/PlaystateCommand.cs index 3aa091f791..df47f3b73d 100644 --- a/MediaBrowser.Model/Session/PlaystateCommand.cs +++ b/MediaBrowser.Model/Session/PlaystateCommand.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - namespace MediaBrowser.Model.Session { /// @@ -46,6 +44,10 @@ namespace MediaBrowser.Model.Session /// The fast forward. /// FastForward, + + /// + /// The play pause. + /// PlayPause } } diff --git a/MediaBrowser.Model/Session/QueueItem.cs b/MediaBrowser.Model/Session/QueueItem.cs new file mode 100644 index 0000000000..32b19101b2 --- /dev/null +++ b/MediaBrowser.Model/Session/QueueItem.cs @@ -0,0 +1,14 @@ +#nullable disable +#pragma warning disable CS1591 + +using System; + +namespace MediaBrowser.Model.Session +{ + public class QueueItem + { + public Guid Id { get; set; } + + public string PlaylistItemId { get; set; } + } +} diff --git a/MediaBrowser.Model/Session/RepeatMode.cs b/MediaBrowser.Model/Session/RepeatMode.cs new file mode 100644 index 0000000000..c6e173d6b8 --- /dev/null +++ b/MediaBrowser.Model/Session/RepeatMode.cs @@ -0,0 +1,11 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Model.Session +{ + public enum RepeatMode + { + RepeatNone = 0, + RepeatAll = 1, + RepeatOne = 2 + } +} diff --git a/MediaBrowser.Model/Session/TranscodeReason.cs b/MediaBrowser.Model/Session/TranscodeReason.cs new file mode 100644 index 0000000000..e93b5d2882 --- /dev/null +++ b/MediaBrowser.Model/Session/TranscodeReason.cs @@ -0,0 +1,31 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Model.Session +{ + public enum TranscodeReason + { + ContainerNotSupported = 0, + VideoCodecNotSupported = 1, + AudioCodecNotSupported = 2, + ContainerBitrateExceedsLimit = 3, + AudioBitrateNotSupported = 4, + AudioChannelsNotSupported = 5, + VideoResolutionNotSupported = 6, + UnknownVideoStreamInfo = 7, + UnknownAudioStreamInfo = 8, + AudioProfileNotSupported = 9, + AudioSampleRateNotSupported = 10, + AnamorphicVideoNotSupported = 11, + InterlacedVideoNotSupported = 12, + SecondaryAudioNotSupported = 13, + RefFramesNotSupported = 14, + VideoBitDepthNotSupported = 15, + VideoBitrateNotSupported = 16, + VideoFramerateNotSupported = 17, + VideoLevelNotSupported = 18, + VideoProfileNotSupported = 19, + AudioBitDepthNotSupported = 20, + SubtitleCodecNotSupported = 21, + DirectPlayError = 22 + } +} diff --git a/MediaBrowser.Model/Session/TranscodingInfo.cs b/MediaBrowser.Model/Session/TranscodingInfo.cs index e832c2f6fa..064a087d5d 100644 --- a/MediaBrowser.Model/Session/TranscodingInfo.cs +++ b/MediaBrowser.Model/Session/TranscodingInfo.cs @@ -7,6 +7,11 @@ namespace MediaBrowser.Model.Session { public class TranscodingInfo { + public TranscodingInfo() + { + TranscodeReasons = Array.Empty(); + } + public string AudioCodec { get; set; } public string VideoCodec { get; set; } @@ -30,37 +35,5 @@ namespace MediaBrowser.Model.Session public int? AudioChannels { get; set; } public TranscodeReason[] TranscodeReasons { get; set; } - - public TranscodingInfo() - { - TranscodeReasons = Array.Empty(); - } - } - - public enum TranscodeReason - { - ContainerNotSupported = 0, - VideoCodecNotSupported = 1, - AudioCodecNotSupported = 2, - ContainerBitrateExceedsLimit = 3, - AudioBitrateNotSupported = 4, - AudioChannelsNotSupported = 5, - VideoResolutionNotSupported = 6, - UnknownVideoStreamInfo = 7, - UnknownAudioStreamInfo = 8, - AudioProfileNotSupported = 9, - AudioSampleRateNotSupported = 10, - AnamorphicVideoNotSupported = 11, - InterlacedVideoNotSupported = 12, - SecondaryAudioNotSupported = 13, - RefFramesNotSupported = 14, - VideoBitDepthNotSupported = 15, - VideoBitrateNotSupported = 16, - VideoFramerateNotSupported = 17, - VideoLevelNotSupported = 18, - VideoProfileNotSupported = 19, - AudioBitDepthNotSupported = 20, - SubtitleCodecNotSupported = 21, - DirectPlayError = 22 } } diff --git a/MediaBrowser.Model/Sync/SyncJob.cs b/MediaBrowser.Model/Sync/SyncJob.cs index b9290b6e83..3e396e5d13 100644 --- a/MediaBrowser.Model/Sync/SyncJob.cs +++ b/MediaBrowser.Model/Sync/SyncJob.cs @@ -7,6 +7,11 @@ namespace MediaBrowser.Model.Sync { public class SyncJob { + public SyncJob() + { + RequestedItemIds = Array.Empty(); + } + /// /// Gets or sets the identifier. /// @@ -126,10 +131,5 @@ namespace MediaBrowser.Model.Sync public string PrimaryImageItemId { get; set; } public string PrimaryImageTag { get; set; } - - public SyncJob() - { - RequestedItemIds = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/System/SystemInfo.cs b/MediaBrowser.Model/System/SystemInfo.cs index 4b83fb7e61..d75ae91c02 100644 --- a/MediaBrowser.Model/System/SystemInfo.cs +++ b/MediaBrowser.Model/System/SystemInfo.cs @@ -30,6 +30,14 @@ namespace MediaBrowser.Model.System /// public class SystemInfo : PublicSystemInfo { + /// + /// Initializes a new instance of the class. + /// + public SystemInfo() + { + CompletedInstallations = Array.Empty(); + } + /// /// Gets or sets the display name of the operating system. /// @@ -37,7 +45,7 @@ namespace MediaBrowser.Model.System public string OperatingSystemDisplayName { get; set; } /// - /// Get or sets the package name. + /// Gets or sets the package name. /// /// The value of the '-package' command line argument. public string PackageName { get; set; } @@ -127,13 +135,5 @@ namespace MediaBrowser.Model.System public FFmpegLocation EncoderLocation { get; set; } public Architecture SystemArchitecture { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public SystemInfo() - { - CompletedInstallations = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/System/WakeOnLanInfo.cs b/MediaBrowser.Model/System/WakeOnLanInfo.cs index b2cbe737d1..aba19a6baf 100644 --- a/MediaBrowser.Model/System/WakeOnLanInfo.cs +++ b/MediaBrowser.Model/System/WakeOnLanInfo.cs @@ -36,7 +36,7 @@ namespace MediaBrowser.Model.System /// Gets the MAC address of the device. /// /// The MAC address. - public string? MacAddress { get; set; } + public string? MacAddress { get; } /// /// Gets or sets the wake-on-LAN port. diff --git a/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs b/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs index 2f05e08c51..ca769e26b3 100644 --- a/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs +++ b/MediaBrowser.Model/Tasks/IScheduledTaskWorker.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Model.Tasks event EventHandler> TaskProgress; /// - /// Gets or sets the scheduled task. + /// Gets the scheduled task. /// /// The scheduled task. IScheduledTask ScheduledTask { get; } @@ -57,10 +57,9 @@ namespace MediaBrowser.Model.Tasks double? CurrentProgress { get; } /// - /// Gets the triggers that define when the task will run. + /// Gets or sets the triggers that define when the task will run. /// /// The triggers. - /// value TaskTriggerInfo[] Triggers { get; set; } /// diff --git a/MediaBrowser.Model/Tasks/ITaskManager.cs b/MediaBrowser.Model/Tasks/ITaskManager.cs index 02b29074e3..a86bf2a1c8 100644 --- a/MediaBrowser.Model/Tasks/ITaskManager.cs +++ b/MediaBrowser.Model/Tasks/ITaskManager.cs @@ -9,6 +9,10 @@ namespace MediaBrowser.Model.Tasks { public interface ITaskManager : IDisposable { + event EventHandler> TaskExecuting; + + event EventHandler TaskCompleted; + /// /// Gets the list of Scheduled Tasks. /// @@ -18,7 +22,7 @@ namespace MediaBrowser.Model.Tasks /// /// Cancels if running and queue. /// - /// + /// An implementatin of . /// Task options. void CancelIfRunningAndQueue(TaskOptions options) where T : IScheduledTask; @@ -26,21 +30,21 @@ namespace MediaBrowser.Model.Tasks /// /// Cancels if running and queue. /// - /// + /// An implementatin of . void CancelIfRunningAndQueue() where T : IScheduledTask; /// /// Cancels if running. /// - /// + /// An implementatin of . void CancelIfRunning() where T : IScheduledTask; /// /// Queues the scheduled task. /// - /// + /// An implementatin of . /// Task options. void QueueScheduledTask(TaskOptions options) where T : IScheduledTask; @@ -48,7 +52,7 @@ namespace MediaBrowser.Model.Tasks /// /// Queues the scheduled task. /// - /// + /// An implementatin of . void QueueScheduledTask() where T : IScheduledTask; @@ -58,6 +62,8 @@ namespace MediaBrowser.Model.Tasks /// /// Queues the scheduled task. /// + /// The to queue. + /// The to use. void QueueScheduledTask(IScheduledTask task, TaskOptions options); /// @@ -67,12 +73,10 @@ namespace MediaBrowser.Model.Tasks void AddTasks(IEnumerable tasks); void Cancel(IScheduledTaskWorker task); + Task Execute(IScheduledTaskWorker task, TaskOptions options); void Execute() where T : IScheduledTask; - - event EventHandler> TaskExecuting; - event EventHandler TaskCompleted; } } diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs index 5c30d6c220..cbd60cca18 100644 --- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs +++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs @@ -21,6 +21,10 @@ namespace MediaBrowser.Model.Tasks /// /// Stars waiting for the trigger action. /// + /// Result of the last run triggerd task. + /// The . + /// The name of the task. + /// Wheter or not this is is fired during startup. void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup); /// diff --git a/MediaBrowser.Model/Tasks/TaskInfo.cs b/MediaBrowser.Model/Tasks/TaskInfo.cs index 77100dfe76..16de0b1210 100644 --- a/MediaBrowser.Model/Tasks/TaskInfo.cs +++ b/MediaBrowser.Model/Tasks/TaskInfo.cs @@ -8,6 +8,14 @@ namespace MediaBrowser.Model.Tasks /// public class TaskInfo { + /// + /// Initializes a new instance of the class. + /// + public TaskInfo() + { + Triggers = Array.Empty(); + } + /// /// Gets or sets the name. /// @@ -67,13 +75,5 @@ namespace MediaBrowser.Model.Tasks /// /// The key. public string Key { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public TaskInfo() - { - Triggers = Array.Empty(); - } } } diff --git a/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs b/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs index 5aeaffc2b3..f8a8c727ef 100644 --- a/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs +++ b/MediaBrowser.Model/Tasks/TaskTriggerInfo.cs @@ -10,6 +10,12 @@ namespace MediaBrowser.Model.Tasks /// public class TaskTriggerInfo { + public const string TriggerDaily = "DailyTrigger"; + public const string TriggerWeekly = "WeeklyTrigger"; + public const string TriggerInterval = "IntervalTrigger"; + public const string TriggerSystemEvent = "SystemEventTrigger"; + public const string TriggerStartup = "StartupTrigger"; + /// /// Gets or sets the type. /// @@ -39,11 +45,5 @@ namespace MediaBrowser.Model.Tasks /// /// The maximum runtime ticks. public long? MaxRuntimeTicks { get; set; } - - public const string TriggerDaily = "DailyTrigger"; - public const string TriggerWeekly = "WeeklyTrigger"; - public const string TriggerInterval = "IntervalTrigger"; - public const string TriggerSystemEvent = "SystemEventTrigger"; - public const string TriggerStartup = "StartupTrigger"; } } diff --git a/MediaBrowser.Model/Users/UserPolicy.cs b/MediaBrowser.Model/Users/UserPolicy.cs index 37da04adf7..111070d813 100644 --- a/MediaBrowser.Model/Users/UserPolicy.cs +++ b/MediaBrowser.Model/Users/UserPolicy.cs @@ -10,6 +10,56 @@ namespace MediaBrowser.Model.Users { public class UserPolicy { + public UserPolicy() + { + IsHidden = true; + + EnableContentDeletion = false; + EnableContentDeletionFromFolders = Array.Empty(); + + EnableSyncTranscoding = true; + EnableMediaConversion = true; + + EnableMediaPlayback = true; + EnableAudioPlaybackTranscoding = true; + EnableVideoPlaybackTranscoding = true; + EnablePlaybackRemuxing = true; + ForceRemoteSourceTranscoding = false; + EnableLiveTvManagement = true; + EnableLiveTvAccess = true; + + // Without this on by default, admins won't be able to do this + // Improve in the future + EnableLiveTvManagement = true; + + EnableSharedDeviceControl = true; + + BlockedTags = Array.Empty(); + BlockUnratedItems = Array.Empty(); + + EnableUserPreferenceAccess = true; + + AccessSchedules = Array.Empty(); + + LoginAttemptsBeforeLockout = -1; + + MaxActiveSessions = 0; + + EnableAllChannels = true; + EnabledChannels = Array.Empty(); + + EnableAllFolders = true; + EnabledFolders = Array.Empty(); + + EnabledDevices = Array.Empty(); + EnableAllDevices = true; + + EnableContentDownloading = true; + EnablePublicSharing = true; + EnableRemoteAccess = true; + SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups; + } + /// /// Gets or sets a value indicating whether this instance is administrator. /// @@ -112,55 +162,5 @@ namespace MediaBrowser.Model.Users /// /// Access level to SyncPlay features. public SyncPlayUserAccessType SyncPlayAccess { get; set; } - - public UserPolicy() - { - IsHidden = true; - - EnableContentDeletion = false; - EnableContentDeletionFromFolders = Array.Empty(); - - EnableSyncTranscoding = true; - EnableMediaConversion = true; - - EnableMediaPlayback = true; - EnableAudioPlaybackTranscoding = true; - EnableVideoPlaybackTranscoding = true; - EnablePlaybackRemuxing = true; - ForceRemoteSourceTranscoding = false; - EnableLiveTvManagement = true; - EnableLiveTvAccess = true; - - // Without this on by default, admins won't be able to do this - // Improve in the future - EnableLiveTvManagement = true; - - EnableSharedDeviceControl = true; - - BlockedTags = Array.Empty(); - BlockUnratedItems = Array.Empty(); - - EnableUserPreferenceAccess = true; - - AccessSchedules = Array.Empty(); - - LoginAttemptsBeforeLockout = -1; - - MaxActiveSessions = 0; - - EnableAllChannels = true; - EnabledChannels = Array.Empty(); - - EnableAllFolders = true; - EnabledFolders = Array.Empty(); - - EnabledDevices = Array.Empty(); - EnableAllDevices = true; - - EnableContentDownloading = true; - EnablePublicSharing = true; - EnableRemoteAccess = true; - SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups; - } } } diff --git a/jellyfin.ruleset b/jellyfin.ruleset index fa09bfb66a..81337390cc 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -32,6 +32,8 @@ + + diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs b/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs index 544a74637a..92c534eaea 100644 --- a/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs +++ b/tests/Jellyfin.Api.Tests/ModelBinders/TestType.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Text; - namespace Jellyfin.Api.Tests.ModelBinders { public enum TestType { -#pragma warning disable SA1602 // Enumeration items should be documented How, Much, Is, The, Fish -#pragma warning restore SA1602 // Enumeration items should be documented } } From 40b9e7592f1990323b7c38ef9b869da9e5e873c9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 20 Feb 2021 23:34:15 +0100 Subject: [PATCH 1117/1930] Fix build --- Emby.Dlna/ContentDirectory/StubType.cs | 1 - Emby.Dlna/PlayTo/TransportState.cs | 1 - Jellyfin.Api/Controllers/ImageController.cs | 4 ++-- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/StubType.cs b/Emby.Dlna/ContentDirectory/StubType.cs index a5116055d1..187dc1d75a 100644 --- a/Emby.Dlna/ContentDirectory/StubType.cs +++ b/Emby.Dlna/ContentDirectory/StubType.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 - namespace Emby.Dlna.ContentDirectory { /// diff --git a/Emby.Dlna/PlayTo/TransportState.cs b/Emby.Dlna/PlayTo/TransportState.cs index 1ca71283a8..2058e9dc79 100644 --- a/Emby.Dlna/PlayTo/TransportState.cs +++ b/Emby.Dlna/PlayTo/TransportState.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 - namespace Emby.Dlna.PlayTo { public enum TransportState diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index dc36349704..a50d6e46bf 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -113,7 +113,7 @@ namespace Jellyfin.Api.Controllers await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); } - user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType))); + user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType ?? string.Empty))); await _providerManager .SaveImage(memoryStream, mimeType, user.ProfileImage.Path) @@ -160,7 +160,7 @@ namespace Jellyfin.Api.Controllers await _userManager.ClearProfileImageAsync(user).ConfigureAwait(false); } - user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType))); + user.ProfileImage = new Data.Entities.ImageInfo(Path.Combine(userDataPath, "profile" + MimeTypes.ToExtension(mimeType ?? string.Empty))); await _providerManager .SaveImage(memoryStream, mimeType, user.ProfileImage.Path) From 55dd0da5dae868a944e729e41973755eaff8d230 Mon Sep 17 00:00:00 2001 From: hoanghuy309 Date: Sat, 20 Feb 2021 17:17:58 +0000 Subject: [PATCH 1118/1930] Translated using Weblate (Vietnamese) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/vi/ --- Emby.Server.Implementations/Localization/Core/vi.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/vi.json b/Emby.Server.Implementations/Localization/Core/vi.json index 40368d464e..58652c4693 100644 --- a/Emby.Server.Implementations/Localization/Core/vi.json +++ b/Emby.Server.Implementations/Localization/Core/vi.json @@ -3,7 +3,7 @@ "Favorites": "Yêu Thích", "Folders": "Thư Mục", "Genres": "Thể Loại", - "HeaderAlbumArtists": "Bộ Sưu Tập Nghệ sĩ", + "HeaderAlbumArtists": "Tuyển Tập Nghệ sĩ", "HeaderContinueWatching": "Xem Tiếp", "HeaderLiveTV": "TV Trực Tiếp", "Movies": "Phim", @@ -13,7 +13,7 @@ "Songs": "Các Bài Hát", "Sync": "Đồng Bộ", "ValueSpecialEpisodeName": "Đặc Biệt - {0}", - "Albums": "Albums", + "Albums": "Tuyển Tập", "Artists": "Các Nghệ Sĩ", "TaskDownloadMissingSubtitlesDescription": "Tìm kiếm phụ đề bị thiếu trên Internet dựa trên cấu hình dữ liệu mô tả.", "TaskDownloadMissingSubtitles": "Tải Xuống Phụ Đề Bị Thiếu", From 401bafbfd0f8f363efdeceb98cc6fa170aaa6dae Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 20 Feb 2021 23:36:22 +0100 Subject: [PATCH 1119/1930] Address comments --- MediaBrowser.Model/Dlna/StreamInfo.cs | 26 ++------------------------ 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index f7010dcd0f..29da5d9e7f 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -116,34 +116,12 @@ namespace MediaBrowser.Model.Dlna /// /// Gets the audio stream that will be used. /// - public MediaStream TargetAudioStream - { - get - { - if (MediaSource != null) - { - return MediaSource.GetDefaultAudioStream(AudioStreamIndex); - } - - return null; - } - } + public MediaStream TargetAudioStream => MediaSource?.GetDefaultAudioStream(AudioStreamIndex); /// /// Gets the video stream that will be used. /// - public MediaStream TargetVideoStream - { - get - { - if (MediaSource != null) - { - return MediaSource.VideoStream; - } - - return null; - } - } + public MediaStream TargetVideoStream => MediaSource?.VideoStream; /// /// Gets the audio sample rate that will be in the output stream. From 605bd80251368a88f7ffc0d0442bd52a7575329a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 20 Feb 2021 22:46:16 +0000 Subject: [PATCH 1120/1930] Fix for ignoreVirtualInterfaces --- Jellyfin.Networking/Manager/NetworkManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 60b899519e..c08406003a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -916,7 +916,8 @@ namespace Jellyfin.Networking.Manager // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. if (config.IgnoreVirtualInterfaces) { - var virtualInterfaceNames = config.VirtualInterfaceNames.Split(','); + // each virtual interface name must be pre-pended with the exclusion symbol ! + var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => '!' + p).ToArray(); var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; Array.Copy(lanAddresses, newList, lanAddresses.Length); Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); From c50d0dbc7236df06b8d438d6c7c404e04c73b56b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 20 Feb 2021 23:06:48 +0000 Subject: [PATCH 1121/1930] Fixed startup racing issue --- Emby.Dlna/Main/DlnaEntryPoint.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 3f7b558f61..6205ba6cb6 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -228,7 +228,10 @@ namespace Emby.Dlna.Main { try { - ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer); + if (communicationsServer != null) + { + ((DeviceDiscovery)_deviceDiscovery).Start(communicationsServer); + } } catch (Exception ex) { From b03bd7a29935895c7d11507e59008df0eb5ba58c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 21 Feb 2021 00:41:14 +0000 Subject: [PATCH 1122/1930] Fix testing --- Jellyfin.Networking/Manager/NetworkManager.cs | 37 ++++++++++++------- .../NetworkTesting/NetworkParseTests.cs | 3 +- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index c08406003a..b60e4e23ba 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -691,11 +691,11 @@ namespace Jellyfin.Networking.Manager /// Checks the string to see if it matches any interface names. /// /// String to check. - /// Interface index number. + /// Interface index numbers that match. /// true if an interface name matches the token, False otherwise. - private bool IsInterface(string token, out int index) + private bool IsInterface(string token, out List? index) { - index = -1; + index = null; // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. @@ -712,13 +712,17 @@ namespace Jellyfin.Networking.Manager if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) { - index = interfcIndex; - return true; + if (index == null) + { + index = new List(); + } + + index.Add(interfcIndex); } } } - return false; + return index != null; } /// @@ -730,14 +734,14 @@ namespace Jellyfin.Networking.Manager { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. - if (IsInterface(token, out int index)) + if (IsInterface(token, out var index)) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); - // Replace interface tags with the interface IP's. + // Replace all the interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (Math.Abs(iface.Tag) == index + if (index!.Contains(Math.Abs(iface.Tag)) && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { @@ -918,10 +922,17 @@ namespace Jellyfin.Networking.Manager { // each virtual interface name must be pre-pended with the exclusion symbol ! var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => '!' + p).ToArray(); - var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; - Array.Copy(lanAddresses, newList, lanAddresses.Length); - Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); - lanAddresses = newList; + if (lanAddresses.Length > 0) + { + var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; + Array.Copy(lanAddresses, newList, lanAddresses.Length); + Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); + lanAddresses = newList; + } + else + { + lanAddresses = virtualInterfaceNames; + } } // Read and parse bind addresses and exclusions, removing ones that don't exist. diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index c350685af0..e41ea3cca2 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -60,7 +60,8 @@ namespace Jellyfin.Networking.Tests [Theory] [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] - [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212;200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] + [InlineData("192.168.1.200/24,-20,vEthernet1:192.168.1.208/24,-16,vEthernet212:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) { var conf = new NetworkConfiguration() From cb09096a59c0df9b02f4c057db93d8479678af8f Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 21 Feb 2021 00:42:06 +0000 Subject: [PATCH 1123/1930] optimized --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index b60e4e23ba..9b9897e76b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -921,7 +921,7 @@ namespace Jellyfin.Networking.Manager if (config.IgnoreVirtualInterfaces) { // each virtual interface name must be pre-pended with the exclusion symbol ! - var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => '!' + p).ToArray(); + var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray(); if (lanAddresses.Length > 0) { var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; From eba859e33e7bf611e5b4d63acd4df81038154be8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 21 Feb 2021 02:49:52 +0100 Subject: [PATCH 1124/1930] Minor improvements --- .../LiveTv/Listings/SchedulesDirect.cs | 1 - .../Session/WebSocketController.cs | 1 - Jellyfin.Api/Extensions/DtoExtensions.cs | 9 ---- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 11 +++-- Jellyfin.Api/Helpers/StreamingHelpers.cs | 2 +- .../Extensions/StringExtensions.cs | 37 ---------------- MediaBrowser.Common/Net/NetworkExtensions.cs | 5 --- tests/Jellyfin.Api.Tests/ParseNetworkTests.cs | 16 +++---- .../Extensions/StringExtensionsTests.cs | 43 ------------------- 9 files changed, 16 insertions(+), 109 deletions(-) delete mode 100644 MediaBrowser.Common/Extensions/StringExtensions.cs delete mode 100644 tests/Jellyfin.Common.Tests/Extensions/StringExtensionsTests.cs diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index c641b760b6..6d7c5ac6ee 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -10,7 +10,6 @@ using System.Net.Http; using System.Net.Mime; using System.Text; using System.Text.Json; -using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index f9c6a13c69..a653b58c2b 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -8,7 +8,6 @@ using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Net; diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index f2abd515d3..e0c744325f 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -113,14 +113,5 @@ namespace Jellyfin.Api.Extensions return dtoOptions; } - - /// - /// Check if DtoOptions contains field. - /// - /// DtoOptions object. - /// Field to check. - /// Field existence. - internal static bool ContainsField(this DtoOptions dtoOptions, ItemFields field) - => dtoOptions.Fields != null && dtoOptions.Fields.Contains(field); } } diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 8a47f7461d..16380f0bba 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; +using System.Net.Mime; using System.Security.Claims; using System.Text; using System.Threading; @@ -171,13 +172,15 @@ namespace Jellyfin.Api.Helpers var queryString = _httpContextAccessor.HttpContext.Request.QueryString.ToString(); // from universal audio service - if (queryString.IndexOf("SegmentContainer", StringComparison.OrdinalIgnoreCase) == -1 && !string.IsNullOrWhiteSpace(state.Request.SegmentContainer)) + if (!string.IsNullOrWhiteSpace(state.Request.SegmentContainer) + && !queryString.Contains("SegmentContainer", StringComparison.OrdinalIgnoreCase)) { queryString += "&SegmentContainer=" + state.Request.SegmentContainer; } // from universal audio service - if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons) && queryString.IndexOf("TranscodeReasons=", StringComparison.OrdinalIgnoreCase) == -1) + if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons) + && !queryString.Contains("TranscodeReasons=", StringComparison.OrdinalIgnoreCase)) { queryString += "&TranscodeReasons=" + state.Request.TranscodeReasons; } @@ -560,13 +563,13 @@ namespace Jellyfin.Api.Helpers profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty; if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { - profileString = profileString ?? "high"; + profileString ??= "high"; } if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase) || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)) { - profileString = profileString ?? "main"; + profileString ??= "main"; } } diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 4957ee8b8d..153ec31759 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -245,7 +245,7 @@ namespace Jellyfin.Api.Helpers var ext = string.IsNullOrWhiteSpace(state.OutputContainer) ? GetOutputFileExtension(state) - : ('.' + state.OutputContainer); + : ("." + state.OutputContainer); state.OutputFilePath = GetOutputFilePath(state, ext!, serverConfigurationManager, streamingRequest.DeviceId, streamingRequest.PlaySessionId); diff --git a/MediaBrowser.Common/Extensions/StringExtensions.cs b/MediaBrowser.Common/Extensions/StringExtensions.cs deleted file mode 100644 index 7643017412..0000000000 --- a/MediaBrowser.Common/Extensions/StringExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -#nullable enable - -using System; - -namespace MediaBrowser.Common.Extensions -{ - /// - /// Extensions methods to simplify string operations. - /// - public static class StringExtensions - { - /// - /// Returns the part on the left of the needle. - /// - /// The string to seek. - /// The needle to find. - /// The part left of the . - public static ReadOnlySpan LeftPart(this ReadOnlySpan haystack, char needle) - { - var pos = haystack.IndexOf(needle); - return pos == -1 ? haystack : haystack[..pos]; - } - - /// - /// Returns the part on the left of the needle. - /// - /// The string to seek. - /// The needle to find. - /// One of the enumeration values that specifies the rules for the search. - /// The part left of the needle. - public static ReadOnlySpan LeftPart(this ReadOnlySpan haystack, ReadOnlySpan needle, StringComparison stringComparison = default) - { - var pos = haystack.IndexOf(needle, stringComparison); - return pos == -1 ? haystack : haystack[..pos]; - } - } -} diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index d07bba249b..9c1a0cf495 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,11 +1,6 @@ -#pragma warning disable CA1062 // Validate arguments of public methods using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net; -using System.Runtime.CompilerServices; -using System.Text; namespace MediaBrowser.Common.Net { diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs index 6c3fd0ee10..3984407ee9 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs @@ -37,28 +37,28 @@ namespace Jellyfin.Api.Tests EnableIPV6 = ip6 }; - var result = match + ','; + var result = match + ","; ForwardedHeadersOptions options = new ForwardedHeadersOptions(); // Need this here as ::1 and 127.0.0.1 are in them by default. options.KnownProxies.Clear(); options.KnownNetworks.Clear(); - ApiServiceCollectionExtensions.AddProxyAddresses(settings, hostList.Split(","), options); + ApiServiceCollectionExtensions.AddProxyAddresses(settings, hostList.Split(','), options); var sb = new StringBuilder(); foreach (var item in options.KnownProxies) { - sb.Append(item); - sb.Append(','); + sb.Append(item) + .Append(','); } foreach (var item in options.KnownNetworks) { - sb.Append(item.Prefix); - sb.Append('/'); - sb.Append(item.PrefixLength.ToString(CultureInfo.InvariantCulture)); - sb.Append(','); + sb.Append(item.Prefix) + .Append('/') + .Append(item.PrefixLength.ToString(CultureInfo.InvariantCulture)) + .Append(','); } Assert.Equal(sb.ToString(), result); diff --git a/tests/Jellyfin.Common.Tests/Extensions/StringExtensionsTests.cs b/tests/Jellyfin.Common.Tests/Extensions/StringExtensionsTests.cs deleted file mode 100644 index 8bf613f05f..0000000000 --- a/tests/Jellyfin.Common.Tests/Extensions/StringExtensionsTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using MediaBrowser.Common.Extensions; -using Xunit; - -namespace Jellyfin.Common.Tests.Extensions -{ - public class StringExtensionsTests - { - [Theory] - [InlineData("", 'q', "")] - [InlineData("Banana split", ' ', "Banana")] - [InlineData("Banana split", 'q', "Banana split")] - public void LeftPart_ValidArgsCharNeedle_Correct(string str, char needle, string expectedResult) - { - var result = str.AsSpan().LeftPart(needle).ToString(); - Assert.Equal(expectedResult, result); - } - - [Theory] - [InlineData("", "", "")] - [InlineData("", "q", "")] - [InlineData("Banana split", "", "")] - [InlineData("Banana split", " ", "Banana")] - [InlineData("Banana split test", " split", "Banana")] - public void LeftPart_ValidArgsWithoutStringComparison_Correct(string str, string needle, string expectedResult) - { - var result = str.AsSpan().LeftPart(needle).ToString(); - Assert.Equal(expectedResult, result); - } - - [Theory] - [InlineData("", "", StringComparison.Ordinal, "")] - [InlineData("Banana split", " ", StringComparison.Ordinal, "Banana")] - [InlineData("Banana split test", " split", StringComparison.Ordinal, "Banana")] - [InlineData("Banana split test", " Split", StringComparison.Ordinal, "Banana split test")] - [InlineData("Banana split test", " Splït", StringComparison.InvariantCultureIgnoreCase, "Banana split test")] - public void LeftPart_ValidArgs_Correct(string str, string needle, StringComparison stringComparison, string expectedResult) - { - var result = str.AsSpan().LeftPart(needle, stringComparison).ToString(); - Assert.Equal(expectedResult, result); - } - } -} From b1fe28d0a6c1bbc67543fc1b5877a69f7958f8c5 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 21 Feb 2021 02:58:30 +0100 Subject: [PATCH 1125/1930] Use GetEncodingOptions where possible --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 5 ----- Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs | 2 +- .../Migrations/Routines/DisableTranscodingThrottling.cs | 2 +- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 6 +++--- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 5ef83f2746..0760e81274 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -335,11 +335,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return new Uri(url).AbsoluteUri.TrimEnd('/'); } - protected EncodingOptions GetEncodingOptions() - { - return Config.GetConfiguration("encoding"); - } - private static string GetHdHrIdFromChannelId(string channelId) { return channelId.Split('_')[1]; diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs index 872a468245..e33e552edb 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs @@ -98,7 +98,7 @@ namespace Jellyfin.Api.Models.PlaybackDtos private EncodingOptions GetOptions() { - return _config.GetConfiguration("encoding"); + return _config.GetEncodingOptions(); } private async void TimerCallback(object? state) diff --git a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs index 0925a87b55..bf0225e988 100644 --- a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs +++ b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs @@ -32,7 +32,7 @@ namespace Jellyfin.Server.Migrations.Routines public void Perform() { // Set EnableThrottling to false since it wasn't used before and may introduce issues - var encoding = _configManager.GetConfiguration("encoding"); + var encoding = _configManager.GetEncodingOptions(); if (encoding.EnableThrottling) { _logger.LogInformation("Disabling transcoding throttling during migration"); diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index c0b6cf28bb..45872b5c08 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -103,7 +103,7 @@ namespace MediaBrowser.MediaEncoding.Encoder public void SetFFmpegPath() { // 1) Custom path stored in config/encoding xml file under tag takes precedence - if (!ValidatePath(_configurationManager.GetConfiguration("encoding").EncoderAppPath, FFmpegLocation.Custom)) + if (!ValidatePath(_configurationManager.GetEncodingOptions().EncoderAppPath, FFmpegLocation.Custom)) { // 2) Check if the --ffmpeg CLI switch has been given if (!ValidatePath(_startupOptionFFmpegPath, FFmpegLocation.SetByArgument)) @@ -118,7 +118,7 @@ namespace MediaBrowser.MediaEncoding.Encoder } // Write the FFmpeg path to the config/encoding.xml file as so it appears in UI - var config = _configurationManager.GetConfiguration("encoding"); + var config = _configurationManager.GetEncodingOptions(); config.EncoderAppPathDisplay = _ffmpegPath ?? string.Empty; _configurationManager.SaveConfiguration("encoding", config); @@ -177,7 +177,7 @@ namespace MediaBrowser.MediaEncoding.Encoder // Write the new ffmpeg path to the xml as // This ensures its not lost on next startup - var config = _configurationManager.GetConfiguration("encoding"); + var config = _configurationManager.GetEncodingOptions(); config.EncoderAppPath = newPath; _configurationManager.SaveConfiguration("encoding", config); From b4897616585d4a7a2ab23335fba66ffba941b144 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 21 Feb 2021 03:06:59 +0100 Subject: [PATCH 1126/1930] Add Jellyfin.Model.Tests project to the solution --- Jellyfin.sln | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Jellyfin.sln b/Jellyfin.sln index 4e6687cceb..d83013dab0 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -74,6 +74,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "test EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -200,6 +202,10 @@ Global {30922383-D513-4F4D-B890-A940B57FA353}.Debug|Any CPU.Build.0 = Debug|Any CPU {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.ActiveCfg = Release|Any CPU {30922383-D513-4F4D-B890-A940B57FA353}.Release|Any CPU.Build.0 = Release|Any CPU + {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -214,6 +220,7 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {30922383-D513-4F4D-B890-A940B57FA353} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} From 7bfc59b562b2a266e184d76c92a2af56377dfb5c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 21 Feb 2021 13:31:59 +0000 Subject: [PATCH 1127/1930] Fixed test data. --- .../NetworkTesting/NetworkParseTests.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 6bff52e73b..8d5d4884a6 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -52,16 +52,20 @@ namespace Jellyfin.Networking.Tests } /// - /// Checks the ability to ignore interfaces + /// Checks the ability to ignore virtual interfaces. /// /// Mock network setup, in the format (IP address, interface index, interface name) | .... /// LAN addresses. /// Bind addresses that are excluded. [Theory] - [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] - [InlineData("192.168.1.208/24,-16,eth16:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] - [InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212:200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] - [InlineData("192.168.1.200/24,-20,vEthernet1:192.168.1.208/24,-16,vEthernet212:200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] + // All valid + [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] + // eth16 only + [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + // All interfaces excluded. + [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] + // vEthernet1 and vEthernet212 should be excluded. + [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) { var conf = new NetworkConfiguration() From 0d3606a7466d55d217e1dffc0539cfa1c189eb7d Mon Sep 17 00:00:00 2001 From: denikrejn1000 Date: Sun, 21 Feb 2021 11:43:44 +0000 Subject: [PATCH 1128/1930] Translated using Weblate (Serbian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sr/ --- .../Localization/Core/sr.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/sr.json b/Emby.Server.Implementations/Localization/Core/sr.json index d785bcb907..15fb34186b 100644 --- a/Emby.Server.Implementations/Localization/Core/sr.json +++ b/Emby.Server.Implementations/Localization/Core/sr.json @@ -4,11 +4,11 @@ "VersionNumber": "Верзија {0}", "ValueSpecialEpisodeName": "Специјал - {0}", "ValueHasBeenAddedToLibrary": "{0} је додато у вашу медијску библиотеку", - "UserStoppedPlayingItemWithValues": "{0} заврши пуштање {1} на {2}", + "UserStoppedPlayingItemWithValues": "{0} завршио пуштање {1} на {2}", "UserStartedPlayingItemWithValues": "{0} пушта {1} на {2}", "UserPasswordChangedWithName": "Лозинка је промењена за корисника {0}", "UserOnlineFromDevice": "{0} је на вези од {1}", - "UserOfflineFromDevice": "{0} се одвезао са {1}", + "UserOfflineFromDevice": "{0} је прекинуо/а везу са {1}", "UserLockedOutWithName": "Корисник {0} је закључан", "UserDownloadingItemWithValues": "{0} преузима {1}", "UserDeletedWithName": "Корисник {0} је обрисан", @@ -41,7 +41,7 @@ "NotificationOptionPluginError": "Грешка прикључка", "NotificationOptionNewLibraryContent": "Додат нови садржај", "NotificationOptionInstallationFailed": "Неуспела инсталација", - "NotificationOptionCameraImageUploaded": "Слика са камере послата", + "NotificationOptionCameraImageUploaded": "Слика са камере отпремљена", "NotificationOptionAudioPlaybackStopped": "Заустављено пуштање звука", "NotificationOptionAudioPlayback": "Покренуто пуштање звука", "NotificationOptionApplicationUpdateInstalled": "Ажурирање инсталирано", @@ -86,7 +86,7 @@ "Channels": "Канали", "CameraImageUploadedFrom": "Нова фотографија је учитана са {0}", "Books": "Књиге", - "AuthenticationSucceededWithUserName": "{0} успешно проверено", + "AuthenticationSucceededWithUserName": "{0} Успешна аутентикација", "Artists": "Извођачи", "Application": "Апликација", "AppDeviceValues": "Апликација: {0}, Уређај: {1}", @@ -100,7 +100,7 @@ "TaskUpdatePluginsDescription": "Преузима и инсталира исправке за додатке који су конфигурисани за аутоматско ажурирање.", "TaskUpdatePlugins": "Ажурирајте додатке", "TaskRefreshPeopleDescription": "Ажурира метаподатке за глумце и редитеље у вашој медијској библиотеци.", - "TaskRefreshPeople": "Освежите људе", + "TaskRefreshPeople": "Освежите кориснике", "TaskCleanLogsDescription": "Брише логове старије од {0} дана.", "TaskCleanLogs": "Очистите директоријум логова", "TaskRefreshLibraryDescription": "Скенира вашу медијску библиотеку за нове датотеке и освежава метаподатке.", @@ -116,6 +116,6 @@ "TaskCleanActivityLogDescription": "Брише историју активности старију од конфигурисаног броја година.", "TaskCleanActivityLog": "Очисти историју активности", "Undefined": "Недефинисано", - "Forced": "Форсирано", + "Forced": "Принудно", "Default": "Подразумевано" } From 473a9956503d2b8b361c3b4ebe65a22303b31172 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 21 Feb 2021 15:53:20 +0000 Subject: [PATCH 1129/1930] Update SubtitleEncoder.cs --- .../Subtitles/SubtitleEncoder.cs | 47 ++++++++----------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index b92c4ee067..c4c0e2a907 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -168,33 +168,25 @@ namespace MediaBrowser.MediaEncoding.Subtitles MediaStream subtitleStream, CancellationToken cancellationToken) { - var inputFile = mediaSource.Path; + var fileInfo = await GetReadableFile(mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); - var protocol = mediaSource.Protocol; - if (subtitleStream.IsExternal) - { - protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path); - } - - var fileInfo = await GetReadableFile(mediaSource.Path, inputFile, mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false); - - var stream = await GetSubtitleStream(fileInfo.Path, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false); + var stream = await GetSubtitleStream(fileInfo, cancellationToken).ConfigureAwait(false); return (stream, fileInfo.Format); } - private async Task GetSubtitleStream(string path, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken) + private async Task GetSubtitleStream(SubtitleInfo fileInfo, CancellationToken cancellationToken) { - if (requiresCharset) + if (fileInfo.IsExternal) { - using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false)) + using (var stream = await GetStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false)) { var result = CharsetDetector.DetectFromStream(stream).Detected; stream.Position = 0; if (result != null) { - _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, path); + _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, fileInfo.Path); using var reader = new StreamReader(stream, result.Encoding); var text = await reader.ReadToEndAsync().ConfigureAwait(false); @@ -204,12 +196,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - return File.OpenRead(path); + return File.OpenRead(fileInfo.Path); } private async Task GetReadableFile( - string mediaPath, - string inputFile, MediaSourceInfo mediaSource, MediaStream subtitleStream, CancellationToken cancellationToken) @@ -241,9 +231,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles } // Extract - var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, "." + outputFormat); + var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFormat); - await ExtractTextSubtitle(inputFile, mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken) + await ExtractTextSubtitle(mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken) .ConfigureAwait(false); return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false); @@ -255,13 +245,18 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (GetReader(currentFormat, false) == null) { // Convert - var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, ".srt"); + var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt"); await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false); return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true); } + if (subtitleStream.IsExternal) + { + return new SubtitleInfo(subtitleStream.Path, _mediaSourceManager.GetPathProtocol(subtitleStream.Path), currentFormat, true); + } + return new SubtitleInfo(subtitleStream.Path, mediaSource.Protocol, currentFormat, true); } @@ -504,7 +499,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// /// Extracts the text subtitle. /// - /// The input file. /// The mediaSource. /// Index of the subtitle stream. /// The output codec. @@ -513,7 +507,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles /// Task. /// Must use inputPath list overload. private async Task ExtractTextSubtitle( - string inputFile, MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputCodec, @@ -529,7 +522,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!File.Exists(outputPath)) { await ExtractTextSubtitleInternal( - _mediaEncoder.GetInputArgument(inputFile, mediaSource), + _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource), subtitleStreamIndex, outputCodec, outputPath, @@ -695,15 +688,15 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - private string GetSubtitleCachePath(string mediaPath, MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension) + private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension) { if (mediaSource.Protocol == MediaProtocol.File) { var ticksParam = string.Empty; - var date = _fileSystem.GetLastWriteTimeUtc(mediaPath); + var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path); - ReadOnlySpan filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension; + ReadOnlySpan filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension; var prefix = filename.Slice(0, 1); @@ -711,7 +704,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles } else { - ReadOnlySpan filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension; + ReadOnlySpan filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension; var prefix = filename.Slice(0, 1); From ff10dd9e127068fc058e17b21628d2679013ac8a Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Feb 2021 09:58:23 +0100 Subject: [PATCH 1130/1930] Update deps Jellyfin.Model.Tests --- tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index 64d51e0638..dc137d0777 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -8,10 +8,10 @@ - + - + From d033c30cd7673cc5c011c5002b74c45b826f848b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Feb 2021 12:00:42 +0000 Subject: [PATCH 1131/1930] Bump coverlet.collector from 3.0.2 to 3.0.3 Bumps [coverlet.collector](https://github.com/coverlet-coverage/coverlet) from 3.0.2 to 3.0.3. - [Release notes](https://github.com/coverlet-coverage/coverlet/releases) - [Commits](https://github.com/coverlet-coverage/coverlet/commits) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index eca3df79b3..944cb1ff0b 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 57edbf902c..47e2354415 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index c766c54458..fb18a8a8db 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 52a9e11932..7e4a2efad3 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 24f6fb3561..ec9cc656a2 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index 64d51e0638..ebdad7c72f 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index a4d5c0d6fd..247e6aa7ab 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index d77645cd9e..36ff93a452 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index c3b3155fe9..14b8cbd54c 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -26,7 +26,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index aed3e8ac5d..bc076caed6 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -18,7 +18,7 @@ - + From 35f460998bf60c174e0c1c9b52bc5c408b9f4060 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Feb 2021 12:00:47 +0000 Subject: [PATCH 1132/1930] Bump sharpcompress from 0.28.0 to 0.28.1 Bumps [sharpcompress](https://github.com/adamhathcock/sharpcompress) from 0.28.0 to 0.28.1. - [Release notes](https://github.com/adamhathcock/sharpcompress/releases) - [Commits](https://github.com/adamhathcock/sharpcompress/compare/0.28...0.28.1) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 522667153b..f03f04e021 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -29,7 +29,7 @@ - + From 29fb2c57c849fc0b6fcc0313eb46655f66b20e61 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Feb 2021 12:00:48 +0000 Subject: [PATCH 1133/1930] Bump Swashbuckle.AspNetCore.ReDoc from 6.0.5 to 6.0.7 Bumps [Swashbuckle.AspNetCore.ReDoc](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.0.5 to 6.0.7. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.0.5...v6.0.7) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 5f7c64a7ef..2fb8b1c7dd 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -18,7 +18,7 @@ - + From 93a1f434a31072416736d2003e62d2162fc157d2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Feb 2021 13:13:31 +0100 Subject: [PATCH 1134/1930] Fix possible null ref exception --- .../EntryPoints/UdpServerEntryPoint.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 9486874d58..a12a6b26c5 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -29,7 +31,7 @@ namespace Emby.Server.Implementations.EntryPoints /// /// The UDP server. /// - private UdpServer _udpServer; + private UdpServer? _udpServer; private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private bool _disposed = false; @@ -71,9 +73,8 @@ namespace Emby.Server.Implementations.EntryPoints } _cancellationTokenSource.Cancel(); - _udpServer.Dispose(); _cancellationTokenSource.Dispose(); - _cancellationTokenSource = null; + _udpServer?.Dispose(); _udpServer = null; _disposed = true; From 57102090d307a62b3759177df3ba545cfad6c327 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Feb 2021 13:15:29 +0100 Subject: [PATCH 1135/1930] Add tests for DashboardController --- .../Controllers/DashboardController.cs | 42 +++------- Jellyfin.Api/Models/ConfigurationPageInfo.cs | 1 - Jellyfin.Server/CoreAppHost.cs | 1 - MediaBrowser.Common/Plugins/BasePlugin.cs | 3 - .../BrandingControllerTests.cs} | 11 +-- .../Controllers/DashboardControllerTests.cs | 76 +++++++++++++++++++ .../Jellyfin.Api.Tests.csproj | 4 + .../JellyfinApplicationFactory.cs | 4 +- tests/Jellyfin.Api.Tests/TestAppHost.cs | 51 +++++++++++++ tests/Jellyfin.Api.Tests/TestPage.html | 9 +++ tests/Jellyfin.Api.Tests/TestPlugin.cs | 43 +++++++++++ 11 files changed, 202 insertions(+), 43 deletions(-) rename tests/Jellyfin.Api.Tests/{BrandingServiceTests.cs => Controllers/BrandingControllerTests.cs} (72%) create mode 100644 tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs create mode 100644 tests/Jellyfin.Api.Tests/TestAppHost.cs create mode 100644 tests/Jellyfin.Api.Tests/TestPage.html create mode 100644 tests/Jellyfin.Api.Tests/TestPlugin.cs diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index b2baa9cea0..0c19f28183 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -22,22 +22,18 @@ namespace Jellyfin.Api.Controllers public class DashboardController : BaseJellyfinApiController { private readonly ILogger _logger; - private readonly IServerApplicationHost _appHost; private readonly IPluginManager _pluginManager; /// /// Initializes a new instance of the class. /// /// Instance of interface. - /// Instance of interface. /// Instance of interface. public DashboardController( ILogger logger, - IServerApplicationHost appHost, IPluginManager pluginManager) { _logger = logger; - _appHost = appHost; _pluginManager = pluginManager; } @@ -51,7 +47,7 @@ namespace Jellyfin.Api.Controllers [HttpGet("web/ConfigurationPages")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult> GetConfigurationPages( + public ActionResult> GetConfigurationPages( [FromQuery] bool? enableInMainMenu) { var configPages = _pluginManager.Plugins.SelectMany(GetConfigPages).ToList(); @@ -77,38 +73,22 @@ namespace Jellyfin.Api.Controllers [ProducesFile(MediaTypeNames.Text.Html, "application/x-javascript")] public ActionResult GetDashboardConfigurationPage([FromQuery] string? name) { - IPlugin? plugin = null; - Stream? stream = null; - - var isJs = false; - var isTemplate = false; - var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, name, StringComparison.OrdinalIgnoreCase)); - if (altPage != null) + if (altPage == null) { - plugin = altPage.Item2; - stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath); - - isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase); - isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html", StringComparison.Ordinal); + return NotFound(); } - if (plugin != null && stream != null) + IPlugin plugin = altPage.Item2; + string resourcePath = altPage.Item1.EmbeddedResourcePath; + Stream? stream = plugin.GetType().Assembly.GetManifestResourceStream(resourcePath); + if (stream == null) { - if (isJs) - { - return File(stream, MimeTypes.GetMimeType("page.js")); - } - - if (isTemplate) - { - return File(stream, MimeTypes.GetMimeType("page.html")); - } - - return File(stream, MimeTypes.GetMimeType("page.html")); + _logger.LogError("Failed to get resource {Resource} from plugin {Plugin}", resourcePath, plugin.Name); + return NotFound(); } - return NotFound(); + return File(stream, MimeTypes.GetMimeType(resourcePath)); } private IEnumerable GetConfigPages(LocalPlugin plugin) @@ -120,7 +100,7 @@ namespace Jellyfin.Api.Controllers { if (plugin?.Instance is not IHasWebPages hasWebPages) { - return new List>(); + return Enumerable.Empty>(); } return hasWebPages.GetPages().Select(i => new Tuple(i, plugin.Instance)); diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index a7bbe42fe5..d214280292 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -1,6 +1,5 @@ using System; using MediaBrowser.Common.Plugins; -using MediaBrowser.Controller.Plugins; using MediaBrowser.Model.Plugins; namespace Jellyfin.Api.Models diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index b76aa5e141..ae2fb39999 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -11,7 +11,6 @@ using Jellyfin.Server.Implementations; using Jellyfin.Server.Implementations.Activity; using Jellyfin.Server.Implementations.Events; using Jellyfin.Server.Implementations.Users; -using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Drawing; diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index e228ae7ec5..7b162c0e1c 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -1,10 +1,7 @@ using System; using System.IO; using System.Reflection; -using System.Runtime.InteropServices; -using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Plugins; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Common.Plugins { diff --git a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs b/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs similarity index 72% rename from tests/Jellyfin.Api.Tests/BrandingServiceTests.cs rename to tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs index 1cbe94c5b9..3207a0f257 100644 --- a/tests/Jellyfin.Api.Tests/BrandingServiceTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs @@ -5,11 +5,11 @@ using Xunit; namespace Jellyfin.Api.Tests { - public sealed class BrandingServiceTests : IClassFixture + public sealed class BrandingControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; - public BrandingServiceTests(JellyfinApplicationFactory factory) + public BrandingControllerTests(JellyfinApplicationFactory factory) { _factory = factory; } @@ -24,8 +24,9 @@ namespace Jellyfin.Api.Tests var response = await client.GetAsync("/Branding/Configuration"); // Assert - response.EnsureSuccessStatusCode(); - Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.True(response.IsSuccessStatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + Assert.Equal("utf-8", response.Content.Headers.ContentType?.CharSet); var responseBody = await response.Content.ReadAsStreamAsync(); _ = await JsonSerializer.DeserializeAsync(responseBody); } @@ -42,7 +43,7 @@ namespace Jellyfin.Api.Tests var response = await client.GetAsync(url); // Assert - response.EnsureSuccessStatusCode(); + Assert.True(response.IsSuccessStatusCode); Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType?.ToString()); } } diff --git a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs new file mode 100644 index 0000000000..fadeddba55 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs @@ -0,0 +1,76 @@ +using System.IO; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; +using Jellyfin.Api.Models; +using Xunit; + +namespace Jellyfin.Api.Tests.Controllers +{ + public sealed class DashboardControllerTests : IClassFixture + { + private readonly JellyfinApplicationFactory _factory; + + public DashboardControllerTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task GetDashboardConfigurationPage_NonExistingPage_NotFound() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("web/ConfigurationPage/ThisPageTotally/Doesnt/Exists.html").ConfigureAwait(false); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetDashboardConfigurationPage_ExistingPage_CorrectPage() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("/web/ConfigurationPage?name=TestPlugin").ConfigureAwait(false); + + Assert.True(response.IsSuccessStatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType?.MediaType); + StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Api.Tests.TestPage.html")!); + Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd()); + } + + [Fact] + public async Task GetDashboardConfigurationPage_BrokenPage_NotFound() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("/web/ConfigurationPage?name=BrokenPage").ConfigureAwait(false); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } + + [Fact] + public async Task GetConfigurationPages_NoParams_AllConfigurationPages() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("/web/ConfigurationPages").ConfigureAwait(false); + + Assert.True(response.IsSuccessStatusCode); + var res = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync()); + // TODO: check content + } + + [Fact] + public async Task GetConfigurationPages_True_MainMenuConfigurationPages() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("/web/ConfigurationPages?enableInMainMenu=true").ConfigureAwait(false); + + Assert.True(response.IsSuccessStatusCode); + var res = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync()); + Assert.Empty(res); + } + } +} diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index eca3df79b3..52dd8ae9c1 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -41,4 +41,8 @@ ../jellyfin-tests.ruleset + + + + diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs index 54f8eb225f..dbbd5ac28c 100644 --- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs @@ -73,7 +73,7 @@ namespace Jellyfin.Api.Tests _disposableComponents.Add(loggerFactory); // Create the app host and initialize it - var appHost = new CoreAppHost( + var appHost = new TestAppHost( appPaths, loggerFactory, commandLineOpts, @@ -93,7 +93,7 @@ namespace Jellyfin.Api.Tests var testServer = base.CreateServer(builder); // Finish initializing the app host - var appHost = (CoreAppHost)testServer.Services.GetRequiredService(); + var appHost = (TestAppHost)testServer.Services.GetRequiredService(); appHost.ServiceProvider = testServer.Services; appHost.InitializeServices().GetAwaiter().GetResult(); appHost.RunStartupTasksAsync().GetAwaiter().GetResult(); diff --git a/tests/Jellyfin.Api.Tests/TestAppHost.cs b/tests/Jellyfin.Api.Tests/TestAppHost.cs new file mode 100644 index 0000000000..772e98d049 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/TestAppHost.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using System.Reflection; +using Emby.Server.Implementations; +using Jellyfin.Server; +using MediaBrowser.Controller; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.Tests +{ + /// + /// Implementation of the abstract class. + /// + public class TestAppHost : CoreAppHost + { + /// + /// Initializes a new instance of the class. + /// + /// The to be used by the . + /// The to be used by the . + /// The to be used by the . + /// The to be used by the . + /// The to be used by the . + public TestAppHost( + IServerApplicationPaths applicationPaths, + ILoggerFactory loggerFactory, + IStartupOptions options, + IFileSystem fileSystem, + IServiceCollection collection) + : base( + applicationPaths, + loggerFactory, + options, + fileSystem, + collection) + { + } + + /// + protected override IEnumerable GetAssembliesWithPartsInternal() + { + foreach (var a in base.GetAssembliesWithPartsInternal()) + { + yield return a; + } + + yield return typeof(TestPlugin).Assembly; + } + } +} diff --git a/tests/Jellyfin.Api.Tests/TestPage.html b/tests/Jellyfin.Api.Tests/TestPage.html new file mode 100644 index 0000000000..8037af8a60 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/TestPage.html @@ -0,0 +1,9 @@ + + + + TestPlugin + + +

This is a Test Page.

+ + diff --git a/tests/Jellyfin.Api.Tests/TestPlugin.cs b/tests/Jellyfin.Api.Tests/TestPlugin.cs new file mode 100644 index 0000000000..a3b4b6994f --- /dev/null +++ b/tests/Jellyfin.Api.Tests/TestPlugin.cs @@ -0,0 +1,43 @@ +#pragma warning disable CS1591 + +using System; +using System.Collections.Generic; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Api.Tests +{ + public class TestPlugin : BasePlugin, IHasWebPages + { + public TestPlugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + public static TestPlugin? Instance { get; private set; } + + public override Guid Id => new Guid("2d350a13-0bf7-4b61-859c-d5e601b5facf"); + + public override string Name => nameof(TestPlugin); + + public override string Description => "Server test Plugin."; + + public IEnumerable GetPages() + { + yield return new PluginPageInfo + { + Name = Name, + EmbeddedResourcePath = GetType().Namespace + ".TestPage.html" + }; + + yield return new PluginPageInfo + { + Name = "BrokenPage", + EmbeddedResourcePath = GetType().Namespace + ".foobar" + }; + } + } +} From ec3237ba55a6c0c6e7a31e2aaa5fbf77c9978ac7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Feb 2021 13:46:40 +0100 Subject: [PATCH 1136/1930] Fix tests --- Jellyfin.Api/Controllers/DashboardController.cs | 1 - Jellyfin.Api/Models/ConfigurationPageInfo.cs | 8 ++++++++ .../Controllers/DashboardControllerTests.cs | 9 ++++++--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index 0c19f28183..a2c2ecd666 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -6,7 +6,6 @@ using System.Net.Mime; using Jellyfin.Api.Attributes; using Jellyfin.Api.Models; using MediaBrowser.Common.Plugins; -using MediaBrowser.Controller; using MediaBrowser.Model.Net; using MediaBrowser.Model.Plugins; using Microsoft.AspNetCore.Http; diff --git a/Jellyfin.Api/Models/ConfigurationPageInfo.cs b/Jellyfin.Api/Models/ConfigurationPageInfo.cs index d214280292..ec4a0d1a1c 100644 --- a/Jellyfin.Api/Models/ConfigurationPageInfo.cs +++ b/Jellyfin.Api/Models/ConfigurationPageInfo.cs @@ -24,6 +24,14 @@ namespace Jellyfin.Api.Models PluginId = plugin?.Id; } + /// + /// Initializes a new instance of the class. + /// + public ConfigurationPageInfo() + { + Name = string.Empty; + } + /// /// Gets or sets the name. /// diff --git a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs index fadeddba55..84d362a397 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs @@ -3,6 +3,7 @@ using System.Net; using System.Text.Json; using System.Threading.Tasks; using Jellyfin.Api.Models; +using MediaBrowser.Common.Json; using Xunit; namespace Jellyfin.Api.Tests.Controllers @@ -10,6 +11,7 @@ namespace Jellyfin.Api.Tests.Controllers public sealed class DashboardControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; + private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.GetOptions(); public DashboardControllerTests(JellyfinApplicationFactory factory) { @@ -57,7 +59,6 @@ namespace Jellyfin.Api.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages").ConfigureAwait(false); Assert.True(response.IsSuccessStatusCode); - var res = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync()); // TODO: check content } @@ -69,8 +70,10 @@ namespace Jellyfin.Api.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages?enableInMainMenu=true").ConfigureAwait(false); Assert.True(response.IsSuccessStatusCode); - var res = await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync()); - Assert.Empty(res); + var res = await response.Content.ReadAsStreamAsync(); + System.Console.WriteLine(res); + var data = await JsonSerializer.DeserializeAsync(res, _jsonOpions); + Assert.Empty(data); } } } From baadc48f43ec425659d0d7210f1a97416d7d34c5 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Feb 2021 16:27:02 +0100 Subject: [PATCH 1137/1930] Address comments --- .../Controllers/BrandingControllerTests.cs | 9 ++++++--- .../Controllers/DashboardControllerTests.cs | 13 ++++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs index 3207a0f257..40933562db 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs @@ -1,3 +1,5 @@ +using System.Net.Mime; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using MediaBrowser.Model.Branding; @@ -25,8 +27,8 @@ namespace Jellyfin.Api.Tests // Assert Assert.True(response.IsSuccessStatusCode); - Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); - Assert.Equal("utf-8", response.Content.Headers.ContentType?.CharSet); + Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); + Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet); var responseBody = await response.Content.ReadAsStreamAsync(); _ = await JsonSerializer.DeserializeAsync(responseBody); } @@ -44,7 +46,8 @@ namespace Jellyfin.Api.Tests // Assert Assert.True(response.IsSuccessStatusCode); - Assert.Equal("text/css; charset=utf-8", response.Content.Headers.ContentType?.ToString()); + Assert.Equal("text/css", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet); } } } diff --git a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs index 84d362a397..300b2697f2 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs @@ -1,5 +1,7 @@ using System.IO; using System.Net; +using System.Net.Mime; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using Jellyfin.Api.Models; @@ -23,7 +25,7 @@ namespace Jellyfin.Api.Tests.Controllers { var client = _factory.CreateClient(); - var response = await client.GetAsync("web/ConfigurationPage/ThisPageTotally/Doesnt/Exists.html").ConfigureAwait(false); + var response = await client.GetAsync("web/ConfigurationPage?name=ThisPageDoesntExists").ConfigureAwait(false); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -36,7 +38,7 @@ namespace Jellyfin.Api.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPage?name=TestPlugin").ConfigureAwait(false); Assert.True(response.IsSuccessStatusCode); - Assert.Equal("text/html", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(MediaTypeNames.Text.Html, response.Content.Headers.ContentType?.MediaType); StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Api.Tests.TestPage.html")!); Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd()); } @@ -59,6 +61,9 @@ namespace Jellyfin.Api.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages").ConfigureAwait(false); Assert.True(response.IsSuccessStatusCode); + + var res = await response.Content.ReadAsStreamAsync(); + _ = await JsonSerializer.DeserializeAsync(res, _jsonOpions); // TODO: check content } @@ -70,8 +75,10 @@ namespace Jellyfin.Api.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages?enableInMainMenu=true").ConfigureAwait(false); Assert.True(response.IsSuccessStatusCode); + Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); + Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet); + var res = await response.Content.ReadAsStreamAsync(); - System.Console.WriteLine(res); var data = await JsonSerializer.DeserializeAsync(res, _jsonOpions); Assert.Empty(data); } From 003945f25b8d19de4638789bf0cdf580c546c9dd Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Mon, 22 Feb 2021 17:10:42 +0100 Subject: [PATCH 1138/1930] Update MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs Co-authored-by: Cody Robibero --- MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs index ca8defd8ba..673d97a9ed 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvChannelQuery.cs @@ -54,7 +54,7 @@ namespace MediaBrowser.Model.LiveTv public Guid UserId { get; set; } /// - /// gets or sets the start index. Used for paging. + /// Gets or sets the start index. Used for paging. /// /// The start index. public int? StartIndex { get; set; } From 875e02318c6164c7aaf8091b10e51cf64e16448c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Feb 2021 16:11:56 +0000 Subject: [PATCH 1139/1930] Bump Swashbuckle.AspNetCore from 6.0.5 to 6.0.7 Bumps [Swashbuckle.AspNetCore](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.0.5 to 6.0.7. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.0.5...v6.0.7) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 2fb8b1c7dd..67d0a3b5ab 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -17,7 +17,7 @@ - + From a015caba3f7089c17b4c675a124c2a46c493b4ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20V=C3=A1radi?= Date: Tue, 23 Feb 2021 06:34:46 +0100 Subject: [PATCH 1140/1930] Remove unnecessary sanity check --- .../Parsers/EpisodeNfoParser.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index aa3be587b4..1e14ba5264 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -86,17 +86,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers { reader.MoveToContent(); - if (reader.ReadToDescendant("episode")) + if (reader.ReadToDescendant("episode") && int.TryParse(reader.ReadElementContentAsString(), out var num)) { - var number = reader.ReadElementContentAsString(); - - if (!string.IsNullOrWhiteSpace(number)) - { - if (int.TryParse(number, out var num)) - { - item.Item.IndexNumberEnd = Math.Max(num, item.Item.IndexNumberEnd ?? num); - } - } + item.Item.IndexNumberEnd = Math.Max(num, item.Item.IndexNumberEnd ?? num); } } } From b18bb3d0de5e459b9bafbc3a67afe6204eca1b08 Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 23 Feb 2021 19:22:20 +0900 Subject: [PATCH 1141/1930] update timestamp parse for plugins --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 696133c9f0..fec7bcb87e 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -372,7 +372,7 @@ namespace Emby.Server.Implementations.Plugins Overview = packageInfo.Overview, Owner = packageInfo.Owner, TargetAbi = versionInfo.TargetAbi ?? string.Empty, - Timestamp = DateTime.Parse(versionInfo.Timestamp ?? string.Empty), + Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp), Version = versionInfo.Version, Status = PluginStatus.Active, AutoUpdate = true, From aff0aea60fc52a2253f04749f11bcb02f6e1f67c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 23 Feb 2021 14:14:02 +0100 Subject: [PATCH 1142/1930] Improve branch coverage --- .../Models/LiveTvDtos/GetProgramsDto.cs | 1 - .../JsonOmdbNotAvailableInt32Converter.cs | 2 +- .../TestPluginWithoutPages.cs | 27 ++++++++++ .../Json/JsonCommaDelimitedArrayTests.cs | 52 ++++++++++++++++++- .../Json/JsonOmdbConverterTests.cs | 27 +++++----- 5 files changed, 92 insertions(+), 17 deletions(-) create mode 100644 tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs diff --git a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs index 588ce717c8..8913180e48 100644 --- a/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs +++ b/Jellyfin.Api/Models/LiveTvDtos/GetProgramsDto.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using Jellyfin.Data.Enums; using MediaBrowser.Common.Json.Converters; diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs index cb3d83f584..3d97a9de55 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableInt32Converter.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Json.Converters return (int?)converter.ConvertFromString(str); } - return JsonSerializer.Deserialize(ref reader, options); + return JsonSerializer.Deserialize(ref reader, options); } /// diff --git a/tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs b/tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs new file mode 100644 index 0000000000..2d2f78a981 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs @@ -0,0 +1,27 @@ +#pragma warning disable CS1591 + +using System; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Api.Tests +{ + public class TestPluginWithoutPages : BasePlugin + { + public TestPluginWithoutPages(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + } + + public static TestPluginWithoutPages? Instance { get; private set; } + + public override Guid Id => new Guid("ae95cbe6-bd3d-4d73-8596-490db334611e"); + + public override string Name => nameof(TestPluginWithoutPages); + + public override string Description => "Server test Plugin without web pages."; + } +} diff --git a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs index 0d2bdd1af9..ca300401da 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonCommaDelimitedArrayTests.cs @@ -1,4 +1,5 @@ -using System.Text.Json; +using System; +using System.Text.Json; using System.Text.Json.Serialization; using Jellyfin.Common.Tests.Models; using MediaBrowser.Model.Session; @@ -8,6 +9,27 @@ namespace Jellyfin.Common.Tests.Json { public static class JsonCommaDelimitedArrayTests { + [Fact] + public static void Deserialize_String_Null_Success() + { + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": null }", options); + Assert.Null(value?.Value); + } + + [Fact] + public static void Deserialize_Empty_Success() + { + var desiredValue = new GenericBodyArrayModel + { + Value = Array.Empty() + }; + + var options = new JsonSerializerOptions(); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": """" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + [Fact] public static void Deserialize_String_Valid_Success() { @@ -48,6 +70,34 @@ namespace Jellyfin.Common.Tests.Json Assert.Equal(desiredValue.Value, value?.Value); } + [Fact] + public static void Deserialize_GenericCommandType_EmptyEntry_Success() + { + var desiredValue = new GenericBodyArrayModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,,MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + + [Fact] + public static void Deserialize_GenericCommandType_Invalid_Success() + { + var desiredValue = new GenericBodyArrayModel + { + Value = new[] { GeneralCommandType.MoveUp, GeneralCommandType.MoveDown } + }; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new JsonStringEnumConverter()); + var value = JsonSerializer.Deserialize>(@"{ ""Value"": ""MoveUp,TotallyNotAVallidCommand,MoveDown"" }", options); + Assert.Equal(desiredValue.Value, value?.Value); + } + [Fact] public static void Deserialize_GenericCommandType_Space_Valid_Success() { diff --git a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs index faed086a12..efe8063a07 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonOmdbConverterTests.cs @@ -38,6 +38,15 @@ namespace Jellyfin.Common.Tests.Json Assert.Null(result); } + [Theory] + [InlineData("\"8\"", 8)] + [InlineData("8", 8)] + public void Deserialize_NullableInt_Success(string input, int? expected) + { + var result = JsonSerializer.Deserialize(input, _options); + Assert.Equal(result, expected); + } + [Theory] [InlineData("\"N/A\"")] [InlineData("null")] @@ -48,21 +57,11 @@ namespace Jellyfin.Common.Tests.Json } [Theory] - [InlineData("\"8\"", 8)] - [InlineData("8", 8)] - public void Deserialize_Int_Success(string input, int expected) + [InlineData("\"Jellyfin\"", "Jellyfin")] + public void Deserialize_Normal_String_Success(string input, string expected) { - var result = JsonSerializer.Deserialize(input, _options); - Assert.Equal(result, expected); - } - - [Fact] - public void Deserialize_Normal_String_Success() - { - const string Input = "\"Jellyfin\""; - const string Expected = "Jellyfin"; - var result = JsonSerializer.Deserialize(Input, _options); - Assert.Equal(Expected, result); + var result = JsonSerializer.Deserialize(input, _options); + Assert.Equal(expected, result); } [Fact] From 64cc5889f2be0dae6b0425c569bd84f996a0e435 Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 23 Feb 2021 23:11:17 +0900 Subject: [PATCH 1143/1930] add suggested changes --- .../Plugins/PluginManager.cs | 49 +++++++++++++++---- .../Updates/InstallationManager.cs | 4 +- MediaBrowser.Common/Plugins/IPluginManager.cs | 2 +- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index fec7bcb87e..b4ab551579 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -4,14 +4,16 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; +using System.Net.Http; using System.Reflection; using System.Text; using System.Text.Json; +using System.Threading.Tasks; using MediaBrowser.Common; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; using MediaBrowser.Common.Json.Converters; +using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Plugins; @@ -35,6 +37,21 @@ namespace Emby.Server.Implementations.Plugins private readonly IList _plugins; private readonly Version _minimumVersion; + private IHttpClientFactory? _httpClientFactory; + + private IHttpClientFactory HttpClientFactory + { + get + { + if (_httpClientFactory == null) + { + _httpClientFactory = _appHost.Resolve(); + } + + return _httpClientFactory; + } + } + /// /// Initializes a new instance of the class. /// @@ -351,15 +368,29 @@ namespace Emby.Server.Implementations.Plugins } /// - public bool GenerateManifest(PackageInfo packageInfo, Version version, string path) + public async Task GenerateManifest(PackageInfo packageInfo, Version version, string path) { - var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString()); - var url = packageInfo.ImageUrl ?? string.Empty; - var imageFilename = url.Substring(url.LastIndexOf('/') + 1, url.Length); - - using (var client = new WebClient()) + if (packageInfo == null) { - client.DownloadFile(url, Path.Join(path, imageFilename)); + return false; + } + + var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString()); + var imagePath = string.Empty; + + if (!string.IsNullOrEmpty(packageInfo.ImageUrl)) + { + var url = new Uri(packageInfo.ImageUrl); + imagePath = Path.Join(path, url.Segments.Last()); + + await using var fileStream = File.OpenWrite(imagePath); + var downloadStream = await HttpClientFactory + .CreateClient(NamedClient.Default) + .GetStreamAsync(url) + .ConfigureAwait(false); + + await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); + await fileStream.DisposeAsync(); } var manifest = new PluginManifest @@ -376,7 +407,7 @@ namespace Emby.Server.Implementations.Plugins Version = versionInfo.Version, Status = PluginStatus.Active, AutoUpdate = true, - ImagePath = Path.Join(path, imageFilename) + ImagePath = imagePath }; return SaveManifest(manifest, path); diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 534c0aa4b8..7af52ea652 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -194,7 +194,7 @@ namespace Emby.Server.Implementations.Updates var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber); if (plugin != null) { - _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path); + await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path); } // Remove versions with a target ABI greater then the current application version. @@ -567,7 +567,7 @@ namespace Emby.Server.Implementations.Updates stream.Position = 0; _zipClient.ExtractAllFromZip(stream, targetDir, true); - _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir); + await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir); _pluginManager.ImportPluginFrom(targetDir); } diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index 6f0a0fbfc8..fc2fcb5179 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -52,7 +52,7 @@ namespace MediaBrowser.Common.Plugins /// Version to be installed. /// The path where to save the manifest. /// True if successful. - bool GenerateManifest(PackageInfo packageInfo, Version version, string path); + Task GenerateManifest(PackageInfo packageInfo, Version version, string path); /// /// Imports plugin details from a folder. From 454deece13b138e5bcb694732b622be27cb6d204 Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 23 Feb 2021 23:36:49 +0900 Subject: [PATCH 1144/1930] improve performance in the wrong place Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index b4ab551579..4dc2985d38 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -381,7 +381,7 @@ namespace Emby.Server.Implementations.Plugins if (!string.IsNullOrEmpty(packageInfo.ImageUrl)) { var url = new Uri(packageInfo.ImageUrl); - imagePath = Path.Join(path, url.Segments.Last()); + imagePath = Path.Join(path, url.Segments[^1]); await using var fileStream = File.OpenWrite(imagePath); var downloadStream = await HttpClientFactory From e9030a62fb9bc48f52b9f961d20e972ad300abeb Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 23 Feb 2021 23:37:32 +0900 Subject: [PATCH 1145/1930] remove useless call to dispose Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Plugins/PluginManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 4dc2985d38..b0a8aba168 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -390,7 +390,6 @@ namespace Emby.Server.Implementations.Plugins .ConfigureAwait(false); await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); - await fileStream.DisposeAsync(); } var manifest = new PluginManifest From fb2d17824225e9849a45bc146fa6e09f3c71b1fb Mon Sep 17 00:00:00 2001 From: dkanada Date: Tue, 23 Feb 2021 23:39:33 +0900 Subject: [PATCH 1146/1930] add await directive for image download Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Plugins/PluginManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index b0a8aba168..d8dac65991 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -384,7 +384,7 @@ namespace Emby.Server.Implementations.Plugins imagePath = Path.Join(path, url.Segments[^1]); await using var fileStream = File.OpenWrite(imagePath); - var downloadStream = await HttpClientFactory + await using var downloadStream = await HttpClientFactory .CreateClient(NamedClient.Default) .GetStreamAsync(url) .ConfigureAwait(false); From 9bfe945f6c1f41ea3456ae27b1ad31a04f3cea3f Mon Sep 17 00:00:00 2001 From: dkanada Date: Wed, 24 Feb 2021 00:03:26 +0900 Subject: [PATCH 1147/1930] catch http exception and fix possible issues --- .../Plugins/PluginManager.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index d8dac65991..7bc9f0a7e2 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -384,12 +384,21 @@ namespace Emby.Server.Implementations.Plugins imagePath = Path.Join(path, url.Segments[^1]); await using var fileStream = File.OpenWrite(imagePath); - await using var downloadStream = await HttpClientFactory - .CreateClient(NamedClient.Default) - .GetStreamAsync(url) - .ConfigureAwait(false); - await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); + try + { + await using var downloadStream = await HttpClientFactory + .CreateClient(NamedClient.Default) + .GetStreamAsync(url) + .ConfigureAwait(false); + + await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false); + } + catch (HttpRequestException ex) + { + _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath); + imagePath = string.Empty; + } } var manifest = new PluginManifest From acac21d8dc3eb9383136ff692606dc2f65adf405 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 23 Feb 2021 16:45:10 +0100 Subject: [PATCH 1148/1930] Improve tests --- .../EntryPoints/UdpServerEntryPoint.cs | 11 + Emby.Server.Implementations/Udp/UdpServer.cs | 2 +- .../JsonCommaDelimitedArrayConverter.cs | 2 +- .../JsonPipeDelimitedArrayConverter.cs | 2 +- .../Json/Converters/JsonVersionConverter.cs | 20 - MediaBrowser.Common/Json/JsonDefaults.cs | 1 - .../Test Data/Updates/manifest-stable.json | 684 ++++++++++++++++++ .../Updates/InstallationManagerTests.cs | 57 ++ 8 files changed, 755 insertions(+), 24 deletions(-) delete mode 100644 MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index a12a6b26c5..3624e079f5 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,5 +1,6 @@ #nullable enable +using System; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -51,6 +52,8 @@ namespace Emby.Server.Implementations.EntryPoints /// public Task RunAsync() { + CheckDisposed(); + try { _udpServer = new UdpServer(_logger, _appHost, _config); @@ -64,6 +67,14 @@ namespace Emby.Server.Implementations.EntryPoints return Task.CompletedTask; } + private void CheckDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(this.GetType().Name); + } + } + /// public void Dispose() { diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index 4fd7ac0c18..d01184e0b6 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -79,7 +79,7 @@ namespace Emby.Server.Implementations.Udp /// Starts the specified port. /// /// The port. - /// + /// The cancellation token to cancel operation. public void Start(int port, CancellationToken cancellationToken) { _endpoint = new IPEndPoint(IPAddress.Any, port); diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index 38a7e1d20f..d9f6519e98 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Common.Json.Converters /// public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) { - JsonSerializer.Serialize(writer, value, options); + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs index 377db1a446..c408a3be13 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -69,7 +69,7 @@ namespace MediaBrowser.Common.Json.Converters /// public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) { - JsonSerializer.Serialize(writer, value, options); + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs deleted file mode 100644 index 37e6f64e34..0000000000 --- a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace MediaBrowser.Common.Json.Converters -{ - /// - /// Converts a Version object or value to/from JSON. - /// - public class JsonVersionConverter : JsonConverter - { - /// - public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => new Version(reader.GetString()); - - /// - public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) - => writer.WriteStringValue(value.ToString()); - } -} diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 2ef24a884a..a3999e7e25 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -35,7 +35,6 @@ namespace MediaBrowser.Common.Json { new JsonGuidConverter(), new JsonNullableGuidConverter(), - new JsonVersionConverter(), new JsonStringEnumConverter(), new JsonNullableStructConverterFactory(), new JsonBoolNumberConverter(), diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json new file mode 100644 index 0000000000..b766e668e3 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/Updates/manifest-stable.json @@ -0,0 +1,684 @@ +[ + { + "guid": "a4df60c5-6ab4-412a-8f79-2cab93fb2bc5", + "name": "Anime", + "description": "Manage your anime in Jellyfin. This plugin supports several different metadata providers and options for organizing your collection.\n", + "overview": "Manage your anime from Jellyfin", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "10.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_10.0.0.0.zip", + "checksum": "93e969adeba1050423fc8817ed3c36f8", + "timestamp": "2020-08-17T01:41:13Z" + }, + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/anime/anime_9.0.0.0.zip", + "checksum": "9b1cebff835813e15f414f44b40c41c8", + "timestamp": "2020-07-20T01:30:16Z" + } + ] + }, + { + "guid": "70b7b43b-471b-4159-b4be-56750c795499", + "name": "Auto Organize", + "description": "Automatically organize your media", + "overview": "Automatically organize your media", + "owner": "jellyfin", + "category": "General", + "versions": [ + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/auto-organize/auto-organize_9.0.0.0.zip", + "checksum": "ff29ac3cbe05d208b6af94cd6d9dea39", + "timestamp": "2020-12-05T22:31:12Z" + }, + { + "version": "8.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/auto-organize/auto-organize_8.0.0.0.zip", + "checksum": "460bbb45e556464a8476b18e41c097f5", + "timestamp": "2020-07-20T01:30:25Z" + } + ] + }, + { + "guid": "9c4e63f1-031b-4f25-988b-4f7d78a8b53e", + "name": "Bookshelf", + "description": "Supports several different metadata providers and options for organizing your collection.\n", + "overview": "Manage your books", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "5.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/bookshelf/bookshelf_5.0.0.0.zip", + "checksum": "2063fb8ab317b8d77b200fde41eb5e1e", + "timestamp": "2020-12-05T22:03:13Z" + }, + { + "version": "4.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/bookshelf/bookshelf_4.0.0.0.zip", + "checksum": "fc9f76c0815d766491e5b0f30ede55ed", + "timestamp": "2020-07-20T01:30:33Z" + } + ] + }, + { + "guid": "cfa0f7f4-4155-4d71-849b-d6598dc4c5bb", + "name": "Email", + "description": "Send SMTP email notifications", + "overview": "Send SMTP email notifications", + "owner": "jellyfin", + "category": "Notifications", + "versions": [ + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/email/email_9.0.0.0.zip", + "checksum": "cfe7afc00f3fbd6d6ab8244d7ff968ce", + "timestamp": "2020-12-05T22:20:32Z" + }, + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/email/email_7.0.0.0.zip", + "checksum": "680ca511d8ad84923cb04f024fd8eb19", + "timestamp": "2020-07-20T01:30:40Z" + } + ] + }, + { + "guid": "170a157f-ac6c-437a-abdd-ca9c25cebd39", + "name": "Fanart", + "description": "Scrape poster images for movies, shows, and artists in your library.", + "overview": "Scrape poster images from Fanart", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/fanart/fanart_6.0.0.0.zip", + "checksum": "ee4360bfcc8722d5a3a54cfe7eef640f", + "timestamp": "2020-12-05T22:25:43Z" + }, + { + "version": "5.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/fanart/fanart_5.0.0.0.zip", + "checksum": "f842f7d65d23f377761c907d40b89647", + "timestamp": "2020-07-20T01:30:48Z" + } + ] + }, + { + "guid": "e29621a5-fa9e-4330-982e-ef6e54c0cad2", + "name": "Gotify Notification", + "description": "You must have a Gotify server to use this plugin!\n", + "overview": "Sends notifications to your Gotify server", + "owner": "crobibero", + "category": "Notifications", + "versions": [ + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/gotify-notification/gotify-notification_7.0.0.0.zip", + "checksum": "7c5ff9e8792c8cdee7e8a2aaeb6cc093", + "timestamp": "2020-07-20T01:30:56Z" + } + ] + }, + { + "guid": "a59b5c4b-05a8-488f-bfa8-7a63fffc7639", + "name": "IPTV", + "description": "Enable IPTV support in Jellyfin", + "overview": "Enable IPTV support in Jellyfin", + "owner": "jellyfin", + "category": "Channel", + "versions": [ + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/iptv/iptv_6.0.0.0.zip", + "checksum": "9cf103bf67a4eda7c3a42d9b235f6447", + "timestamp": "2020-07-20T01:31:05Z" + } + ] + }, + { + "guid": "4682DD4C-A675-4F1B-8E7C-79ADF137A8F8", + "name": "ISO Mounter", + "description": "Mount your ISO files for Jellyfin.\n", + "overview": "Mount your ISO files for Jellyfin", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "1.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/iso-mounter/iso-mounter_1.0.0.0.zip", + "checksum": "847e5bc7ac34c1bf4dc5b28173170fae", + "timestamp": "2020-07-20T01:31:13Z" + } + ] + }, + { + "guid": "771e19d6-5385-4caf-b35c-28a0e865cf63", + "name": "Kodi Sync Queue", + "description": "This plugin will track all media changes while Kodi clients are offline to decrease sync times.", + "overview": "Sync all media changes with Kodi clients", + "owner": "jellyfin", + "category": "General", + "versions": [ + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/kodi-sync-queue/kodi-sync-queue_6.0.0.0.zip", + "checksum": "787c856c0d2ad2224cdd8b3094cf0329", + "timestamp": "2020-12-05T22:10:37Z" + }, + { + "version": "5.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/kodi-sync-queue/kodi-sync-queue_5.0.0.0.zip", + "checksum": "08285397aecd93ea64a4f15d38b1bd7b", + "timestamp": "2020-07-20T01:31:22Z" + } + ] + }, + { + "guid": "958aad66-3784-4d2a-b89a-a7b6fab6e25c", + "name": "LDAP Authentication", + "description": "Authenticate your Jellyfin users against an LDAP database, and optionally create users who do not yet exist automatically.\nAllows the administrator to customize most aspects of the LDAP authentication process, including customizable search attributes, username attribute, and a search filter for administrative users (set on user creation). The user, via the \"Manual Login\" process, can enter any valid attribute value, which will be mapped back to the specified username attribute automatically as well.\n", + "overview": "Authenticate users against an LDAP database", + "owner": "jellyfin", + "category": "Authentication", + "versions": [ + { + "version": "10.0.0.0", + "changelog": "Update for 10.7 support\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_10.0.0.0.zip", + "checksum": "62e7e1cd3ffae0944c14750a3c90df4f", + "timestamp": "2020-12-05T19:48:10Z" + }, + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_9.0.0.0.zip", + "checksum": "7f2f83587a65a43ebf168e4058421463", + "timestamp": "2020-07-22T15:42:57Z" + }, + { + "version": "8.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/ldap-authentication/ldap-authentication_8.0.0.0.zip", + "checksum": "8af8cee62717d63577f8b1e710839415", + "timestamp": "2020-07-20T01:31:30Z" + } + ] + }, + { + "guid": "9574ac10-bf23-49bc-949f-924f23cfa48f", + "name": "NextPVR", + "description": "Provides access to live TV, program guide, and recordings from NextPVR.\n", + "overview": "Live TV plugin for NextPVR", + "owner": "jellyfin", + "category": "LiveTV", + "versions": [ + { + "version": "5.0.0.0", + "changelog": "Updated to use NextPVR API v5, no longer compatable with API v4.\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/nextpvr/nextpvr_5.0.0.0.zip", + "checksum": "d70f694d14bf9462ba2b2ebe110068d3", + "timestamp": "2020-12-05T22:24:03Z" + }, + { + "version": "4.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/nextpvr/nextpvr_4.0.0.0.zip", + "checksum": "b15949d895ac5a8c89496581db350478", + "timestamp": "2020-07-20T01:31:38Z" + } + ] + }, + { + "guid": "4b9ed42f-5185-48b5-9803-6ff2989014c4", + "name": "Open Subtitles", + "description": "Download subtitles from the internet to use with your media files.", + "overview": "Download subtitles for your media", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "10.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/open-subtitles/open-subtitles_10.0.0.0.zip", + "checksum": "ed99d03ec463bf15fca1256a113f57b4", + "timestamp": "2020-12-05T21:56:19Z" + }, + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/open-subtitles/open-subtitles_9.0.0.0.zip", + "checksum": "16789b26497cea0509daf6b18c579340", + "timestamp": "2020-07-20T01:32:00Z" + } + ] + }, + { + "guid": "5c534381-91a3-43cb-907a-35aa02eb9d2c", + "name": "Playback Reporting", + "description": "Collect and show user play statistics", + "overview": "Collect and show user play statistics", + "owner": "jellyfin", + "category": "General", + "versions": [ + { + "version": "9.0.0.0", + "changelog": "Add authentication to plugin endpoints\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_9.0.0.0.zip", + "checksum": "ca323b3dcb2cb86cc2e72a7a0f1eee22", + "timestamp": "2020-12-05T22:15:48Z" + }, + { + "version": "8.0.0.0", + "changelog": "Add authentication to plugin endpoints\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_8.0.0.0.zip", + "checksum": "58644c505586542ef0b8b65e2f704bd1", + "timestamp": "2020-11-18T03:01:51Z" + }, + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/playback-reporting/playback-reporting_7.0.0.0.zip", + "checksum": "6a361ef33bca97f9155856d02ff47380", + "timestamp": "2020-07-20T01:32:09Z" + } + ] + }, + { + "guid": "de228f12-e43e-4bd9-9fc0-2830819c3b92", + "name": "Pushbullet", + "description": "Get notifications via Pushbullet.\n", + "overview": "Pushbullet notification plugin", + "owner": "jellyfin", + "category": "Notifications", + "versions": [ + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushbullet/pushbullet_6.0.0.0.zip", + "checksum": "248cf3d56644f1d909e75aaddbdfb3a6", + "timestamp": "2020-12-06T02:47:53Z" + }, + { + "version": "5.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushbullet/pushbullet_5.0.0.0.zip", + "checksum": "dabbdd86328b2922a69dfa0c9e1c8343", + "timestamp": "2020-07-20T01:32:17Z" + } + ] + }, + { + "guid": "F240D6BE-5743-441B-87F1-A70ECAC42642", + "name": "Pushover", + "description": "Send messages to a wide range of devices through Pushover.", + "overview": "Send notifications via Pushover", + "owner": "crobibero", + "category": "Notifications", + "versions": [ + { + "version": "4.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/pushover/pushover_4.0.0.0.zip", + "checksum": "56a0da16c7e48cc184987737b7e155dd", + "timestamp": "2020-07-20T01:32:25Z" + } + ] + }, + { + "guid": "d4312cd9-5c90-4f38-82e8-51da566790e8", + "name": "Reports", + "description": "Generate reports of your media library", + "overview": "Generate reports of your media library", + "owner": "jellyfin", + "category": "General", + "versions": [ + { + "version": "11.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_11.0.0.0.zip", + "checksum": "d71bc6a4c008e58ee70ad44c83bfd310", + "timestamp": "2020-12-05T22:00:46Z" + }, + { + "version": "10.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_10.0.0.0.zip", + "checksum": "3917e75839337475b42daf2ba0b5bd7b", + "timestamp": "2020-10-19T19:30:41Z" + }, + { + "version": "9.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/reports/reports_9.0.0.0.zip", + "checksum": "5b5ad8d885616a21e8d1e8eecf5ea979", + "timestamp": "2020-10-16T23:52:37Z" + } + ] + }, + { + "guid": "1fc322a1-af2e-49a5-b2eb-a89b4240f700", + "name": "ServerWMC", + "description": "Provides access to Live TV, Program Guide and Recordings from your Windows MediaCenter Server running ServerWMC. Requires ServerWMC to be installed and running on your Windows MediaCenter machine.\n", + "overview": "Jellyfin Live TV plugin for Windows MediaCenter with ServerWMC", + "owner": "jellyfin", + "category": "LiveTV", + "versions": [ + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/serverwmc/serverwmc_6.0.0.0.zip", + "checksum": "3120af0cea2c1cb8b7cf578d9b4b862c", + "timestamp": "2020-12-05T22:28:15Z" + }, + { + "version": "5.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/serverwmc/serverwmc_5.0.0.0.zip", + "checksum": "dc44b039aa1b66eaf40a44fbf02d37e2", + "timestamp": "2020-07-20T01:32:42Z" + } + ] + }, + { + "guid": "94fb77c3-55ad-4c50-bf4e-4e5497467b79", + "name": "Slack Notifications", + "description": "Get notifications via Slack.\n", + "overview": "Get notifications via Slack", + "owner": "jellyfin", + "category": "Notifications", + "versions": [ + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/slack-notifications/slack-notifications_7.0.0.0.zip", + "checksum": "1d5330a77ce7b2a9ac8e5d58088a012c", + "timestamp": "2020-12-05T22:40:02Z" + }, + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/slack-notifications/slack-notifications_6.0.0.0.zip", + "checksum": "ede4cbe064542d1ecccc5823921bee4b", + "timestamp": "2020-07-20T01:32:50Z" + } + ] + }, + { + "guid": "bc4aad2e-d3d0-4725-a5e2-fd07949e5b42", + "name": "TMDb Box Sets", + "description": "Automatically create movie box sets based on TMDb collections", + "overview": "Automatically create movie box sets based on TMDb collections", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tmdb-box-sets/tmdb-box-sets_7.0.0.0.zip", + "checksum": "1551792e6af4d36f2cead01153c73cf0", + "timestamp": "2020-12-05T22:07:21Z" + }, + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tmdb-box-sets/tmdb-box-sets_6.0.0.0.zip", + "checksum": "b92b68a922c5fcbb8f4d47b8601b01b6", + "timestamp": "2020-07-20T01:32:58Z" + } + ] + }, + { + "guid": "4fe3201e-d6ae-4f2e-8917-e12bda571281", + "name": "Trakt", + "description": "Record your watched media with Trakt.\n", + "overview": "Record your watched media with Trakt", + "owner": "jellyfin", + "category": "General", + "versions": [ + { + "version": "11.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/trakt/trakt_11.0.0.0.zip", + "checksum": "2257ccde1e39114644a27e0966a0bf2d", + "timestamp": "2020-12-05T19:56:12Z" + }, + { + "version": "10.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/trakt/trakt_10.0.0.0.zip", + "checksum": "ab67e6b59ea2e7860a6a3ff7b8452759", + "timestamp": "2020-07-20T01:33:06Z" + } + ] + }, + { + "guid": "3fd018e5-5e78-4e58-b280-a0c068febee0", + "name": "TVHeadend", + "description": "Manage TVHeadend from Jellyfin", + "overview": "Manage TVHeadend from Jellyfin", + "owner": "jellyfin", + "category": "LiveTV", + "versions": [ + { + "version": "7.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tvheadend/tvheadend_7.0.0.0.zip", + "checksum": "1abbfce737b6962f4b1b2255dc63e932", + "timestamp": "2021-01-05T16:20:33Z" + }, + { + "version": "6.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tvheadend/tvheadend_6.0.0.0.zip", + "checksum": "143c34fd70d7173b8912cc03ce4b517d", + "timestamp": "2020-07-20T01:33:15Z" + } + ] + }, + { + "guid": "022a3003-993f-45f1-8565-87d12af2e12a", + "name": "InfuseSync", + "description": "This plugin will track all media changes while any Infuse clients are offline to decrease sync times when logging back in to your server.", + "overview": "Blazing fast indexing for Infuse", + "owner": "Firecore LLC", + "category": "General", + "versions": [ + { + "version": "1.2.4.0", + "changelog": "New Playlist support.\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.4/InfuseSync-jellyfin-1.2.4.zip", + "checksum": "7adde11b8c8404fd2923f59d98fb1a30", + "timestamp": "2020-10-12T08:00:00Z" + }, + { + "version": "1.2.1.3", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.3/InfuseSync-jellyfin-1.2.3.zip", + "checksum": "d8e2c5fe736a302097bb3bac3d04b1c4", + "timestamp": "2020-09-18T12:19:00Z" + }, + { + "version": "1.2.1.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.1/InfuseSync-jellyfin-1.2.1.zip", + "checksum": "1a853e926cc422f5d79d398d9ae18ee8", + "timestamp": "2020-08-21T10:48:00Z" + }, + { + "version": "1.2.0.0", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://github.com/firecore/InfuseSync/releases/download/v1.2.0/InfuseSync-jellyfin-1.2.0.zip", + "checksum": "2d3c7859852695a7f05adc6d3fcbc783", + "timestamp": "2020-07-20T11:51:00Z" + } + ] + }, + { + "guid": "8119f3c6-cfc2-4d9c-a0ba-028f1d93e526", + "name": "Cover Art Archive", + "description": "This plugin provides images from the Cover Art Archive https://musicbrainz.org/doc/Cover_Art_Archive and depends on the MusicBrainz metadata provider to know what images belong where\n", + "overview": "MusicBrainz Cover Art Archive", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "2.0.0.0", + "changelog": "changelog\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/cover-art-archive/cover-art-archive_2.0.0.0.zip", + "checksum": "bea8fa4a37b3e7ed74e22266e7597a68", + "timestamp": "2020-12-06T02:51:03Z" + }, + { + "version": "1.0.0.3", + "changelog": "changelog\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/cover-art-archive/cover-art-archive_1.0.0.3.zip", + "checksum": "c502a5c54b168810614c1c40709b9598", + "timestamp": "2020-08-06T21:21:22Z" + } + ] + }, + { + "guid": "A4A488D0-17A3-4919-8D82-7F3DE4F6B209", + "name": "TV Maze", + "description": "Get TV metadata from TV Maze\n", + "overview": "Get TV metadata from TV Maze", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "5.0.0.0", + "changelog": "Get additional image types\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_5.0.0.0.zip", + "checksum": "509a85e40b1d1ac36eef45673deaf606", + "timestamp": "2020-12-06T02:51:56Z" + }, + { + "version": "4.0.0.0", + "changelog": "Get additional image types\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_4.0.0.0.zip", + "checksum": "58ee9ab3f129151bdfff033ad889ad87", + "timestamp": "2020-11-24T14:44:37Z" + }, + { + "version": "3.0.0.0", + "changelog": "Remove unused dependencies \n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_3.0.0.0.zip", + "checksum": "f3b2c70b3e136fb15c917e4420f4fdec", + "timestamp": "2020-11-09T14:32:56Z" + }, + { + "version": "2.0.0.0", + "changelog": "Remove unused dependencies \n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_2.0.0.0.zip", + "checksum": "c7662ae8ae52ce8a4e8d685d55f36e80", + "timestamp": "2020-11-09T02:33:11Z" + }, + { + "version": "1.0.0.0", + "changelog": "Initial release.\n", + "targetAbi": "10.6.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/tv-maze/tv-maze_1.0.0.0.zip", + "checksum": "c90eee48c12f2c07880b4b28e507fd14", + "timestamp": "2020-11-08T19:05:32Z" + } + ] + }, + { + "guid": "a677c0da-fac5-4cde-941a-7134223f14c8", + "name": "TheTVDB", + "description": "Get TV metadata from TheTvdb\n", + "overview": "Get TV metadata from TheTvdb", + "owner": "jellyfin", + "category": "Metadata", + "versions": [ + { + "version": "2.0.0.0", + "changelog": "Remove from Jellyfin core.\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/thetvdb/thetvdb_2.0.0.0.zip", + "checksum": "e46cee334476a1b475e5c553171c4cb6", + "timestamp": "2020-12-16T20:03:28Z" + }, + { + "version": "1.0.0.0", + "changelog": "Remove from Jellyfin core.\n", + "targetAbi": "10.7.0.0", + "sourceUrl": "https://repo.jellyfin.org/releases/plugin/thetvdb/thetvdb_1.0.0.0.zip", + "checksum": "5a3dca5c0db4824d83bfd4e7e2b7bf11", + "timestamp": "2020-12-06T02:56:40Z" + } + ] + } +] \ No newline at end of file diff --git a/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs new file mode 100644 index 0000000000..4fa64d8a22 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Updates/InstallationManagerTests.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.Updates; +using MediaBrowser.Model.Updates; +using Moq; +using Moq.Protected; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Updates +{ + public class InstallationManagerTests + { + private readonly Fixture _fixture; + private readonly InstallationManager _installationManager; + + public InstallationManagerTests() + { + var messageHandler = new Mock(); + messageHandler.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .Returns( + (m, _) => + { + return Task.FromResult(new HttpResponseMessage() + { + Content = new StreamContent(File.OpenRead("Test Data/Updates/" + m.RequestUri?.Segments[^1])) + }); + }); + + var http = new Mock(); + http.Setup(x => x.CreateClient(It.IsAny())) + .Returns(new HttpClient(messageHandler.Object)); + _fixture = new Fixture(); + _fixture.Customize(new AutoMoqCustomization + { + ConfigureMembers = true + }).Inject(http); + _installationManager = _fixture.Create(); + } + + [Fact] + public async Task GetPackages_Valid_Success() + { + IList packages = await _installationManager.GetPackages( + "Jellyfin Stable", + "https://repo.jellyfin.org/releases/plugin/manifest-stable.json", + false); + + Assert.Equal(25, packages.Count); + } + } +} From 032d72a8a7a1c3884d07b0f3b7bd93790988d414 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 23 Feb 2021 17:30:24 +0100 Subject: [PATCH 1149/1930] Pls fix race condition --- Emby.Server.Implementations/ApplicationHost.cs | 10 ++++++---- Jellyfin.Server/Program.cs | 2 +- tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs | 5 +++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0a7c5c1fb0..d7ac8bc3bb 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -126,7 +126,6 @@ namespace Emby.Server.Implementations private IMediaEncoder _mediaEncoder; private ISessionManager _sessionManager; private string[] _urlPrefixes; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); /// /// Gets a value indicating whether this instance can self restart. @@ -484,8 +483,9 @@ namespace Emby.Server.Implementations /// Runs the startup tasks. /// /// . - public async Task RunStartupTasksAsync() + public async Task RunStartupTasksAsync(CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); Logger.LogInformation("Running startup tasks"); Resolve().AddTasks(GetExports(false)); @@ -501,13 +501,15 @@ namespace Emby.Server.Implementations var stopWatch = new Stopwatch(); stopWatch.Start(); - await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + await Task.WhenAny(Task.WhenAll(StartEntryPoints(entryPoints, true)), Task.Delay(-1, cancellationToken)).ConfigureAwait(false); Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed); Logger.LogInformation("Core startup complete"); CoreStartupHasCompleted = true; stopWatch.Restart(); - await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + await Task.WhenAny(Task.WhenAll(StartEntryPoints(entryPoints, false)), Task.Delay(-1, cancellationToken)).ConfigureAwait(false); Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed); stopWatch.Stop(); } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index f05cdfe9bd..81199c7752 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -202,7 +202,7 @@ namespace Jellyfin.Server throw; } - await appHost.RunStartupTasksAsync().ConfigureAwait(false); + await appHost.RunStartupTasksAsync(_tokenSource.Token).ConfigureAwait(false); stopWatch.Stop(); diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs index dbbd5ac28c..ab7e0b6e7d 100644 --- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.IO; +using System.Threading; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; using Jellyfin.Server; @@ -21,7 +22,7 @@ namespace Jellyfin.Api.Tests public class JellyfinApplicationFactory : WebApplicationFactory { private static readonly string _testPathRoot = Path.Combine(Path.GetTempPath(), "jellyfin-test-data"); - private static readonly ConcurrentBag _disposableComponents = new ConcurrentBag(); + private readonly ConcurrentBag _disposableComponents = new ConcurrentBag(); /// /// Initializes a new instance of the class. @@ -96,7 +97,7 @@ namespace Jellyfin.Api.Tests var appHost = (TestAppHost)testServer.Services.GetRequiredService(); appHost.ServiceProvider = testServer.Services; appHost.InitializeServices().GetAwaiter().GetResult(); - appHost.RunStartupTasksAsync().GetAwaiter().GetResult(); + appHost.RunStartupTasksAsync(CancellationToken.None).GetAwaiter().GetResult(); return testServer; } From ff7cae8a13ce4bd5f158da840907a46ef2ad7d86 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 23 Feb 2021 17:06:40 +0000 Subject: [PATCH 1150/1930] renamed method --- Jellyfin.Networking/Manager/NetworkManager.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index bd4b165b5d..9cb49ce685 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; @@ -693,7 +694,7 @@ namespace Jellyfin.Networking.Manager /// String to check. /// Interface index numbers that match. /// true if an interface name matches the token, False otherwise. - private bool IsInterface(string token, out List? index) + private bool TryIsInterface(string token, [NotNullWhen(true)] out List? index) { index = null; @@ -734,14 +735,14 @@ namespace Jellyfin.Networking.Manager { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. - if (IsInterface(token, out var index)) + if (TryIsInterface(token, out var index)) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); // Replace all the interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (index!.Contains(Math.Abs(iface.Tag)) + if (index.Contains(Math.Abs(iface.Tag)) && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { From f67137004c16fc8bf2478e9898e786599469c465 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 23 Feb 2021 20:34:32 +0000 Subject: [PATCH 1151/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Bond-009 --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 9cb49ce685..e4623cd62b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -694,7 +694,7 @@ namespace Jellyfin.Networking.Manager /// String to check. /// Interface index numbers that match. /// true if an interface name matches the token, False otherwise. - private bool TryIsInterface(string token, [NotNullWhen(true)] out List? index) + private bool TryIsInterface(string token, [MaybeNullWhen(false)] out List index) { index = null; From b5c6e5fb97d06533583f8273227f9215906c2ed1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 23 Feb 2021 20:34:42 +0000 Subject: [PATCH 1152/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Bond-009 --- Jellyfin.Networking/Manager/NetworkManager.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index e4623cd62b..3f209277f4 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -713,11 +713,7 @@ namespace Jellyfin.Networking.Manager if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) { - if (index == null) - { - index = new List(); - } - + index ??= new List(); index.Add(interfcIndex); } } From 914e891689af38911332d14b18b4a1b4834cd9ae Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Feb 2021 02:05:12 +0100 Subject: [PATCH 1153/1930] Fix unchecked input --- .../Library/LibraryManager.cs | 6 +++--- .../Controllers/LibraryStructureController.cs | 2 +- .../Library/ILibraryManager.cs | 2 +- .../Entities/CollectionTypeOptions.cs | 15 +++++++++++++++ 4 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 MediaBrowser.Model/Entities/CollectionTypeOptions.cs diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index db27862ce7..03da1add85 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2956,7 +2956,7 @@ namespace Emby.Server.Implementations.Library throw new InvalidOperationException(); } - public async Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary) + public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary) { if (string.IsNullOrWhiteSpace(name)) { @@ -2990,9 +2990,9 @@ namespace Emby.Server.Implementations.Library { Directory.CreateDirectory(virtualFolderPath); - if (!string.IsNullOrEmpty(collectionType)) + if (collectionType != null) { - var path = Path.Combine(virtualFolderPath, collectionType + ".collection"); + var path = Path.Combine(virtualFolderPath, collectionType.ToString() + ".collection"); File.WriteAllBytes(path, Array.Empty()); } diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs index 94995650cb..328efea26e 100644 --- a/Jellyfin.Api/Controllers/LibraryStructureController.cs +++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs @@ -75,7 +75,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task AddVirtualFolder( [FromQuery] string? name, - [FromQuery] string? collectionType, + [FromQuery] CollectionTypeOptions? collectionType, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] paths, [FromBody] AddVirtualFolderDto? libraryOptionsDto, [FromQuery] bool refreshLibrary = false) diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 6700761fcc..80fcf71f3e 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -542,7 +542,7 @@ namespace MediaBrowser.Controller.Library Guid GetMusicGenreId(string name); - Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary); + Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary); Task RemoveVirtualFolder(string name, bool refreshLibrary); diff --git a/MediaBrowser.Model/Entities/CollectionTypeOptions.cs b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs new file mode 100644 index 0000000000..d7615a7eda --- /dev/null +++ b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs @@ -0,0 +1,15 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Model.Entities +{ + public enum CollectionTypeOptions + { + Movies, + Music, + TvShows, + Books, + HomeVideos, + MusicVideos, + Mixed + } +} From 82634a99343bf9ca4f1b711f83fb4b85f2182655 Mon Sep 17 00:00:00 2001 From: Christopher G Date: Wed, 24 Feb 2021 00:59:32 +0000 Subject: [PATCH 1154/1930] Translated using Weblate (Indonesian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/id/ --- Emby.Server.Implementations/Localization/Core/id.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/id.json b/Emby.Server.Implementations/Localization/Core/id.json index 105ef7be99..ba35138700 100644 --- a/Emby.Server.Implementations/Localization/Core/id.json +++ b/Emby.Server.Implementations/Localization/Core/id.json @@ -1,7 +1,7 @@ { "Albums": "Album", "AuthenticationSucceededWithUserName": "{0} berhasil diautentikasi", - "AppDeviceValues": "Aplikasi : {0}, Alat : {1}", + "AppDeviceValues": "Aplikasi : {0}, Perangkat : {1}", "LabelRunningTimeValue": "Waktu berjalan: {0}", "MessageApplicationUpdatedTo": "Jellyfin Server sudah diperbarui ke {0}", "MessageApplicationUpdated": "Jellyfin Server sudah diperbarui", From 1c74e2f40e6790621ebc06dd37083a29be2459bd Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Feb 2021 02:34:50 +0100 Subject: [PATCH 1155/1930] Fix build --- .../Collections/CollectionManager.cs | 2 +- .../Library/LibraryManager.cs | 17 +++++++++++++---- .../LiveTv/EmbyTV/EmbyTV.cs | 4 ++-- .../Entities/CollectionTypeOptions.cs | 15 ++++++++------- .../Entities/VirtualFolderInfo.cs | 2 +- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 3011a37e31..1ab2bdfbe8 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -107,7 +107,7 @@ namespace Emby.Server.Implementations.Collections var name = _localizationManager.GetLocalizedString("Collections"); - await _libraryManager.AddVirtualFolder(name, CollectionType.BoxSets, libraryOptions, true).ConfigureAwait(false); + await _libraryManager.AddVirtualFolder(name, CollectionTypeOptions.BoxSets, libraryOptions, true).ConfigureAwait(false); return FindFolders(path).First(); } diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 03da1add85..799f8abc34 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1240,11 +1240,20 @@ namespace Emby.Server.Implementations.Library return info; } - private string GetCollectionType(string path) + private CollectionTypeOptions GetCollectionType(string path) { - return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false) - .Select(Path.GetFileNameWithoutExtension) - .FirstOrDefault(i => !string.IsNullOrEmpty(i)); + var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false); + foreach (var file in files) + { + // TODO: @bond use a ReadOnlySpan here when Enum.TryParse supports it + // https://github.com/dotnet/runtime/issues/20008 + if (Enum.TryParse(Path.GetExtension(file), true, out var res)) + { + return res; + } + } + + throw new FileNotFoundException("Coudn't find an appropriate collection type file."); } /// diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 2c0de661df..13b5a1c552 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -2604,7 +2604,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { Locations = new string[] { customPath }, Name = "Recorded Movies", - CollectionType = CollectionType.Movies + CollectionType = CollectionTypeOptions.Movies }; } @@ -2615,7 +2615,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { Locations = new string[] { customPath }, Name = "Recorded Shows", - CollectionType = CollectionType.TvShows + CollectionType = CollectionTypeOptions.TvShows }; } } diff --git a/MediaBrowser.Model/Entities/CollectionTypeOptions.cs b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs index d7615a7eda..e1894d84ad 100644 --- a/MediaBrowser.Model/Entities/CollectionTypeOptions.cs +++ b/MediaBrowser.Model/Entities/CollectionTypeOptions.cs @@ -4,12 +4,13 @@ namespace MediaBrowser.Model.Entities { public enum CollectionTypeOptions { - Movies, - Music, - TvShows, - Books, - HomeVideos, - MusicVideos, - Mixed + Movies = 0, + TvShows = 1, + Music = 2, + MusicVideos = 3, + HomeVideos = 4, + BoxSets = 5, + Books = 6, + Mixed = 7 } } diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs index 1b0e592401..55879b2e02 100644 --- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs +++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Model.Entities /// Gets or sets the type of the collection. /// /// The type of the collection. - public string CollectionType { get; set; } + public CollectionTypeOptions CollectionType { get; set; } public LibraryOptions LibraryOptions { get; set; } From 81f527f8083289ce8eab77d522f51f06c3a5a70c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Feb 2021 11:57:04 +0100 Subject: [PATCH 1156/1930] CollectionType can be null --- Emby.Server.Implementations/Library/LibraryManager.cs | 4 ++-- MediaBrowser.Model/Entities/VirtualFolderInfo.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 799f8abc34..d9ffe64b3b 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1240,7 +1240,7 @@ namespace Emby.Server.Implementations.Library return info; } - private CollectionTypeOptions GetCollectionType(string path) + private CollectionTypeOptions? GetCollectionType(string path) { var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false); foreach (var file in files) @@ -1253,7 +1253,7 @@ namespace Emby.Server.Implementations.Library } } - throw new FileNotFoundException("Coudn't find an appropriate collection type file."); + return null; } /// diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs index 55879b2e02..ea3df37265 100644 --- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs +++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Model.Entities /// Gets or sets the type of the collection. /// /// The type of the collection. - public CollectionTypeOptions CollectionType { get; set; } + public CollectionTypeOptions? CollectionType { get; set; } public LibraryOptions LibraryOptions { get; set; } From 039a4fb22d52d840019ecdb39c62bcd7f76e3b84 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 24 Feb 2021 11:40:50 +0000 Subject: [PATCH 1157/1930] renamed method --- Jellyfin.Networking/Manager/NetworkManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 3f209277f4..1d5eb1826e 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -694,7 +694,7 @@ namespace Jellyfin.Networking.Manager /// String to check. /// Interface index numbers that match. /// true if an interface name matches the token, False otherwise. - private bool TryIsInterface(string token, [MaybeNullWhen(false)] out List index) + private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List? index) { index = null; @@ -731,7 +731,7 @@ namespace Jellyfin.Networking.Manager { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. - if (TryIsInterface(token, out var index)) + if (TryGetInterfaces(token, out var index)) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); From 1569cc301cae443c49e65cb316162cc4bd5863e5 Mon Sep 17 00:00:00 2001 From: sebastianporta Date: Wed, 24 Feb 2021 13:22:59 +0000 Subject: [PATCH 1158/1930] Translated using Weblate (Spanish (Mexico)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/es_MX/ --- Emby.Server.Implementations/Localization/Core/es-MX.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/es-MX.json b/Emby.Server.Implementations/Localization/Core/es-MX.json index 05181116da..5d7ed243f4 100644 --- a/Emby.Server.Implementations/Localization/Core/es-MX.json +++ b/Emby.Server.Implementations/Localization/Core/es-MX.json @@ -117,5 +117,6 @@ "TaskCleanActivityLogDescription": "Elimina entradas del registro de actividad que sean más antiguas al periodo establecido.", "TaskCleanActivityLog": "Limpiar registro de actividades", "Undefined": "Sin definir", - "Forced": "Forzado" + "Forced": "Forzado", + "Default": "Predeterminado" } From 2bc1eef4ddb23385f90c8bfc6af2ecf9888d7879 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Feb 2021 22:18:59 +0100 Subject: [PATCH 1159/1930] Clean up code --- Emby.Server.Implementations/ApplicationHost.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index d7ac8bc3bb..b1c20815ec 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -499,17 +499,22 @@ namespace Emby.Server.Implementations var entryPoints = GetExports(); + cancellationToken.ThrowIfCancellationRequested(); + var stopWatch = new Stopwatch(); stopWatch.Start(); - cancellationToken.ThrowIfCancellationRequested(); - await Task.WhenAny(Task.WhenAll(StartEntryPoints(entryPoints, true)), Task.Delay(-1, cancellationToken)).ConfigureAwait(false); + + await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false); Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed); Logger.LogInformation("Core startup complete"); CoreStartupHasCompleted = true; - stopWatch.Restart(); + cancellationToken.ThrowIfCancellationRequested(); - await Task.WhenAny(Task.WhenAll(StartEntryPoints(entryPoints, false)), Task.Delay(-1, cancellationToken)).ConfigureAwait(false); + + stopWatch.Restart(); + + await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false); Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed); stopWatch.Stop(); } From bae97322a073fcb507fd5918385c0c6157b7ea54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Est=C3=A9vez?= Date: Wed, 24 Feb 2021 17:57:16 +0000 Subject: [PATCH 1160/1930] Translated using Weblate (Galician) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/gl/ --- .../Localization/Core/gl.json | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/gl.json b/Emby.Server.Implementations/Localization/Core/gl.json index faee2519a1..12bcd793e3 100644 --- a/Emby.Server.Implementations/Localization/Core/gl.json +++ b/Emby.Server.Implementations/Localization/Core/gl.json @@ -7,5 +7,55 @@ "Books": "Libros", "AuthenticationSucceededWithUserName": "{0} autenticouse correctamente", "Artists": "Artistas", - "Application": "Aplicativo" + "Application": "Aplicativo", + "NotificationOptionServerRestartRequired": "Necesario un reinicio do servidor", + "NotificationOptionPluginUpdateInstalled": "Actualización do Plugin instalada", + "NotificationOptionPluginUninstalled": "Plugin desinstalado", + "NotificationOptionPluginInstalled": "Plugin instalado", + "NotificationOptionPluginError": "Fallo do Plugin", + "NotificationOptionNewLibraryContent": "Novo contido engadido", + "NotificationOptionInstallationFailed": "Fallo na instalación", + "NotificationOptionCameraImageUploaded": "Imaxe da cámara subida", + "NotificationOptionAudioPlaybackStopped": "Reproducción de audio parada", + "NotificationOptionAudioPlayback": "Reproducción de audio comezada", + "NotificationOptionApplicationUpdateInstalled": "Actualización da aplicación instalada", + "NotificationOptionApplicationUpdateAvailable": "Actualización da aplicación dispoñible", + "NewVersionIsAvailable": "Unha nova versión do Servidor Jellyfin está dispoñible para descarga.", + "NameSeasonUnknown": "Tempada descoñecida", + "NameSeasonNumber": "Tempada {0}", + "NameInstallFailed": "{0} instalación fallida", + "MusicVideos": "Vídeos Musicais", + "Music": "Música", + "Movies": "Películas", + "MixedContent": "Contido Mixto", + "MessageServerConfigurationUpdated": "A configuración do servidor foi actualizada", + "MessageNamedServerConfigurationUpdatedWithValue": "A sección de configuración {0} do servidor foi actualizada", + "MessageApplicationUpdatedTo": "O servidor Jellyfin foi actualizado a {0}", + "MessageApplicationUpdated": "O servidor Jellyfin foi actualizado", + "Latest": "Último", + "LabelRunningTimeValue": "Tempo de execución: {0}", + "LabelIpAddressValue": "Enderezo IP: {0}", + "ItemRemovedWithName": "{0} foi eliminado da biblioteca", + "ItemAddedWithName": "{0} foi engadido a biblioteca", + "Inherit": "Herdar", + "HomeVideos": "Videos caseiros", + "HeaderRecordingGroups": "Grupos de Grabación", + "HeaderNextUp": "De seguido", + "HeaderLiveTV": "TV en directo", + "HeaderFavoriteSongs": "Cancións Favoritas", + "HeaderFavoriteShows": "Series de TV Favoritas", + "HeaderFavoriteEpisodes": "Episodios Favoritos", + "HeaderFavoriteArtists": "Artistas Favoritos", + "HeaderFavoriteAlbums": "Álbunes Favoritos", + "HeaderContinueWatching": "Seguir mirando", + "HeaderAlbumArtists": "Artistas de Album", + "Genres": "Xéneros", + "Forced": "Forzado", + "Folders": "Cartafoles", + "Favorites": "Favoritos", + "FailedLoginAttemptWithUserName": "Intento de incio de sesión fallido {0}", + "DeviceOnlineWithName": "{0} conectouse", + "DeviceOfflineWithName": "{0} desconectouse", + "Default": "Por defecto", + "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}" } From 03cc6b1d782067e58975dbea4b61e42a3c04e1aa Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 25 Feb 2021 19:02:27 -0500 Subject: [PATCH 1161/1930] Make styling more consistent --- Jellyfin.Server.Implementations/Users/UserManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 38a074e988..25d7524c74 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -407,12 +407,12 @@ namespace Jellyfin.Server.Implementations.Users var authenticationProvider = authResult.authenticationProvider; var success = authResult.success; - if (user is null) + if (user == null) { string updatedUsername = authResult.username; if (success - && authenticationProvider is not null + && authenticationProvider != null && authenticationProvider is not DefaultAuthenticationProvider) { // Trust the username returned by the authentication provider From 9413d974f3f234dd3fc2225d318d7fced7257912 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 25 Feb 2021 20:38:18 -0500 Subject: [PATCH 1162/1930] Switch to using declarations in MediaBrowser.Providers --- .../Plugins/MusicBrainz/ArtistProvider.cs | 82 ++++----- .../MusicBrainz/MusicBrainzAlbumProvider.cs | 174 ++++++++---------- .../Studios/StudiosImageProvider.cs | 26 ++- .../Subtitles/SubtitleManager.cs | 50 +++-- 4 files changed, 149 insertions(+), 183 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs index ce93924026..2eab95294a 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/ArtistProvider.cs @@ -69,58 +69,52 @@ namespace MediaBrowser.Providers.Music private IEnumerable GetResultsFromResponse(Stream stream) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using var oReader = new StreamReader(stream, Encoding.UTF8); + var settings = new XmlReaderSettings() { - var settings = new XmlReaderSettings() - { - ValidationType = ValidationType.None, - CheckCharacters = false, - IgnoreProcessingInstructions = true, - IgnoreComments = true - }; + ValidationType = ValidationType.None, + CheckCharacters = false, + IgnoreProcessingInstructions = true, + IgnoreComments = true + }; - using (var reader = XmlReader.Create(oReader, settings)) - { - reader.MoveToContent(); - reader.Read(); + using var reader = XmlReader.Create(oReader, settings); + reader.MoveToContent(); + reader.Read(); - // Loop through each element - while (!reader.EOF && reader.ReadState == ReadState.Interactive) + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) + { + if (reader.NodeType == XmlNodeType.Element) + { + switch (reader.Name) { - if (reader.NodeType == XmlNodeType.Element) + case "artist-list": { - switch (reader.Name) + if (reader.IsEmptyElement) { - case "artist-list": - { - if (reader.IsEmptyElement) - { - reader.Read(); - continue; - } - - using (var subReader = reader.ReadSubtree()) - { - return ParseArtistList(subReader).ToList(); - } - } - - default: - { - reader.Skip(); - break; - } + reader.Read(); + continue; } + + using var subReader = reader.ReadSubtree(); + return ParseArtistList(subReader).ToList(); } - else + + default: { - reader.Read(); + reader.Skip(); + break; } } - - return Enumerable.Empty(); + } + else + { + reader.Read(); } } + + return Enumerable.Empty(); } private IEnumerable ParseArtistList(XmlReader reader) @@ -145,13 +139,11 @@ namespace MediaBrowser.Providers.Music var mbzId = reader.GetAttribute("id"); - using (var subReader = reader.ReadSubtree()) + using var subReader = reader.ReadSubtree(); + var artist = ParseArtist(subReader, mbzId); + if (artist != null) { - var artist = ParseArtist(subReader, mbzId); - if (artist != null) - { - yield return artist; - } + yield return artist; } break; diff --git a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs index e5ad0f3e09..0023d59594 100644 --- a/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/MusicBrainz/MusicBrainzAlbumProvider.cs @@ -128,53 +128,49 @@ namespace MediaBrowser.Providers.Music private IEnumerable GetResultsFromResponse(Stream stream) { - using (var oReader = new StreamReader(stream, Encoding.UTF8)) + using var oReader = new StreamReader(stream, Encoding.UTF8); + var settings = new XmlReaderSettings() { - var settings = new XmlReaderSettings() + ValidationType = ValidationType.None, + CheckCharacters = false, + IgnoreProcessingInstructions = true, + IgnoreComments = true + }; + + using var reader = XmlReader.Create(oReader, settings); + var results = ReleaseResult.Parse(reader); + + return results.Select(i => + { + var result = new RemoteSearchResult { - ValidationType = ValidationType.None, - CheckCharacters = false, - IgnoreProcessingInstructions = true, - IgnoreComments = true + Name = i.Title, + ProductionYear = i.Year }; - using (var reader = XmlReader.Create(oReader, settings)) + if (i.Artists.Count > 0) { - var results = ReleaseResult.Parse(reader); - - return results.Select(i => + result.AlbumArtist = new RemoteSearchResult { - var result = new RemoteSearchResult - { - Name = i.Title, - ProductionYear = i.Year - }; + SearchProviderName = Name, + Name = i.Artists[0].Item1 + }; - if (i.Artists.Count > 0) - { - result.AlbumArtist = new RemoteSearchResult - { - SearchProviderName = Name, - Name = i.Artists[0].Item1 - }; - - result.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, i.Artists[0].Item2); - } - - if (!string.IsNullOrWhiteSpace(i.ReleaseId)) - { - result.SetProviderId(MetadataProvider.MusicBrainzAlbum, i.ReleaseId); - } - - if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId)) - { - result.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, i.ReleaseGroupId); - } - - return result; - }); + result.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, i.Artists[0].Item2); } - } + + if (!string.IsNullOrWhiteSpace(i.ReleaseId)) + { + result.SetProviderId(MetadataProvider.MusicBrainzAlbum, i.ReleaseId); + } + + if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId)) + { + result.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, i.ReleaseGroupId); + } + + return result; + }); } /// @@ -339,10 +335,8 @@ namespace MediaBrowser.Providers.Music continue; } - using (var subReader = reader.ReadSubtree()) - { - return ParseReleaseList(subReader).ToList(); - } + using var subReader = reader.ReadSubtree(); + return ParseReleaseList(subReader).ToList(); } default: @@ -383,13 +377,11 @@ namespace MediaBrowser.Providers.Music var releaseId = reader.GetAttribute("id"); - using (var subReader = reader.ReadSubtree()) + using var subReader = reader.ReadSubtree(); + var release = ParseRelease(subReader, releaseId); + if (release != null) { - var release = ParseRelease(subReader, releaseId); - if (release != null) - { - yield return release; - } + yield return release; } break; @@ -460,14 +452,12 @@ namespace MediaBrowser.Providers.Music case "artist-credit": { - using (var subReader = reader.ReadSubtree()) - { - var artist = ParseArtistCredit(subReader); + using var subReader = reader.ReadSubtree(); + var artist = ParseArtistCredit(subReader); - if (!string.IsNullOrEmpty(artist.Item1)) - { - result.Artists.Add(artist); - } + if (!string.IsNullOrEmpty(artist.Item1)) + { + result.Artists.Add(artist); } break; @@ -505,12 +495,10 @@ namespace MediaBrowser.Providers.Music switch (reader.Name) { case "name-credit": - { - using (var subReader = reader.ReadSubtree()) - { - return ParseArtistNameCredit(subReader); - } - } + { + using var subReader = reader.ReadSubtree(); + return ParseArtistNameCredit(subReader); + } default: { @@ -545,10 +533,8 @@ namespace MediaBrowser.Providers.Music case "artist": { var id = reader.GetAttribute("id"); - using (var subReader = reader.ReadSubtree()) - { - return ParseArtistArtistCredit(subReader, id); - } + using var subReader = reader.ReadSubtree(); + return ParseArtistArtistCredit(subReader, id); } default: @@ -647,47 +633,43 @@ namespace MediaBrowser.Providers.Music IgnoreComments = true }; - using (var reader = XmlReader.Create(oReader, settings)) + using var reader = XmlReader.Create(oReader, settings); + reader.MoveToContent(); + reader.Read(); + + // Loop through each element + while (!reader.EOF && reader.ReadState == ReadState.Interactive) { - reader.MoveToContent(); - reader.Read(); - - // Loop through each element - while (!reader.EOF && reader.ReadState == ReadState.Interactive) + if (reader.NodeType == XmlNodeType.Element) { - if (reader.NodeType == XmlNodeType.Element) + switch (reader.Name) { - switch (reader.Name) + case "release-group-list": { - case "release-group-list": + if (reader.IsEmptyElement) { - if (reader.IsEmptyElement) - { - reader.Read(); - continue; - } - - using (var subReader = reader.ReadSubtree()) - { - return GetFirstReleaseGroupId(subReader); - } + reader.Read(); + continue; } - default: - { - reader.Skip(); - break; - } + using var subReader = reader.ReadSubtree(); + return GetFirstReleaseGroupId(subReader); + } + + default: + { + reader.Skip(); + break; } } - else - { - reader.Read(); - } } - - return null; + else + { + reader.Read(); + } } + + return null; } private string GetFirstReleaseGroupId(XmlReader reader) diff --git a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs index 5fcf6d9aa1..9268ed7146 100644 --- a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs +++ b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs @@ -171,25 +171,21 @@ namespace MediaBrowser.Providers.Studios public IEnumerable GetAvailableImages(string file) { - using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) + using var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using var reader = new StreamReader(fileStream); + var lines = new List(); + + while (!reader.EndOfStream) { - using (var reader = new StreamReader(fileStream)) + var text = reader.ReadLine(); + + if (!string.IsNullOrWhiteSpace(text)) { - var lines = new List(); - - while (!reader.EndOfStream) - { - var text = reader.ReadLine(); - - if (!string.IsNullOrWhiteSpace(text)) - { - lines.Add(text); - } - } - - return lines; + lines.Add(text); } } + + return lines; } } } diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 47e9d5ee8c..adee8d6bc2 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -187,31 +187,29 @@ namespace MediaBrowser.Providers.Subtitles { var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia; - using (var stream = response.Stream) - using (var memoryStream = new MemoryStream()) + using var stream = response.Stream; + using var memoryStream = new MemoryStream(); + await stream.CopyToAsync(memoryStream).ConfigureAwait(false); + memoryStream.Position = 0; + + var savePaths = new List(); + var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant(); + + if (response.IsForced) { - await stream.CopyToAsync(memoryStream).ConfigureAwait(false); - memoryStream.Position = 0; - - var savePaths = new List(); - var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant(); - - if (response.IsForced) - { - saveFileName += ".forced"; - } - - saveFileName += "." + response.Format.ToLowerInvariant(); - - if (saveInMediaFolder) - { - savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName)); - } - - savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); - - await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); + saveFileName += ".forced"; } + + saveFileName += "." + response.Format.ToLowerInvariant(); + + if (saveInMediaFolder) + { + savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName)); + } + + savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); + + await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); } private async Task TrySaveToFiles(Stream stream, List savePaths) @@ -228,10 +226,8 @@ namespace MediaBrowser.Providers.Subtitles { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); - using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, FileStreamBufferSize, true)) - { - await stream.CopyToAsync(fs).ConfigureAwait(false); - } + using var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, FileStreamBufferSize, true); + await stream.CopyToAsync(fs).ConfigureAwait(false); return; } From 0a1b91f084ec9eb7db5a341b9699c41c340d644a Mon Sep 17 00:00:00 2001 From: Eben van Deventer Date: Fri, 26 Feb 2021 15:53:55 +0000 Subject: [PATCH 1163/1930] Translated using Weblate (Afrikaans) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/af/ --- Emby.Server.Implementations/Localization/Core/af.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/af.json b/Emby.Server.Implementations/Localization/Core/af.json index 977a1c2d70..b029b7042b 100644 --- a/Emby.Server.Implementations/Localization/Core/af.json +++ b/Emby.Server.Implementations/Localization/Core/af.json @@ -112,5 +112,8 @@ "TaskRefreshLibraryDescription": "Skandeer u media versameling vir nuwe lêers en verfris metadata.", "TaskRefreshLibrary": "Skandeer Media Versameling", "TaskRefreshChapterImagesDescription": "Maak kleinkiekeis (fotos) vir films wat hoofstukke het.", - "TaskRefreshChapterImages": "Verkry Hoofstuk Beelde" + "TaskRefreshChapterImages": "Verkry Hoofstuk Beelde", + "Undefined": "Ongedefineerd", + "Forced": "Geforseer", + "Default": "Oorspronklik" } From a25e3c02568b5632278e23d6168efa927b29eda9 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 13:56:21 +0000 Subject: [PATCH 1164/1930] fix for override ports contained in PublishedServerUrl --- Emby.Dlna/Main/DlnaEntryPoint.cs | 9 ++++++--- Emby.Server.Implementations/ApplicationHost.cs | 10 ++++++++++ MediaBrowser.Controller/IServerApplicationHost.cs | 5 +++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 82490ec310..2652e62457 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -313,9 +313,12 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); - // DLNA will only work over http, so we must reset to http:// : {port} - uri.Scheme = "http://"; - uri.Port = _netConfig.HttpServerPortNumber; + if (string.IsNullOrEmpty(_appHost.PublishedServerUrl)) + { + // DLNA will only work over http, so we must reset to http:// : {port}. + uri.Scheme = "http"; + uri.Port = _netConfig.HttpServerPortNumber; + } var device = new SsdpRootDevice { diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1b9bb86bbd..604f699862 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -135,6 +135,11 @@ namespace Emby.Server.Implementations public bool CoreStartupHasCompleted { get; private set; } + /// + /// Gets a value indicating whether this instance has a custom published url. + /// + public Uri PublishedServerUrl => _startupOptions.PublishedServerUrl; + public virtual bool CanLaunchWebBrowser { get @@ -1141,6 +1146,11 @@ namespace Emby.Server.Implementations /// public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps; + public string GetStartupOption(string propName) + { + return _startupOptions.GetType().GetProperty(propName).GetValue(src, null); + } + /// public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) { diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 92b2d43ce2..b6f049391f 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -52,6 +52,11 @@ namespace MediaBrowser.Controller /// The name of the friendly. string FriendlyName { get; } + /// + /// Gets a value indicating whether this instance has a custom published url. + /// + Uri PublishedServerUrl { get; } + /// /// Gets the system info. /// From d95ca20fc731cf51e060c7ba6802821b6dd8c48f Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 14:05:13 +0000 Subject: [PATCH 1165/1930] removed bad merge code --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- Emby.Server.Implementations/ApplicationHost.cs | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 2652e62457..797045857f 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -313,7 +313,7 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); - if (string.IsNullOrEmpty(_appHost.PublishedServerUrl)) + if (_appHost.PublishedServerUrl == null) { // DLNA will only work over http, so we must reset to http:// : {port}. uri.Scheme = "http"; diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 604f699862..56aa5a007f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1146,11 +1146,6 @@ namespace Emby.Server.Implementations /// public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps; - public string GetStartupOption(string propName) - { - return _startupOptions.GetType().GetProperty(propName).GetValue(src, null); - } - /// public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) { From ebb6467db46f650d39fe9b2de266afcd561aa351 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 27 Feb 2021 11:42:37 -0500 Subject: [PATCH 1166/1930] Remove unused entity --- .../Configuration/AccessSchedule.cs | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 MediaBrowser.Model/Configuration/AccessSchedule.cs diff --git a/MediaBrowser.Model/Configuration/AccessSchedule.cs b/MediaBrowser.Model/Configuration/AccessSchedule.cs deleted file mode 100644 index 7bd355449f..0000000000 --- a/MediaBrowser.Model/Configuration/AccessSchedule.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Jellyfin.Data.Enums; - -#pragma warning disable CS1591 - -namespace MediaBrowser.Model.Configuration -{ - public class AccessSchedule - { - /// - /// Gets or sets the day of week. - /// - /// The day of week. - public DynamicDayOfWeek DayOfWeek { get; set; } - - /// - /// Gets or sets the start hour. - /// - /// The start hour. - public double StartHour { get; set; } - - /// - /// Gets or sets the end hour. - /// - /// The end hour. - public double EndHour { get; set; } - } -} From 9f03064ad890395aedb7617d0c65a4a4197a1198 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 17:34:44 +0000 Subject: [PATCH 1167/1930] Update MediaBrowser.Controller/IServerApplicationHost.cs Co-authored-by: Cody Robibero --- MediaBrowser.Controller/IServerApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index b6f049391f..6378625e87 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -53,7 +53,7 @@ namespace MediaBrowser.Controller string FriendlyName { get; } /// - /// Gets a value indicating whether this instance has a custom published url. + /// Gets the configured published server url. /// Uri PublishedServerUrl { get; } From 73ca367bf9419b47e6be9487971bce90aec6b82d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 17:34:48 +0000 Subject: [PATCH 1168/1930] Update Emby.Server.Implementations/ApplicationHost.cs Co-authored-by: Cody Robibero --- Emby.Server.Implementations/ApplicationHost.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 56aa5a007f..cddd600791 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -135,9 +135,7 @@ namespace Emby.Server.Implementations public bool CoreStartupHasCompleted { get; private set; } - /// - /// Gets a value indicating whether this instance has a custom published url. - /// + /// public Uri PublishedServerUrl => _startupOptions.PublishedServerUrl; public virtual bool CanLaunchWebBrowser From d99d95422ed52bd3a7dbf9f7bd947feb809a2616 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 19:10:53 +0000 Subject: [PATCH 1169/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 1d5eb1826e..05796d6a38 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -731,7 +731,7 @@ namespace Jellyfin.Networking.Manager { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. - if (TryGetInterfaces(token, out var index)) + if (TryGetInterfaces(token, out var indices)) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); From cc19d281e7363748af0b42a063859df169bf71e3 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 19:10:58 +0000 Subject: [PATCH 1170/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 05796d6a38..51fcb6d9a0 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -738,7 +738,7 @@ namespace Jellyfin.Networking.Manager // Replace all the interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (index.Contains(Math.Abs(iface.Tag)) + if (indices.Contains(Math.Abs(iface.Tag)) && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { From 5074d67379bdb90ce43fa066222fbb7b87d8bf48 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 21:17:58 +0000 Subject: [PATCH 1171/1930] performance --- MediaBrowser.Common/Net/IPHost.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 84aebb6e78..4a7c701907 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -178,8 +178,9 @@ namespace MediaBrowser.Common.Net // Use regular expression as CheckHostName isn't RFC5892 compliant. // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation - Regex re = new Regex(@"^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$", RegexOptions.IgnoreCase | RegexOptions.Multiline); - if (re.Match(host).Success) + string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$"; + + if (Regex.IsMatch(host, pattern)) { hostObj = new IPHost(host); return true; From 02848189e3e2824fac6ee155f3efa52084279b18 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 28 Feb 2021 00:10:36 +0100 Subject: [PATCH 1172/1930] MaybeNullWhen(false) -> NotNullWhen(true) --- MediaBrowser.Model/Entities/ProviderIdsExtensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 4aff6e3a4f..11c3dbe42e 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Model.Entities /// The name. /// The provider id. /// true if a provider id with the given name was found; otherwise false. - public static bool TryGetProviderId(this IHasProviderIds instance, string name, [MaybeNullWhen(false)] out string id) + public static bool TryGetProviderId(this IHasProviderIds instance, string name, [NotNullWhen(true)] out string? id) { if (instance == null) { @@ -39,7 +39,7 @@ namespace MediaBrowser.Model.Entities /// The provider. /// The provider id. /// true if a provider id with the given name was found; otherwise false. - public static bool TryGetProviderId(this IHasProviderIds instance, MetadataProvider provider, [MaybeNullWhen(false)] out string id) + public static bool TryGetProviderId(this IHasProviderIds instance, MetadataProvider provider, [NotNullWhen(true)] out string? id) { return instance.TryGetProviderId(provider.ToString(), out id); } From f666b7e10268a5c19228d8fdb1bd313a642b0915 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Feb 2021 20:12:55 +0000 Subject: [PATCH 1173/1930] fix --- .../ApplicationHost.cs | 22 ++++++++++++++----- .../IStartupOptions.cs | 12 +++++----- Jellyfin.Server/CoreAppHost.cs | 4 ++++ Jellyfin.Server/Program.cs | 1 + Jellyfin.Server/StartupOptions.cs | 4 ++-- .../JellyfinApplicationFactory.cs | 2 ++ 6 files changed, 31 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1b9bb86bbd..785a3e89c4 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -99,6 +99,7 @@ using MediaBrowser.Providers.Subtitles; using MediaBrowser.XbmcMetadata.Providers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Prometheus.DotNetRuntime; @@ -118,6 +119,7 @@ namespace Emby.Server.Implementations private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" }; private readonly IFileSystem _fileSystemManager; + private readonly IConfiguration _startupConfig; private readonly IXmlSerializer _xmlSerializer; private readonly IStartupOptions _startupOptions; private readonly IPluginManager _pluginManager; @@ -228,6 +230,11 @@ namespace Emby.Server.Implementations /// public int HttpsPort { get; private set; } + /// + /// Gets the PublishedServerUrl setting. + /// + public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig["PublishedServerUrl"]; + /// /// Gets the server configuration manager. /// @@ -240,12 +247,14 @@ namespace Emby.Server.Implementations /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// The interface. /// Instance of the interface. /// Instance of the interface. public ApplicationHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, + IConfiguration startupConfig, IFileSystem fileSystem, IServiceCollection serviceCollection) { @@ -268,6 +277,7 @@ namespace Emby.Server.Implementations Logger = LoggerFactory.CreateLogger(); _startupOptions = options; + _startupConfig = startupConfig; // Initialize runtime stat collection if (ServerConfigurationManager.Configuration.EnableMetrics) @@ -1145,10 +1155,10 @@ namespace Emby.Server.Implementations public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) { // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + if (!string.IsNullOrEmpty(PublishedServerUrl)) { // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + return PublishedServerUrl.Trim('/'); } string smart = NetManager.GetBindInterface(ipAddress, out port); @@ -1165,10 +1175,10 @@ namespace Emby.Server.Implementations public string GetSmartApiUrl(HttpRequest request, int? port = null) { // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + if (!string.IsNullOrEmpty(PublishedServerUrl)) { // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + return PublishedServerUrl.Trim('/'); } string smart = NetManager.GetBindInterface(request, out port); @@ -1185,10 +1195,10 @@ namespace Emby.Server.Implementations public string GetSmartApiUrl(string hostname, int? port = null) { // Published server ends with a / - if (_startupOptions.PublishedServerUrl != null) + if (!string.IsNullOrEmpty(PublishedServerUrl)) { // Published server ends with a '/', so we need to remove it. - return _startupOptions.PublishedServerUrl.ToString().Trim('/'); + return PublishedServerUrl.Trim('/'); } string smart = NetManager.GetBindInterface(hostname, out port); diff --git a/Emby.Server.Implementations/IStartupOptions.cs b/Emby.Server.Implementations/IStartupOptions.cs index 4bef59543f..0b823ff063 100644 --- a/Emby.Server.Implementations/IStartupOptions.cs +++ b/Emby.Server.Implementations/IStartupOptions.cs @@ -1,5 +1,5 @@ #pragma warning disable CS1591 - +#nullable enable using System; namespace Emby.Server.Implementations @@ -9,7 +9,7 @@ namespace Emby.Server.Implementations /// /// Gets the value of the --ffmpeg command line option. /// - string FFmpegPath { get; } + string? FFmpegPath { get; } /// /// Gets the value of the --service command line option. @@ -19,21 +19,21 @@ namespace Emby.Server.Implementations /// /// Gets the value of the --package-name command line option. /// - string PackageName { get; } + string? PackageName { get; } /// /// Gets the value of the --restartpath command line option. /// - string RestartPath { get; } + string? RestartPath { get; } /// /// Gets the value of the --restartargs command line option. /// - string RestartArgs { get; } + string? RestartArgs { get; } /// /// Gets the value of the --published-server-url command line option. /// - Uri PublishedServerUrl { get; } + string? PublishedServerUrl { get; } } } diff --git a/Jellyfin.Server/CoreAppHost.cs b/Jellyfin.Server/CoreAppHost.cs index b76aa5e141..1daa32deea 100644 --- a/Jellyfin.Server/CoreAppHost.cs +++ b/Jellyfin.Server/CoreAppHost.cs @@ -21,6 +21,7 @@ using MediaBrowser.Controller.Net; using MediaBrowser.Model.Activity; using MediaBrowser.Model.IO; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -37,18 +38,21 @@ namespace Jellyfin.Server /// The to be used by the . /// The to be used by the . /// The to be used by the . + /// The to be used by the . /// The to be used by the . /// The to be used by the . public CoreAppHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, + IConfiguration startupConfig, IFileSystem fileSystem, IServiceCollection collection) : base( applicationPaths, loggerFactory, options, + startupConfig, fileSystem, collection) { diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index f05cdfe9bd..18aa91ee13 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -164,6 +164,7 @@ namespace Jellyfin.Server appPaths, _loggerFactory, options, + startupConfig, new ManagedFileSystem(_loggerFactory.CreateLogger(), appPaths), serviceCollection); diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs index b634340927..6d8210527c 100644 --- a/Jellyfin.Server/StartupOptions.cs +++ b/Jellyfin.Server/StartupOptions.cs @@ -77,7 +77,7 @@ namespace Jellyfin.Server /// [Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")] - public Uri? PublishedServerUrl { get; set; } + public string? PublishedServerUrl { get; set; } /// /// Gets the command line options as a dictionary that can be used in the .NET configuration system. @@ -94,7 +94,7 @@ namespace Jellyfin.Server if (PublishedServerUrl != null) { - config.Add(UdpServer.AddressOverrideConfigKey, PublishedServerUrl.ToString()); + config.Add(UdpServer.AddressOverrideConfigKey, PublishedServerUrl); } if (FFmpegPath != null) diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs index 54f8eb225f..262e8f9120 100644 --- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs @@ -8,6 +8,7 @@ using MediaBrowser.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; @@ -77,6 +78,7 @@ namespace Jellyfin.Api.Tests appPaths, loggerFactory, commandLineOpts, + new ConfigurationBuilder().Build(), new ManagedFileSystem(loggerFactory.CreateLogger(), appPaths), serviceCollection); _disposableComponents.Add(appHost); From 1d6f489f17919e557987b2616048dc8def790f43 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 28 Feb 2021 10:11:37 +0000 Subject: [PATCH 1174/1930] comment change --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 785a3e89c4..7740b4fc5b 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -231,7 +231,7 @@ namespace Emby.Server.Implementations public int HttpsPort { get; private set; } /// - /// Gets the PublishedServerUrl setting. + /// Gets the value of the PublishedServerUrl setting. /// public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig["PublishedServerUrl"]; From 159ecb882f419e485a95e727b647f0e2cf6eeb3d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 28 Feb 2021 10:14:05 +0000 Subject: [PATCH 1175/1930] Fixed bad sync --- Emby.Server.Implementations/ApplicationHost.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 6880b18423..37047a4f72 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -137,9 +137,6 @@ namespace Emby.Server.Implementations public bool CoreStartupHasCompleted { get; private set; } - /// - public Uri PublishedServerUrl => _startupOptions.PublishedServerUrl; - public virtual bool CanLaunchWebBrowser { get From caa8e7cdf37a426b983792077542ef0bb50721a7 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 28 Feb 2021 10:16:28 +0000 Subject: [PATCH 1176/1930] fixed build --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- MediaBrowser.Controller/IServerApplicationHost.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index ec87160293..9a2d524d16 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -316,7 +316,7 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); var uri = new UriBuilder(_appHost.GetSmartApiUrl(address.Address) + descriptorUri); - if (_appHost.PublishedServerUrl == null) + if (!string.IsNullOrEmpty(_appHost.PublishedServerUrl)) { // DLNA will only work over http, so we must reset to http:// : {port}. uri.Scheme = "http"; diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 6378625e87..20bfa697e5 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Controller /// /// Gets the configured published server url. /// - Uri PublishedServerUrl { get; } + string PublishedServerUrl { get; } /// /// Gets the system info. From 8836242559710cbe4577451c65f91133c3da4a79 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 28 Feb 2021 10:25:14 +0000 Subject: [PATCH 1177/1930] fixed tests --- tests/Jellyfin.Api.Tests/TestAppHost.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Jellyfin.Api.Tests/TestAppHost.cs b/tests/Jellyfin.Api.Tests/TestAppHost.cs index 772e98d049..eb4c9b3055 100644 --- a/tests/Jellyfin.Api.Tests/TestAppHost.cs +++ b/tests/Jellyfin.Api.Tests/TestAppHost.cs @@ -4,6 +4,7 @@ using Emby.Server.Implementations; using Jellyfin.Server; using MediaBrowser.Controller; using MediaBrowser.Model.IO; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -20,18 +21,21 @@ namespace Jellyfin.Api.Tests /// The to be used by the . /// The to be used by the . /// The to be used by the . + /// The to be used by the . /// The to be used by the . /// The to be used by the . public TestAppHost( IServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory, IStartupOptions options, + IConfiguration startup, IFileSystem fileSystem, IServiceCollection collection) : base( applicationPaths, loggerFactory, options, + startup, fileSystem, collection) { From 16694b0cfcc51ba009a0aedce0d383ab010e8b99 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 27 Feb 2021 22:46:03 +0100 Subject: [PATCH 1178/1930] Add nfo thumb tag support --- .../ApplicationHost.cs | 2 + .../Providers/MetadataResult.cs | 12 ++- .../Manager/MetadataService.cs | 6 ++ .../Parsers/BaseNfoParser.cs | 78 ++++++++++++++++++- .../Parsers/EpisodeNfoParser.cs | 6 +- .../Parsers/MovieNfoParser.cs | 6 +- .../Parsers/SeasonNfoParser.cs | 6 +- .../Parsers/SeriesNfoParser.cs | 6 +- .../Providers/AlbumNfoProvider.cs | 8 +- .../Providers/ArtistNfoProvider.cs | 8 +- .../Providers/BaseVideoNfoProvider.cs | 9 ++- .../Providers/EpisodeNfoProvider.cs | 8 +- .../Providers/MovieNfoProvider.cs | 6 +- .../Providers/MusicVideoNfoProvider.cs | 6 +- .../Providers/SeasonNfoProvider.cs | 8 +- .../Providers/SeriesNfoProvider.cs | 8 +- .../Providers/VideoNfoProvider.cs | 6 +- .../Parsers/EpisodeNfoProviderTests.cs | 9 ++- .../Parsers/MovieNfoParserTests.cs | 64 ++++++++++++++- .../Parsers/MusicAlbumNfoProviderTests.cs | 11 ++- .../Parsers/MusicArtistNfoParserTests.cs | 9 ++- .../Parsers/MusicVideoNfoParserTests.cs | 9 ++- .../Parsers/SeasonNfoProviderTests.cs | 9 ++- .../Parsers/SeriesNfoParserTests.cs | 3 +- .../Test Data/Justice League.nfo | 2 + 25 files changed, 265 insertions(+), 40 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1b9bb86bbd..788e08e48b 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -682,6 +682,8 @@ namespace Emby.Server.Implementations ServiceCollection.AddScoped(); ServiceCollection.AddScoped(); ServiceCollection.AddScoped(); + + ServiceCollection.AddSingleton(); } /// diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs index 1c695cafa0..864cb30506 100644 --- a/MediaBrowser.Controller/Providers/MetadataResult.cs +++ b/MediaBrowser.Controller/Providers/MetadataResult.cs @@ -4,21 +4,25 @@ using System; using System.Collections.Generic; using System.Globalization; using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Entities; namespace MediaBrowser.Controller.Providers { public class MetadataResult { - public List Images { get; set; } - - public List UserDataList { get; set; } - public MetadataResult() { Images = new List(); + RemoteImages = new List<(string url, ImageType type)>(); ResultLanguage = "en"; } + public List Images { get; set; } + + public List<(string url, ImageType type)> RemoteImages { get; set; } + + public List UserDataList { get; set; } + public List People { get; set; } public bool HasMetadata { get; set; } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 8b3ca17ca1..494e479a57 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -706,6 +706,12 @@ namespace MediaBrowser.Providers.Manager if (localItem.HasMetadata) { + foreach (var remoteImage in localItem.RemoteImages) + { + await ProviderManager.SaveImage(item, remoteImage.url, remoteImage.type, null, cancellationToken).ConfigureAwait(false); + refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.ImageUpdate; + } + if (imageService.MergeImages(item, localItem.Images)) { refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.ImageUpdate; diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 6f164caf37..aa89936d0c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -27,6 +27,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers private readonly IConfigurationManager _config; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; private Dictionary _validProviderIds; /// @@ -37,12 +38,14 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public BaseNfoParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) { Logger = logger; _config = config; @@ -50,6 +53,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers _validProviderIds = new Dictionary(); _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } protected CultureInfo UsCulture { get; } = new CultureInfo("en-US"); @@ -785,6 +789,78 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } + case "thumb": + { + var artType = reader.GetAttribute("aspect"); + var val = reader.ReadElementContentAsString(); + + // skip: + // - empty aspect tag + // - empty uri + // - tag containing '.' because we can't set images for seasons, episodes or movie sets within series or movies + if (string.IsNullOrEmpty(artType) || string.IsNullOrEmpty(val) || artType.Contains('.', StringComparison.Ordinal)) + { + break; + } + + ImageType imageType = artType switch + { + "banner" => ImageType.Banner, + "clearlogo" => ImageType.Logo, + "discart" => ImageType.Disc, + "landscape" => ImageType.Thumb, + "clearart" => ImageType.Art, + // unknown type (including "poster") --> primary + _ => ImageType.Primary, + }; + + Uri uri; + try + { + uri = new Uri(val); + } + catch (UriFormatException ex) + { + Logger.LogError(ex, "Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file path.", val, item.Name); + break; + } + + if (uri.IsFile) + { + // only allow one item of each type + if (itemResult.Images.Any(x => x.Type == imageType)) + { + break; + } + + var fileSystemMetadata = _directoryService.GetFile(val); + // non existing file returns null + if (fileSystemMetadata == null || !fileSystemMetadata.Exists) + { + Logger.LogWarning("Artwork file {Path} specified in nfo file for {ItemName} does not exist.", uri, item.Name); + break; + } + + itemResult.Images.Add(new LocalImageInfo() + { + FileInfo = fileSystemMetadata, + Type = imageType + }); + } + else + { + // only allow one item of each type + if (itemResult.RemoteImages.Any(x => x.type == imageType)) + { + break; + } + + itemResult.RemoteImages.Add((uri.ToString(), imageType)); + } + + break; + } + default: string readerName = reader.Name; if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue)) diff --git a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs index f0c50d8e51..7ae55c791e 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/EpisodeNfoParser.cs @@ -25,13 +25,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public EpisodeNfoParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, config, providerManager, userManager, userDataManager, directoryService) { } diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 2d0eb8433d..b466fa25ae 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -25,13 +25,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public MovieNfoParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, config, providerManager, userManager, userDataManager, directoryService) { } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs index bd2607bd8d..2f5fd40e2f 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeasonNfoParser.cs @@ -21,13 +21,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public SeasonNfoParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, config, providerManager, userManager, userDataManager, directoryService) { } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index fbab8b5214..f6574c365c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -22,13 +22,15 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public SeriesNfoParser( ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, config, providerManager, userManager, userDataManager, directoryService) { } diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs index 24f1274112..bd557d783c 100644 --- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs @@ -20,6 +20,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; /// /// Initializes a new instance of the class. @@ -30,13 +31,15 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public AlbumNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -44,12 +47,13 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken) { - new BaseNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(result, path, cancellationToken); + new BaseNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs index fac28ab59c..54bb83114b 100644 --- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs @@ -20,6 +20,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; /// /// Initializes a new instance of the class. @@ -30,13 +31,15 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public ArtistNfoProvider( IFileSystem fileSystem, ILogger logger, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -44,12 +47,13 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken) { - new BaseNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(result, path, cancellationToken); + new BaseNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs index af722748b5..b8f76f31da 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs @@ -21,6 +21,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; public BaseVideoNfoProvider( ILogger> logger, @@ -28,7 +29,8 @@ namespace MediaBrowser.XbmcMetadata.Providers IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -36,6 +38,7 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// @@ -45,10 +48,12 @@ namespace MediaBrowser.XbmcMetadata.Providers { Item = result.Item }; - new MovieNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(tmpItem, path, cancellationToken); + new MovieNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(tmpItem, path, cancellationToken); result.Item = (T)tmpItem.Item; result.People = tmpItem.People; + result.Images = tmpItem.Images; + result.RemoteImages = tmpItem.RemoteImages; if (tmpItem.UserDataList != null) { diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs index 7233f99dcb..64b208345e 100644 --- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs @@ -20,6 +20,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; /// /// Initializes a new instance of the class. @@ -30,13 +31,15 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public EpisodeNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -44,12 +47,13 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken) { - new EpisodeNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(result, path, cancellationToken); + new EpisodeNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// diff --git a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs index 811d39a9da..cdbc5a9187 100644 --- a/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/MovieNfoProvider.cs @@ -21,14 +21,16 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public MovieNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, fileSystem, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService) { } } diff --git a/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs index 09df509eed..9d1f3e61d1 100644 --- a/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/MusicVideoNfoProvider.cs @@ -21,14 +21,16 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public MusicVideoNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, fileSystem, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService) { } } diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs index 8f0ed6df78..97220cf7ea 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs @@ -20,6 +20,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; /// /// Initializes a new instance of the class. @@ -30,13 +31,15 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public SeasonNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -44,12 +47,13 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken) { - new SeasonNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(result, path, cancellationToken); + new SeasonNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs index 3e496dc584..9a9b941236 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs @@ -20,6 +20,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; + private readonly IDirectoryService _directoryService; /// /// Initializes a new instance of the class. @@ -30,13 +31,15 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public SeriesNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) : base(fileSystem) { _logger = logger; @@ -44,12 +47,13 @@ namespace MediaBrowser.XbmcMetadata.Providers _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; + _directoryService = directoryService; } /// protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken) { - new SeriesNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager).Fetch(result, path, cancellationToken); + new SeriesNfoParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// diff --git a/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs index 4717d81e6f..93b1be62fc 100644 --- a/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/VideoNfoProvider.cs @@ -21,14 +21,16 @@ namespace MediaBrowser.XbmcMetadata.Providers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public VideoNfoProvider( ILogger logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, - IUserDataManager userDataManager) - : base(logger, fileSystem, config, providerManager, userManager, userDataManager) + IUserDataManager userDataManager, + IDirectoryService directoryService) + : base(logger, fileSystem, config, providerManager, userManager, userDataManager, directoryService) { } } diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs index d10ef9b478..4386844732 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/EpisodeNfoProviderTests.cs @@ -37,8 +37,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new XbmcMetadataOptions()); var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new EpisodeNfoParser(new NullLogger(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new EpisodeNfoParser( + new NullLogger(), + config.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 76231391e2..76e10b4515 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -9,7 +9,9 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; +using MediaBrowser.Model.System; using MediaBrowser.Providers.Plugins.Tmdb.Movies; using MediaBrowser.XbmcMetadata.Parsers; using Microsoft.Extensions.Logging.Abstractions; @@ -23,6 +25,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers private readonly MovieNfoParser _parser; private readonly IUserDataManager _userDataManager; private readonly User _testUser; + private readonly FileSystemMetadata _localImageFileMetadata; public MovieNfoParserTests() { @@ -52,8 +55,36 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers userData.Setup(x => x.GetUserData(_testUser, It.IsAny())) .Returns(new UserItemData()); + var directoryService = new Mock(); + if (MediaBrowser.Common.System.OperatingSystem.Id != OperatingSystemId.Windows) + { + _localImageFileMetadata = new FileSystemMetadata() + { + Exists = true, + FullName = "/media/movies/Justice League (2017).jpg" + }; + directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName)) + .Returns(_localImageFileMetadata); + } + else + { + _localImageFileMetadata = new FileSystemMetadata() + { + Exists = true, + FullName = "C:\\media\\movies\\Justice League (2017).jpg" + }; + directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName)) + .Returns(_localImageFileMetadata); + } + _userDataManager = userData.Object; - _parser = new MovieNfoParser(new NullLogger(), configManager.Object, providerManager.Object, user.Object, userData.Object); + _parser = new MovieNfoParser( + new NullLogger(), + configManager.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] @@ -134,6 +165,37 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers // Movie set Assert.Equal("702342", item.ProviderIds[MetadataProvider.TmdbCollection.ToString()]); Assert.Equal("Justice League Collection", item.CollectionName); + + // Images + Assert.Equal(6, result.RemoteImages.Count); + + var posters = result.RemoteImages.Where(x => x.type == ImageType.Primary).ToList(); + Assert.Single(posters); + Assert.Equal("http://image.tmdb.org/t/p/original/9rtrRGeRnL0JKtu9IMBWsmlmmZz.jpg", posters[0].url); + + var logos = result.RemoteImages.Where(x => x.type == ImageType.Logo).ToList(); + Assert.Single(logos); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png", logos[0].url); + + var banners = result.RemoteImages.Where(x => x.type == ImageType.Banner).ToList(); + Assert.Single(banners); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviebanner/justice-league-586017e95adbd.jpg", banners[0].url); + + var thumbs = result.RemoteImages.Where(x => x.type == ImageType.Thumb).ToList(); + Assert.Single(thumbs); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviethumb/justice-league-585fb155c3743.jpg", thumbs[0].url); + + var art = result.RemoteImages.Where(x => x.type == ImageType.Art).ToList(); + Assert.Single(art); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/hdmovieclearart/justice-league-5865c23193041.png", art[0].url); + + var discArt = result.RemoteImages.Where(x => x.type == ImageType.Disc).ToList(); + Assert.Single(discArt); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png", discArt[0].url); + + // Local Image - contains only one item depending on operating system + Assert.Single(result.Images); + Assert.Equal(_localImageFileMetadata.Name, result.Images[0].FileInfo.Name); } [Theory] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs index 2183d2a2f0..29de2a95e9 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicAlbumNfoProviderTests.cs @@ -1,7 +1,6 @@ #pragma warning disable CA5369 using System; -using System.Linq; using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; @@ -11,7 +10,6 @@ using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; using MediaBrowser.Providers.Music; -using MediaBrowser.Providers.Plugins.MusicBrainz; using MediaBrowser.XbmcMetadata.Parsers; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -38,8 +36,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new XbmcMetadataOptions()); var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new BaseNfoParser(new NullLogger>(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new BaseNfoParser( + new NullLogger>(), + config.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs index f86b7604e4..e54b35eb5e 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs @@ -35,8 +35,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new XbmcMetadataOptions()); var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new BaseNfoParser(new NullLogger>(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new BaseNfoParser( + new NullLogger>(), + config.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs index 898554936b..bf887cab18 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicVideoNfoParserTests.cs @@ -30,8 +30,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new MovieNfoParser(new NullLogger>(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new MovieNfoParser( + new NullLogger>(), + config.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs index 602db7c09a..c497d4fa26 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeasonNfoProviderTests.cs @@ -31,8 +31,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new XbmcMetadataOptions()); var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new SeasonNfoParser(new NullLogger(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new SeasonNfoParser( + new NullLogger(), + config.Object, + providerManager.Object, + user.Object, + userData.Object, + directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs index f8eb04b3a9..7c7d698f08 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/SeriesNfoParserTests.cs @@ -29,8 +29,9 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new XbmcMetadataOptions()); var user = new Mock(); var userData = new Mock(); + var directoryService = new Mock(); - _parser = new SeriesNfoParser(new NullLogger(), config.Object, providerManager.Object, user.Object, userData.Object); + _parser = new SeriesNfoParser(new NullLogger(), config.Object, providerManager.Object, user.Object, userData.Object, directoryService.Object); } [Fact] diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo index 72e27fe506..c35d37b180 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo @@ -59,6 +59,8 @@ http://image.tmdb.org/t/p/original/exLtrlI7JjKcfQVTccI7XdQRFMz.jpg http://image.tmdb.org/t/p/original/paLcue01KpfQftorfjKqqD4qvlL.jpg http://image.tmdb.org/t/p/original/yVDIfiKIsCbdFcgLXW34bAsnQvy.jpg + C:\media\movies\Justice League (2017).jpg + /media/movies/Justice League (2017).jpg https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-5865bf95cbadb.png https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-585e9ca3bcf6a.png https://assets.fanart.tv/fanart/movies/141052/hdmovielogo/justice-league-57b476a831d74.png From 0fde0a82e4a914e1d9b4b9814d9f4942307a3c15 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sun, 28 Feb 2021 12:12:37 +0000 Subject: [PATCH 1179/1930] Translated using Weblate (Swedish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sv/ --- Emby.Server.Implementations/Localization/Core/sv.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json index 345d41e9ee..b5a7fa5b8f 100644 --- a/Emby.Server.Implementations/Localization/Core/sv.json +++ b/Emby.Server.Implementations/Localization/Core/sv.json @@ -117,5 +117,6 @@ "TaskCleanActivityLogDescription": "Radera aktivitets logg inlägg som är äldre än definerad ålder.", "TaskCleanActivityLog": "Rensa Aktivitets Logg", "Undefined": "odefinierad", - "Forced": "Tvingad" + "Forced": "Tvingad", + "Default": "Standard" } From 4bbfcaef83579239a9bef708c71a889cb3d829b4 Mon Sep 17 00:00:00 2001 From: Moshe Schmidt Date: Wed, 17 Feb 2021 21:18:27 +0100 Subject: [PATCH 1180/1930] Include specials in the calculation for the "Next Up" episode. Fixes #1479 --- CONTRIBUTORS.md | 1 + .../Sorting/AiredEpisodeOrderComparer.cs | 4 +- .../TV/TVSeriesManager.cs | 46 +++++++++++++++---- 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1200275d52..bcc27b4dd8 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -104,6 +104,7 @@ - [shemanaev](https://github.com/shemanaev) - [skaro13](https://github.com/skaro13) - [sl1288](https://github.com/sl1288) + - [Smith00101010](https://github.com/Smith00101010) - [sorinyo2004](https://github.com/sorinyo2004) - [sparky8251](https://github.com/sparky8251) - [spookbits](https://github.com/spookbits) diff --git a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs index 1f68a9c810..60698e803d 100644 --- a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs +++ b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs @@ -131,11 +131,11 @@ namespace Emby.Server.Implementations.Sorting return GetSpecialCompareValue(x).CompareTo(GetSpecialCompareValue(y)); } - private static int GetSpecialCompareValue(Episode item) + private static long GetSpecialCompareValue(Episode item) { // First sort by season number // Since there are three sort orders, pad with 9 digits (3 for each, figure 1000 episode buffer should be enough) - var val = (item.AirsAfterSeasonNumber ?? item.AirsBeforeSeasonNumber ?? 0) * 1000000000; + var val = (item.AirsAfterSeasonNumber ?? item.AirsBeforeSeasonNumber ?? 0) * 1000000000L; // Second sort order is if it airs after the season if (item.AirsAfterSeasonNumber.HasValue) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 839b62448b..d111e1a1c6 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; @@ -11,7 +10,6 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.TV; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Episode = MediaBrowser.Controller.Entities.TV.Episode; using Series = MediaBrowser.Controller.Entities.TV.Series; @@ -23,12 +21,14 @@ namespace Emby.Server.Implementations.TV private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; private readonly ILibraryManager _libraryManager; + private readonly IServerConfigurationManager _configurationManager; - public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager) + public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager) { _userManager = userManager; _userDataManager = userDataManager; _libraryManager = libraryManager; + _configurationManager = configurationManager; } public QueryResult GetNextUp(NextUpQuery request, DtoOptions dtoOptions) @@ -200,13 +200,10 @@ namespace Emby.Server.Implementations.TV ParentIndexNumberNotEquals = 0, DtoOptions = new DtoOptions { - Fields = new ItemFields[] - { - ItemFields.SortName - }, + Fields = new[] { ItemFields.SortName }, EnableImages = false } - }).FirstOrDefault(); + }).Cast().FirstOrDefault(); Func getEpisode = () => { @@ -224,6 +221,39 @@ namespace Emby.Server.Implementations.TV DtoOptions = dtoOptions }).Cast().FirstOrDefault(); + if (_configurationManager.Configuration.DisplaySpecialsWithinSeasons) + { + var consideredEpisodes = _libraryManager.GetItemList(new InternalItemsQuery(user) + { + AncestorWithPresentationUniqueKey = null, + SeriesPresentationUniqueKey = seriesKey, + ParentIndexNumber = 0, + IncludeItemTypes = new[] { nameof(Episode) }, + IsPlayed = false, + IsVirtualItem = false, + DtoOptions = dtoOptions + }).Cast().Where(episode => episode.AirsBeforeSeasonNumber != null || episode.AirsAfterSeasonNumber != null).ToList(); + + if (lastWatchedEpisode != null) + { + // Last watched episode is added, because there could be specials that aired before the last watched episode + consideredEpisodes.Add(lastWatchedEpisode); + } + + if (nextEpisode != null) + { + consideredEpisodes.Add(nextEpisode); + } + + var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) }).Cast(); + if (lastWatchedEpisode != null) + { + sortedConsideredEpisodes = sortedConsideredEpisodes.SkipWhile(episode => episode.Id != lastWatchedEpisode.Id).Skip(1); + } + + nextEpisode = sortedConsideredEpisodes.FirstOrDefault(); + } + if (nextEpisode != null) { var userData = _userDataManager.GetUserData(user, nextEpisode); From 18cd634ec8316fe5978d7ad3867de66b85cd5fba Mon Sep 17 00:00:00 2001 From: Mister Rajoy Date: Sun, 28 Feb 2021 23:03:28 +0100 Subject: [PATCH 1181/1930] Fix duplicated movies when group movies into collections is enabled --- .../Collections/CollectionManager.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 1ab2bdfbe8..449f8872fd 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -344,7 +344,20 @@ namespace Emby.Server.Implementations.Collections } else { - results[item.Id] = item; + var alreadyInResults = false; + foreach (var child in item.GetMediaSources(true)) + { + + if (results.ContainsKey(Guid.Parse(child.Id))) + { + alreadyInResults = true; + } + } + if (!alreadyInResults) + { + + results[item.Id] = item; + } } } } From f6c49f1373554609257f2126e34e04fc2790e715 Mon Sep 17 00:00:00 2001 From: Csaba Date: Mon, 1 Mar 2021 09:12:46 +0000 Subject: [PATCH 1182/1930] Translated using Weblate (Hungarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hu/ --- Emby.Server.Implementations/Localization/Core/hu.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index e5707e78c9..ef80705031 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -49,7 +49,7 @@ "NotificationOptionAudioPlayback": "Audió lejátszás elkezdve", "NotificationOptionAudioPlaybackStopped": "Audió lejátszás leállítva", "NotificationOptionCameraImageUploaded": "Kamera kép feltöltve", - "NotificationOptionInstallationFailed": "Telepítési hiba", + "NotificationOptionInstallationFailed": "Telepítés sikertelen", "NotificationOptionNewLibraryContent": "Új tartalom hozzáadva", "NotificationOptionPluginError": "Bővítmény hiba", "NotificationOptionPluginInstalled": "Bővítmény telepítve", From fef43c556d3987b008aab882f409e780c4b36b82 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Mar 2021 12:00:38 +0000 Subject: [PATCH 1183/1930] Bump libse from 3.5.8 to 3.6.0 Bumps [libse](https://github.com/SubtitleEdit/subtitleedit) from 3.5.8 to 3.6.0. - [Release notes](https://github.com/SubtitleEdit/subtitleedit/releases) - [Changelog](https://github.com/SubtitleEdit/subtitleedit/blob/master/Changelog.txt) - [Commits](https://github.com/SubtitleEdit/subtitleedit/compare/3.5.8...3.6.0) Signed-off-by: dependabot[bot] --- MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 61daf50b32..3d6b4f98a7 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -24,7 +24,7 @@ - + From 829442c419277e29602ac641fb3d52fad44c9df6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Mar 2021 12:00:38 +0000 Subject: [PATCH 1184/1930] Bump Microsoft.NET.Test.Sdk from 16.8.3 to 16.9.1 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.8.3 to 16.9.1. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.8.3...v16.9.1) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index c6a8ffbd06..5ed7db0ac9 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 47e2354415..278f341099 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index fb18a8a8db..b02a68a3d9 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 7e4a2efad3..850db1c75b 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -8,7 +8,7 @@ - + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index ec9cc656a2..e729dbb09e 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -19,7 +19,7 @@ - + diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index 6c404193c2..b6d2c63bd8 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -8,7 +8,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 247e6aa7ab..99185c975d 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index 36ff93a452..ac5034f4e7 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 14b8cbd54c..e312fa5ce0 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index bc076caed6..2796b2ef16 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -14,7 +14,7 @@ - + From b0d391427bac1dfd6f03fdd519a21c9dc0efbbf8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Mar 2021 14:06:48 +0000 Subject: [PATCH 1185/1930] Bump Moq from 4.16.0 to 4.16.1 Bumps [Moq](https://github.com/moq/moq4) from 4.16.0 to 4.16.1. - [Release notes](https://github.com/moq/moq4/releases) - [Changelog](https://github.com/moq/moq4/blob/main/CHANGELOG.md) - [Commits](https://github.com/moq/moq4/compare/v4.16.0...v4.16.1) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../NetworkTesting/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 5ed7db0ac9..873ff0ab4a 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj index ac5034f4e7..fd77397bae 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index e312fa5ce0..1ad8171bee 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -23,7 +23,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index 2796b2ef16..d6aab3f85e 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -15,7 +15,7 @@ - + From ed0267252f1a2b5922db7a52ad63799a5009a6ce Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 1 Mar 2021 20:00:00 +0100 Subject: [PATCH 1186/1930] Remove tests that are upstreamed libse (the SSA parser we use) has these same tests now --- .../Subtitles/SsaParserTests.cs | 29 +------------------ 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs index 5033d1de91..5db80c3001 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SsaParserTests.cs @@ -13,38 +13,11 @@ namespace Jellyfin.MediaEncoding.Subtitles.Tests { public class SsaParserTests { - // commonly shared invariant value between tests, assumes default format order - private const string InvariantDialoguePrefix = "[Events]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,"; - private readonly SsaParser _parser = new SsaParser(new NullLogger()); - [Theory] - [InlineData("[EvEnTs]\nDialogue: ,0:00:00.00,0:00:00.01,,,,,,,text", "text")] // label casing insensitivity - [InlineData("[Events]\n,0:00:00.00,0:00:00.01,,,,,,,labelless dialogue", "labelless dialogue")] // no "Dialogue:" label, it is optional - // TODO: Fix upstream - // [InlineData("[Events]\nFormat: Text, Start, End, Layer, Effect, Style\nDialogue: reordered text,0:00:00.00,0:00:00.01", "reordered text")] // reordered formats - [InlineData(InvariantDialoguePrefix + "Cased TEXT", "Cased TEXT")] // preserve text casing - [InlineData(InvariantDialoguePrefix + " text ", " text ")] // do not trim text - [InlineData(InvariantDialoguePrefix + "text, more text", "text, more text")] // append excess dialogue values (> 10) to text - [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text{\\fn} end", "start text end")] // font name - [InlineData(InvariantDialoguePrefix + "start {\\fs10}text{\\fs} end", "start text end")] // font size - [InlineData(InvariantDialoguePrefix + "start {\\c&H112233}text{\\c} end", "start text end")] // color - // TODO: Fix upstream - // [InlineData(InvariantDialoguePrefix + "start {\\1c&H112233}text{\\1c} end", "start text end")] // primay color - // [InlineData(InvariantDialoguePrefix + "start {\\fnFont Name}text1 {\\fs10}text2{\\fs}{\\fn} {\\1c&H112233}text3{\\1c} end", "start text1 text2 text3 end")] // nested formatting - public void Parse(string ssa, string expectedText) - { - using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) - { - SubtitleTrackInfo subtitleTrackInfo = _parser.Parse(stream, CancellationToken.None); - SubtitleTrackEvent actual = subtitleTrackInfo.TrackEvents[0]; - Assert.Equal(expectedText, actual.Text); - } - } - [Theory] [MemberData(nameof(Parse_MultipleDialogues_TestData))] - public void Parse_MultipleDialogues(string ssa, IReadOnlyList expectedSubtitleTrackEvents) + public void Parse_MultipleDialogues_Success(string ssa, IReadOnlyList expectedSubtitleTrackEvents) { using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(ssa))) { From ba62d9d1fe84dfb16c502ab7e105c6c6807770ab Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 1 Mar 2021 20:35:38 +0100 Subject: [PATCH 1187/1930] Revert breaking change --- .../Entities/ProviderIdsExtensions.cs | 27 +++++++++++++ .../Entities/ProviderIdsExtensionsTests.cs | 38 +++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 11c3dbe42e..bde5a1da19 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -9,6 +9,33 @@ namespace MediaBrowser.Model.Entities /// public static class ProviderIdsExtensions { + /// + /// Checks if this instance has an id for the given provider. + /// + /// The instance. + /// The of the provider name. + /// true if a provider id with the given name was found; otherwise false. + public static bool HasProviderId(this IHasProviderIds instance, string name) + { + if (instance == null) + { + throw new ArgumentNullException(nameof(instance)); + } + + return instance.ProviderIds?.ContainsKey(name) ?? false; + } + + /// + /// Checks if this instance has an id for the given provider. + /// + /// The instance. + /// The provider. + /// true if a provider id with the given name was found; otherwise false. + public static bool HasProviderId(this IHasProviderIds instance, MetadataProvider provider) + { + return instance.HasProviderId(provider.ToString()); + } + /// /// Gets a provider id. /// diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs index c1a1525bad..2b2414ef1b 100644 --- a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs +++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs @@ -9,6 +9,44 @@ namespace Jellyfin.Model.Tests.Entities { private const string ExampleImdbId = "tt0113375"; + [Fact] + public void HasProviderId_NullInstance_ThrowsArgumentNullException() + { + Assert.Throws(() => ProviderIdsExtensions.HasProviderId(null!, MetadataProvider.Imdb)); + } + + [Fact] + public void HasProviderId_NullProvider_False() + { + var nullProvider = new ProviderIdsExtensionsTestsObject() + { + ProviderIds = null! + }; + + Assert.False(nullProvider.HasProviderId(MetadataProvider.Imdb)); + } + + [Fact] + public void HasProviderId_NullName_ThrowsArgumentNullException() + { + Assert.Throws(() => ProviderIdsExtensionsTestsObject.Empty.HasProviderId(null!)); + } + + [Fact] + public void HasProviderId_NotFoundName_False() + { + Assert.False(ProviderIdsExtensionsTestsObject.Empty.HasProviderId(MetadataProvider.Imdb)); + } + + [Fact] + public void HasProviderId_FoundName_True() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = ExampleImdbId; + + Assert.True(provider.HasProviderId(MetadataProvider.Imdb)); + } + [Fact] public void GetProviderId_NullInstance_ThrowsArgumentNullException() { From fdd4b6b3f146c4598fb1709f71dd11ffa623db28 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 1 Mar 2021 21:02:20 +0000 Subject: [PATCH 1188/1930] Changed message --- Jellyfin.Server/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index f05cdfe9bd..461ff163c3 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -198,7 +198,7 @@ namespace Jellyfin.Server } catch { - _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in system.xml and try again."); + _logger.LogError("Kestrel failed to start! This is most likely due to an invalid address or port bind - correct your bind configuration in network.xml and try again."); throw; } From dedc94ec91d3562a71cc9d7e88c8c23f373d64a2 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 1 Mar 2021 21:32:49 +0000 Subject: [PATCH 1189/1930] correction of ip6 loopback --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 51fcb6d9a0..9c7d096a76 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -414,7 +414,7 @@ namespace Jellyfin.Networking.Manager } // There isn't any others, so we'll use the loopback. - result = IsIP6Enabled ? "::" : "127.0.0.1"; + result = IsIP6Enabled ? "::1" : "127.0.0.1"; _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); return result; } From 594294871438bd83fee3198c647b2ff30defa8e1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 1 Mar 2021 23:42:04 +0000 Subject: [PATCH 1190/1930] Kestrel workaround --- Jellyfin.Networking/Manager/NetworkManager.cs | 19 +++++++++++++++---- Jellyfin.Server/Program.cs | 2 +- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 9c7d096a76..d2e9dcf9e6 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -285,14 +285,25 @@ namespace Jellyfin.Networking.Manager // No bind address and no exclusions, so listen on all interfaces. Collection result = new Collection(); - if (IsIP4Enabled) + if (IsIP6Enabled && IsIP4Enabled) + { + // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any + result.AddItem(IPAddress.IPv6Any); + } + else if (IsIP4Enabled) { result.AddItem(IPAddress.Any); } - - if (IsIP6Enabled) + else if (IsIP6Enabled) { - result.AddItem(IPAddress.IPv6Any); + // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses. + foreach (var iface in _interfaceAddresses) + { + if (iface.AddressFamily == AddressFamily.InterNetworkV6) + { + result.AddItem(iface.Address); + } + } } return result; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index f05cdfe9bd..aee53b9868 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -280,7 +280,7 @@ namespace Jellyfin.Server bool flagged = false; foreach (IPObject netAdd in addresses) { - _logger.LogInformation("Kestrel listening on {0}", netAdd); + _logger.LogInformation("Kestrel listening on {0}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { From b5e3c02865b4fc4953c317f647b7319db34922c8 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Mon, 1 Mar 2021 19:37:46 -0500 Subject: [PATCH 1191/1930] Move IHasPermissions.cs to correct namespace --- Jellyfin.Data/Interfaces/IHasPermissions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Data/Interfaces/IHasPermissions.cs b/Jellyfin.Data/Interfaces/IHasPermissions.cs index 3be72259ad..85ee12ad74 100644 --- a/Jellyfin.Data/Interfaces/IHasPermissions.cs +++ b/Jellyfin.Data/Interfaces/IHasPermissions.cs @@ -2,7 +2,7 @@ using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; -namespace Jellyfin.Data +namespace Jellyfin.Data.Interfaces { /// /// An abstraction representing an entity that has permissions. From c275c5c1ea12a73c90b0f3599916eb48e21e130c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 2 Mar 2021 08:57:27 +0000 Subject: [PATCH 1192/1930] Update Jellyfin.Server/Program.cs Co-authored-by: Claus Vium --- Jellyfin.Server/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index aee53b9868..d2ab11be4f 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -280,7 +280,7 @@ namespace Jellyfin.Server bool flagged = false; foreach (IPObject netAdd in addresses) { - _logger.LogInformation("Kestrel listening on {0}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); + _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { From 8f99bdd07ce037b633993f06f5a68dcb293d6828 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Tue, 2 Mar 2021 21:17:25 +0100 Subject: [PATCH 1193/1930] Fix TMDb search name containing year (#5349) --- .../Plugins/Tmdb/TV/TmdbEpisodeProvider.cs | 16 ++++++---------- .../Plugins/Tmdb/TV/TmdbSeriesProvider.cs | 14 +++++++++----- .../Plugins/Tmdb/TmdbClientManager.cs | 5 +++-- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs index 93998a1102..b455e56349 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs @@ -111,10 +111,14 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var item = new Episode { - Name = info.Name, IndexNumber = info.IndexNumber, ParentIndexNumber = info.ParentIndexNumber, - IndexNumberEnd = info.IndexNumberEnd + IndexNumberEnd = info.IndexNumberEnd, + Name = episodeResult.Name, + PremiereDate = episodeResult.AirDate, + ProductionYear = episodeResult.AirDate?.Year, + Overview = episodeResult.Overview, + CommunityRating = Convert.ToSingle(episodeResult.VoteAverage) }; if (!string.IsNullOrEmpty(episodeResult.ExternalIds?.TvdbId)) @@ -122,14 +126,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV item.SetProviderId(MetadataProvider.Tvdb, episodeResult.ExternalIds.TvdbId); } - item.PremiereDate = episodeResult.AirDate; - item.ProductionYear = episodeResult.AirDate?.Year; - - item.Name = episodeResult.Name; - item.Overview = episodeResult.Overview; - - item.CommunityRating = Convert.ToSingle(episodeResult.VoteAverage); - if (episodeResult.Videos?.Results != null) { foreach (var video in episodeResult.Videos.Results) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index 942c85b90d..0238d0574b 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -22,15 +23,17 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV public class TmdbSeriesProvider : IRemoteMetadataProvider, IHasOrder { private readonly IHttpClientFactory _httpClientFactory; + private readonly ILibraryManager _libraryManager; private readonly TmdbClientManager _tmdbClientManager; public TmdbSeriesProvider( + ILibraryManager libraryManager, IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager) { + _libraryManager = libraryManager; _httpClientFactory = httpClientFactory; _tmdbClientManager = tmdbClientManager; - Current = this; } public string Name => TmdbUtils.ProviderName; @@ -38,8 +41,6 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV // After TheTVDB public int Order => 1; - internal static TmdbSeriesProvider Current { get; private set; } - public async Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken) { var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb); @@ -104,7 +105,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV } } - var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken) + var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken: cancellationToken) .ConfigureAwait(false); var remoteResults = new RemoteSearchResult[tvSearchResults.Count]; @@ -203,7 +204,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV if (string.IsNullOrEmpty(tmdbId)) { result.QueriedById = false; - var searchResults = await _tmdbClientManager.SearchSeriesAsync(info.Name, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + // ParseName is required here. + // Caller provides the filename with extension stripped and NOT the parsed filename + var parsedName = _libraryManager.ParseName(info.Name); + var searchResults = await _tmdbClientManager.SearchSeriesAsync(parsedName.Name, info.MetadataLanguage, info.Year ?? 0, cancellationToken).ConfigureAwait(false); if (searchResults.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 2dc5cd55da..bf0f027fce 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -278,9 +278,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// /// The name of the tv show. /// The tv show's language. + /// The year the tv show first aired. /// The cancellation token. /// The TMDb tv show information. - public async Task> SearchSeriesAsync(string name, string language, CancellationToken cancellationToken) + public async Task> SearchSeriesAsync(string name, string language, int year = 0, CancellationToken cancellationToken = default) { var key = $"searchseries-{name}-{language}"; if (_memoryCache.TryGetValue(key, out SearchContainer series)) @@ -291,7 +292,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb await EnsureClientConfigAsync().ConfigureAwait(false); var searchResults = await _tmDbClient - .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken) + .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), firstAirDateYear: year, cancellationToken: cancellationToken) .ConfigureAwait(false); if (searchResults.Results.Count > 0) From bfe84affb32f798b6f2b2a6a4306065fc8800b1a Mon Sep 17 00:00:00 2001 From: Nathan Mascitelli Date: Tue, 2 Mar 2021 22:20:41 -0500 Subject: [PATCH 1194/1930] Update README to include ffmpeg --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 29f9923499..5af312ad70 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,8 @@ Before the project can be built, you must first install the [.NET 5.0 SDK](https Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download). +[ffmpeg](https://ffmpeg.org/download.html) will also need to be installed. + ### Cloning the Repository After dependencies are installed you will need to clone a local copy of this repository. If you just want to run the server from source you can clone this repository directly, but if you are intending to contribute code changes to the project, you should [set up your own fork](https://jellyfin.org/docs/general/contributing/development.html#set-up-your-copy-of-the-repo) of the repository. The following example shows how you can clone the repository directly over HTTPS. From 664c5da31728e65d0e53ada7c06c918059f73615 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 3 Mar 2021 09:09:57 +0100 Subject: [PATCH 1195/1930] return false when providerid is null or empty --- MediaBrowser.Model/Entities/ProviderIdsExtensions.cs | 8 +++++--- MediaBrowser.Providers/Manager/ProviderManager.cs | 8 ++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index bde5a1da19..571bc70062 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -50,13 +50,15 @@ namespace MediaBrowser.Model.Entities throw new ArgumentNullException(nameof(instance)); } - if (instance.ProviderIds == null) + var foundProviderId = instance.ProviderIds.TryGetValue(name, out id); + // This occurs when searching with Identify (and possibly in other places) + if (string.IsNullOrEmpty(id)) { id = null; - return false; + foundProviderId = false; } - return instance.ProviderIds.TryGetValue(name, out id); + return foundProviderId; } /// diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 913f14d9b8..bc16a8abb3 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -869,14 +869,14 @@ namespace MediaBrowser.Providers.Manager } } } - catch (Exception) +#pragma warning disable CA1031 // do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // do not catch general exception types { - // Logged at lower levels + _logger.LogError(ex, "Provider {ProviderName} failed to retrieve search results", provider.Name); } } - // _logger.LogDebug("Returning search results {0}", _json.SerializeToString(resultList)); - return resultList; } From a49f5d2a441d53076c0eae27fc115a97691f4856 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 3 Mar 2021 09:37:21 +0100 Subject: [PATCH 1196/1930] revert removal of null check --- MediaBrowser.Model/Entities/ProviderIdsExtensions.cs | 6 ++++++ .../Entities/ProviderIdsExtensionsTests.cs | 10 +++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 571bc70062..3086fcefd4 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -50,6 +50,12 @@ namespace MediaBrowser.Model.Entities throw new ArgumentNullException(nameof(instance)); } + if (instance.ProviderIds == null) + { + id = null; + return false; + } + var foundProviderId = instance.ProviderIds.TryGetValue(name, out id); // This occurs when searching with Identify (and possibly in other places) if (string.IsNullOrEmpty(id)) diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs index 2b2414ef1b..cf9fb15d70 100644 --- a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs +++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs @@ -18,7 +18,7 @@ namespace Jellyfin.Model.Tests.Entities [Fact] public void HasProviderId_NullProvider_False() { - var nullProvider = new ProviderIdsExtensionsTestsObject() + var nullProvider = new ProviderIdsExtensionsTestsObject { ProviderIds = null! }; @@ -68,7 +68,7 @@ namespace Jellyfin.Model.Tests.Entities [Fact] public void GetProviderId_NullProvider_Null() { - var nullProvider = new ProviderIdsExtensionsTestsObject() + var nullProvider = new ProviderIdsExtensionsTestsObject { ProviderIds = null! }; @@ -85,7 +85,7 @@ namespace Jellyfin.Model.Tests.Entities [Fact] public void TryGetProviderId_NullProvider_False() { - var nullProvider = new ProviderIdsExtensionsTestsObject() + var nullProvider = new ProviderIdsExtensionsTestsObject { ProviderIds = null! }; @@ -146,7 +146,7 @@ namespace Jellyfin.Model.Tests.Entities [Fact] public void SetProviderId_NullProvider_Success() { - var nullProvider = new ProviderIdsExtensionsTestsObject() + var nullProvider = new ProviderIdsExtensionsTestsObject { ProviderIds = null! }; @@ -158,7 +158,7 @@ namespace Jellyfin.Model.Tests.Entities [Fact] public void SetProviderId_NullProviderAndEmptyName_Success() { - var nullProvider = new ProviderIdsExtensionsTestsObject() + var nullProvider = new ProviderIdsExtensionsTestsObject { ProviderIds = null! }; From 8b72b902f53b32c0c0d69eeda3bd32f992ac53ee Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 3 Mar 2021 12:28:40 +0100 Subject: [PATCH 1197/1930] fix HasProviderId and add tests --- .../Entities/ProviderIdsExtensions.cs | 2 +- .../Entities/ProviderIdsExtensionsTests.cs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 3086fcefd4..09d14dc6a4 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.Model.Entities throw new ArgumentNullException(nameof(instance)); } - return instance.ProviderIds?.ContainsKey(name) ?? false; + return instance.TryGetProviderId(name, out _); } /// diff --git a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs index cf9fb15d70..a1ace84769 100644 --- a/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs +++ b/tests/Jellyfin.Model.Tests/Entities/ProviderIdsExtensionsTests.cs @@ -47,6 +47,15 @@ namespace Jellyfin.Model.Tests.Entities Assert.True(provider.HasProviderId(MetadataProvider.Imdb)); } + [Fact] + public void HasProviderId_FoundNameEmptyValue_False() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = string.Empty; + + Assert.False(provider.HasProviderId(MetadataProvider.Imdb)); + } + [Fact] public void GetProviderId_NullInstance_ThrowsArgumentNullException() { @@ -112,6 +121,16 @@ namespace Jellyfin.Model.Tests.Entities Assert.Equal(ExampleImdbId, id); } + [Fact] + public void TryGetProviderId_FoundNameEmptyValue_False() + { + var provider = new ProviderIdsExtensionsTestsObject(); + provider.ProviderIds[MetadataProvider.Imdb.ToString()] = string.Empty; + + Assert.False(provider.TryGetProviderId(MetadataProvider.Imdb, out var id)); + Assert.Null(id); + } + [Fact] public void SetProviderId_NullInstance_ThrowsArgumentNullException() { From 610a30d791ab11b3d815cbf7e361198f30fdafd5 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 3 Mar 2021 15:13:43 +0100 Subject: [PATCH 1198/1930] Do nothing in timer callback when device locator is disposed --- RSSDP/SsdpDeviceLocator.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index bfad6de97a..0cdc5ce3db 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -97,6 +97,11 @@ namespace Rssdp.Infrastructure private async void OnBroadcastTimerCallback(object state) { + if (IsDisposed) + { + return; + } + StartListeningForNotifications(); RemoveExpiredDevicesFromCache(); @@ -180,8 +185,6 @@ namespace Rssdp.Infrastructure /// Throw if the ty is true. public void StartListeningForNotifications() { - ThrowIfDisposed(); - _CommunicationsServer.RequestReceived -= CommsServer_RequestReceived; _CommunicationsServer.RequestReceived += CommsServer_RequestReceived; _CommunicationsServer.BeginListeningForBroadcasts(); @@ -353,7 +356,7 @@ namespace Rssdp.Infrastructure { return; } - + var location = GetFirstHeaderUriValue("Location", message); if (location != null) { @@ -515,11 +518,6 @@ namespace Rssdp.Infrastructure private void RemoveExpiredDevicesFromCache() { - if (this.IsDisposed) - { - return; - } - DiscoveredSsdpDevice[] expiredDevices = null; lock (_Devices) { From d819a1d92827f6a8c8b3b5289a4ca306a9f098ed Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 3 Mar 2021 14:41:18 +0000 Subject: [PATCH 1199/1930] Remove Content-Length header from DLNA HEAD request (#5335) --- Emby.Dlna/PlayTo/PlayToController.cs | 2 +- Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index e4923b9eb0..5abc1bc134 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -132,7 +132,7 @@ namespace Emby.Dlna.PlayTo private async void OnDeviceMediaChanged(object sender, MediaChangedEventArgs e) { - if (_disposed) + if (_disposed || string.IsNullOrEmpty(e.OldMediaInfo.Url)) { return; } diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index 89d36ab09f..f828b1d9d6 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -107,7 +107,8 @@ namespace Jellyfin.Api.Helpers // Headers only if (isHeadRequest) { - return new FileContentResult(Array.Empty(), contentType); + httpContext.Response.Headers[HeaderNames.ContentType] = contentType; + return new OkResult(); } var transcodingLock = transcodingJobHelper.GetTranscodingLock(outputPath); From 631c0a35f61e9c9ce3e6decfe369faf2c73f3f62 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 3 Mar 2021 17:11:19 -0700 Subject: [PATCH 1200/1930] Always use case insensitive json parsing for api --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 77f6695bb7..1828f1a7eb 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -232,7 +232,6 @@ namespace Jellyfin.Server.Extensions options.JsonSerializerOptions.WriteIndented = jsonOptions.WriteIndented; options.JsonSerializerOptions.DefaultIgnoreCondition = jsonOptions.DefaultIgnoreCondition; options.JsonSerializerOptions.NumberHandling = jsonOptions.NumberHandling; - options.JsonSerializerOptions.PropertyNameCaseInsensitive = jsonOptions.PropertyNameCaseInsensitive; options.JsonSerializerOptions.Converters.Clear(); foreach (var converter in jsonOptions.Converters) From 858c91ab485f79648aa625e89378c6de9e19df4b Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 4 Mar 2021 18:25:52 -0700 Subject: [PATCH 1201/1930] Specify defaults or set query parameter to nullable --- Jellyfin.Api/Controllers/AudioController.cs | 8 ++-- .../Controllers/DynamicHlsController.cs | 48 +++++++++---------- .../Controllers/HlsSegmentController.cs | 4 +- Jellyfin.Api/Controllers/ImageController.cs | 16 +++---- .../Controllers/ItemUpdateController.cs | 2 +- Jellyfin.Api/Controllers/LibraryController.cs | 2 +- .../Controllers/PlaystateController.cs | 20 ++++---- .../Controllers/UniversalAudioController.cs | 2 +- .../Controllers/VideoHlsController.cs | 8 ++-- Jellyfin.Api/Controllers/VideosController.cs | 12 ++--- 10 files changed, 62 insertions(+), 60 deletions(-) diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs index 616fe5b91f..8b1813b200 100644 --- a/Jellyfin.Api/Controllers/AudioController.cs +++ b/Jellyfin.Api/Controllers/AudioController.cs @@ -122,7 +122,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -174,7 +174,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -287,7 +287,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -339,7 +339,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index e375645cf0..f6c23c5aad 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -203,7 +203,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -218,7 +218,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions, [FromQuery] bool enableAdaptiveBitrateStreaming = true) { @@ -255,7 +255,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -270,7 +270,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions, EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming }; @@ -370,7 +370,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -385,7 +385,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions, [FromQuery] bool enableAdaptiveBitrateStreaming = true) { @@ -422,7 +422,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -437,7 +437,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions, EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming }; @@ -533,7 +533,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -548,7 +548,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { var cancellationTokenSource = new CancellationTokenSource(); @@ -585,7 +585,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -600,7 +600,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; @@ -698,7 +698,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -713,7 +713,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { var cancellationTokenSource = new CancellationTokenSource(); @@ -750,7 +750,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -765,7 +765,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; @@ -868,7 +868,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -883,7 +883,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { var streamingRequest = new VideoRequestDto @@ -920,7 +920,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -935,7 +935,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; @@ -1040,7 +1040,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -1055,7 +1055,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { var streamingRequest = new StreamingRequestDto @@ -1092,7 +1092,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -1107,7 +1107,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 25abe73ed0..d0ed45acb4 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -96,7 +96,9 @@ namespace Jellyfin.Api.Controllers [HttpDelete("Videos/ActiveEncodings")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult StopEncodingProcess([FromQuery] string deviceId, [FromQuery] string playSessionId) + public ActionResult StopEncodingProcess( + [FromQuery, Required] string deviceId, + [FromQuery, Required] string playSessionId) { _transcodingJobHelper.KillTranscodingJobs(deviceId, playSessionId, path => true); return NoContent(); diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index a50d6e46bf..cfc038f237 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -392,7 +392,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] Guid itemId, [FromRoute, Required] ImageType imageType, [FromRoute, Required] int imageIndex, - [FromQuery] int newIndex) + [FromQuery, Required] int newIndex) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -741,7 +741,7 @@ namespace Jellyfin.Api.Controllers public async Task GetArtistImage( [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -820,7 +820,7 @@ namespace Jellyfin.Api.Controllers public async Task GetGenreImage( [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -900,7 +900,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, [FromRoute, Required] int imageIndex, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -978,7 +978,7 @@ namespace Jellyfin.Api.Controllers public async Task GetMusicGenreImage( [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -1058,7 +1058,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, [FromRoute, Required] int imageIndex, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -1136,7 +1136,7 @@ namespace Jellyfin.Api.Controllers public async Task GetPersonImage( [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -1216,7 +1216,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string name, [FromRoute, Required] ImageType imageType, [FromRoute, Required] int imageIndex, - [FromQuery] string tag, + [FromQuery] string? tag, [FromQuery] ImageFormat? format, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, diff --git a/Jellyfin.Api/Controllers/ItemUpdateController.cs b/Jellyfin.Api/Controllers/ItemUpdateController.cs index 9e1a398538..a9f4a5a58c 100644 --- a/Jellyfin.Api/Controllers/ItemUpdateController.cs +++ b/Jellyfin.Api/Controllers/ItemUpdateController.cs @@ -195,7 +195,7 @@ namespace Jellyfin.Api.Controllers [HttpPost("Items/{itemId}/ContentType")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] - public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string contentType) + public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string? contentType) { var item = _libraryManager.GetItemById(itemId); if (item == null) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index db4aa96681..3443ebd72f 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -777,7 +777,7 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetLibraryOptionsInfo( [FromQuery] string? libraryContentType, - [FromQuery] bool isNewLibrary) + [FromQuery] bool isNewLibrary = false) { var result = new LibraryOptionsResultDto(); diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs index ec7b84ff60..f256c8c25c 100644 --- a/Jellyfin.Api/Controllers/PlaystateController.cs +++ b/Jellyfin.Api/Controllers/PlaystateController.cs @@ -152,7 +152,7 @@ namespace Jellyfin.Api.Controllers /// A . [HttpPost("Sessions/Playing/Ping")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult PingPlaybackSession([FromQuery] string playSessionId) + public ActionResult PingPlaybackSession([FromQuery, Required] string playSessionId) { _transcodingJobHelper.PingTranscodingJob(playSessionId, null); return NoContent(); @@ -202,9 +202,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? mediaSourceId, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, - [FromQuery] PlayMethod playMethod, + [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, - [FromQuery] string playSessionId, + [FromQuery] string? playSessionId, [FromQuery] bool canSeek = false) { var playbackStartInfo = new PlaybackStartInfo @@ -214,7 +214,7 @@ namespace Jellyfin.Api.Controllers MediaSourceId = mediaSourceId, AudioStreamIndex = audioStreamIndex, SubtitleStreamIndex = subtitleStreamIndex, - PlayMethod = playMethod, + PlayMethod = playMethod ?? PlayMethod.Transcode, PlaySessionId = playSessionId, LiveStreamId = liveStreamId }; @@ -254,10 +254,10 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] int? volumeLevel, - [FromQuery] PlayMethod playMethod, + [FromQuery] PlayMethod? playMethod, [FromQuery] string? liveStreamId, - [FromQuery] string playSessionId, - [FromQuery] RepeatMode repeatMode, + [FromQuery] string? playSessionId, + [FromQuery] RepeatMode? repeatMode, [FromQuery] bool isPaused = false, [FromQuery] bool isMuted = false) { @@ -271,10 +271,10 @@ namespace Jellyfin.Api.Controllers AudioStreamIndex = audioStreamIndex, SubtitleStreamIndex = subtitleStreamIndex, VolumeLevel = volumeLevel, - PlayMethod = playMethod, + PlayMethod = playMethod ?? PlayMethod.Transcode, PlaySessionId = playSessionId, LiveStreamId = liveStreamId, - RepeatMode = repeatMode + RepeatMode = repeatMode ?? RepeatMode.RepeatNone }; playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId); @@ -352,7 +352,7 @@ namespace Jellyfin.Api.Controllers return _userDataRepository.GetUserDataDto(item, user); } - private PlayMethod ValidatePlayMethod(PlayMethod method, string playSessionId) + private PlayMethod ValidatePlayMethod(PlayMethod method, string? playSessionId) { if (method == PlayMethod.Transcode) { diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 5aa033ccf4..0c2e6f19f1 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -112,7 +112,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? maxAudioSampleRate, [FromQuery] int? maxAudioBitDepth, [FromQuery] bool? enableRemoteMedia, - [FromQuery] bool breakOnNonKeyFrames, + [FromQuery] bool breakOnNonKeyFrames = false, [FromQuery] bool enableRedirection = true) { var deviceProfile = GetDeviceProfile(container, transcodingContainer, audioCodec, transcodingProtocol, breakOnNonKeyFrames, transcodingAudioChannels, maxAudioSampleRate, maxAudioBitDepth, maxAudioChannels); diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index ba51aa43e2..620eef5680 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -198,7 +198,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -213,7 +213,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions, [FromQuery] int? maxWidth, [FromQuery] int? maxHeight, @@ -253,7 +253,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -268,7 +268,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions, MaxHeight = maxHeight, MaxWidth = maxWidth, diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 44dc639523..8c7aa73257 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -364,7 +364,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -379,7 +379,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { var isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head; @@ -418,7 +418,7 @@ namespace Jellyfin.Api.Controllers Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, - SubtitleMethod = subtitleMethod, + SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? true, @@ -433,7 +433,7 @@ namespace Jellyfin.Api.Controllers TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, - Context = context, + Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; @@ -620,7 +620,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? height, [FromQuery] int? videoBitRate, [FromQuery] int? subtitleStreamIndex, - [FromQuery] SubtitleDeliveryMethod subtitleMethod, + [FromQuery] SubtitleDeliveryMethod? subtitleMethod, [FromQuery] int? maxRefFrames, [FromQuery] int? maxVideoBitDepth, [FromQuery] bool? requireAvc, @@ -635,7 +635,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? transcodeReasons, [FromQuery] int? audioStreamIndex, [FromQuery] int? videoStreamIndex, - [FromQuery] EncodingContext context, + [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { return GetVideoStream( From ba366118f9c9853153a90b7b5b22f0acd40867ed Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 5 Mar 2021 08:18:04 +0100 Subject: [PATCH 1202/1930] Do not use language or imagelanguages when searching for images TMDb API returns all images if languages are excluded, which is needed for the All Languages toggle in Identify. --- MediaBrowser.Providers/Manager/ProviderManager.cs | 1 + .../Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs | 3 ++- .../Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs | 3 ++- .../Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs | 3 ++- .../Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs | 3 ++- .../Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs | 3 ++- 6 files changed, 11 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index bc16a8abb3..d581dd4341 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -242,6 +242,7 @@ namespace MediaBrowser.Providers.Manager languages.Add(preferredLanguage); } + // TODO include [query.IncludeAllLanguages] as an argument to the providers var tasks = providers.Select(i => GetImages(item, i, languages, cancellationToken, query.ImageType)); var results = await Task.WhenAll(tasks).ConfigureAwait(false); diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs index df1e12240d..5ad61c567f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetImageProvider.cs @@ -58,7 +58,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets var language = item.GetPreferredMetadataLanguage(); - var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false); + // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here + var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, null, null, cancellationToken).ConfigureAwait(false); if (collection?.Images == null) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs index dac9e961c6..f34d689c1a 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieImageProvider.cs @@ -73,8 +73,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies return Enumerable.Empty(); } + // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here var movie = await _tmdbClientManager - .GetMovieAsync(movieTmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken) + .GetMovieAsync(movieTmdbId, null, null, cancellationToken) .ConfigureAwait(false); if (movie?.Images == null) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs index 3b7a0b254e..d923366242 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs @@ -63,8 +63,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var language = item.GetPreferredMetadataLanguage(); + // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here var episodeResult = await _tmdbClientManager - .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken) + .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, null, null, cancellationToken) .ConfigureAwait(false); var stills = episodeResult?.Images?.Stills; diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs index f4ed480aef..0d23c7872f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeasonImageProvider.cs @@ -52,8 +52,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var language = item.GetPreferredMetadataLanguage(); + // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here var seasonResult = await _tmdbClientManager - .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken) + .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, null, null, cancellationToken) .ConfigureAwait(false); var posters = seasonResult?.Images?.Posters; diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs index d0c6b8b886..a96fc8ed63 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs @@ -59,8 +59,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var language = item.GetPreferredMetadataLanguage(); + // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here var series = await _tmdbClientManager - .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken) + .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), null, null, cancellationToken) .ConfigureAwait(false); if (series?.Images == null) From ed7154db68f089cb8366aedaaeb93f1d5405251a Mon Sep 17 00:00:00 2001 From: Nichgon Date: Fri, 5 Mar 2021 07:42:03 +0000 Subject: [PATCH 1203/1930] Translated using Weblate (Thai) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/th/ --- Emby.Server.Implementations/Localization/Core/th.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/th.json b/Emby.Server.Implementations/Localization/Core/th.json index 71dd2c7a30..5bf58baf8c 100644 --- a/Emby.Server.Implementations/Localization/Core/th.json +++ b/Emby.Server.Implementations/Localization/Core/th.json @@ -50,7 +50,7 @@ "HeaderFavoriteArtists": "ศิลปินที่ชื่นชอบ", "HeaderFavoriteAlbums": "อัมบั้มที่ชื่นชอบ", "HeaderContinueWatching": "ดูต่อ", - "HeaderAlbumArtists": "อัลบั้มศิลปิน", + "HeaderAlbumArtists": "ศิลปินอัลบั้ม", "Genres": "ประเภท", "Folders": "โฟลเดอร์", "Favorites": "รายการโปรด", @@ -112,5 +112,6 @@ "System": "ระบบ", "Sync": "ซิงค์", "SubtitleDownloadFailureFromForItem": "ไม่สามารถดาวน์โหลดคำบรรยายจาก {0} สำหรับ {1} ได้", - "StartupEmbyServerIsLoading": "กำลังโหลดเซิร์ฟเวอร์ Jellyfin โปรดลองอีกครั้งในอีกสักครู่" + "StartupEmbyServerIsLoading": "กำลังโหลดเซิร์ฟเวอร์ Jellyfin โปรดลองอีกครั้งในอีกสักครู่", + "Default": "ค่าเริ่มต้น" } From a6d0db5d0409f72e2abb02291268b6971eaf1fcf Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 5 Mar 2021 11:15:14 +0100 Subject: [PATCH 1204/1930] 100% branch coverage for DashboardController --- Emby.Server.Implementations/Plugins/PluginManager.cs | 4 ++-- Jellyfin.Api/Controllers/DashboardController.cs | 4 ++-- MediaBrowser.Common/Plugins/IPluginManager.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 7bc9f0a7e2..c579fc8cba 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -34,7 +34,7 @@ namespace Emby.Server.Implementations.Plugins private readonly ILogger _logger; private readonly IApplicationHost _appHost; private readonly ServerConfiguration _config; - private readonly IList _plugins; + private readonly List _plugins; private readonly Version _minimumVersion; private IHttpClientFactory? _httpClientFactory; @@ -94,7 +94,7 @@ namespace Emby.Server.Implementations.Plugins /// /// Gets the Plugins. /// - public IList Plugins => _plugins; + public IReadOnlyList Plugins => _plugins; /// /// Returns all the assemblies. diff --git a/Jellyfin.Api/Controllers/DashboardController.cs b/Jellyfin.Api/Controllers/DashboardController.cs index a2c2ecd666..445733c24d 100644 --- a/Jellyfin.Api/Controllers/DashboardController.cs +++ b/Jellyfin.Api/Controllers/DashboardController.cs @@ -95,9 +95,9 @@ namespace Jellyfin.Api.Controllers return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin.Instance, i.Item1)); } - private IEnumerable> GetPluginPages(LocalPlugin? plugin) + private IEnumerable> GetPluginPages(LocalPlugin plugin) { - if (plugin?.Instance is not IHasWebPages hasWebPages) + if (plugin.Instance is not IHasWebPages hasWebPages) { return Enumerable.Empty>(); } diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index fc2fcb5179..f9a8fb6f7a 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Common.Plugins /// /// Gets the Plugins. /// - IList Plugins { get; } + IReadOnlyList Plugins { get; } /// /// Creates the plugins. From 37e374d33d73403470d07d814b5ee1367ca12e85 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 5 Mar 2021 14:09:23 +0100 Subject: [PATCH 1205/1930] make sure network path substitution matches correctly --- .../Library/LibraryManager.cs | 64 ++++----------- .../Library/PathExtensions.cs | 80 +++++++++++++++++++ .../Library/PathExtensionsTests.cs | 23 ++++++ 3 files changed, 117 insertions(+), 50 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index d9ffe64b3b..973b2df8ae 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2788,10 +2788,9 @@ namespace Emby.Server.Implementations.Library continue; } - var substitutionResult = SubstitutePathInternal(path, pathInfo.Path, pathInfo.NetworkPath); - if (substitutionResult.Item2) + if (path.TryReplaceSubPath(pathInfo.Path, pathInfo.NetworkPath, out var newPath)) { - return substitutionResult.Item1; + return newPath; } } } @@ -2802,22 +2801,22 @@ namespace Emby.Server.Implementations.Library if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath)) { - var metadataSubstitutionResult = SubstitutePathInternal(path, metadataPath, metadataNetworkPath); - if (metadataSubstitutionResult.Item2) + if (path.TryReplaceSubPath(metadataPath, metadataNetworkPath, out var newPath)) { - return metadataSubstitutionResult.Item1; + return newPath; } } foreach (var map in _configurationManager.Configuration.PathSubstitutions) { - if (!string.IsNullOrWhiteSpace(map.From)) + if (string.IsNullOrWhiteSpace(map.From)) { - var substitutionResult = SubstitutePathInternal(path, map.From, map.To); - if (substitutionResult.Item2) - { - return substitutionResult.Item1; - } + continue; + } + + if (path.TryReplaceSubPath(map.From, map.To, out var newPath)) + { + return newPath; } } @@ -2826,47 +2825,12 @@ namespace Emby.Server.Implementations.Library public string SubstitutePath(string path, string from, string to) { - return SubstitutePathInternal(path, from, to).Item1; - } - - private Tuple SubstitutePathInternal(string path, string from, string to) - { - if (string.IsNullOrWhiteSpace(path)) + if (path.TryReplaceSubPath(from, to, out var newPath)) { - throw new ArgumentNullException(nameof(path)); + return newPath; } - if (string.IsNullOrWhiteSpace(from)) - { - throw new ArgumentNullException(nameof(from)); - } - - if (string.IsNullOrWhiteSpace(to)) - { - throw new ArgumentNullException(nameof(to)); - } - - from = from.Trim(); - to = to.Trim(); - - var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase); - var changed = false; - - if (!string.Equals(newPath, path, StringComparison.Ordinal)) - { - if (to.IndexOf('/', StringComparison.Ordinal) != -1) - { - newPath = newPath.Replace('\\', '/'); - } - else - { - newPath = newPath.Replace('/', '\\'); - } - - changed = true; - } - - return new Tuple(newPath, changed); + return path; } private void SetExtraTypeFromFilename(Video item) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 06ff3e611b..1fc5526ae1 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -1,6 +1,7 @@ #nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Emby.Server.Implementations.Library @@ -47,5 +48,84 @@ namespace Emby.Server.Implementations.Library return null; } + + /// + /// Replaces a sub path with another sub path and normalizes the final path. + /// + /// The original path. + /// The original sub path. + /// The new sub path. + /// The result of the sub path replacement + /// The path after replacing the sub path. + /// , or is empty. + public static bool TryReplaceSubPath(this string path, string subPath, string newSubPath, [NotNullWhen(true)] out string? newPath) + { + if (string.IsNullOrWhiteSpace(path)) + { + throw new ArgumentNullException(nameof(path)); + } + + if (string.IsNullOrWhiteSpace(subPath)) + { + throw new ArgumentNullException(nameof(subPath)); + } + + if (string.IsNullOrWhiteSpace(newSubPath)) + { + throw new ArgumentNullException(nameof(newSubPath)); + } + + char oldDirectorySeparatorChar; + char newDirectorySeparatorChar; + // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162 + // The reasoning behind this is that a forward slash likely means it's a Linux path and + // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much). + if (newSubPath.Contains('/', StringComparison.Ordinal)) + { + oldDirectorySeparatorChar = '\\'; + newDirectorySeparatorChar = '/'; + } + else + { + oldDirectorySeparatorChar = '/'; + newDirectorySeparatorChar = '\\'; + } + + if (path.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) + { + path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); + } + + if (subPath.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) + { + subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); + } + + // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results + // when the sub path matches a similar but in-complete subpath + if (!subPath.EndsWith(newDirectorySeparatorChar)) + { + subPath += newDirectorySeparatorChar; + } + + if (newSubPath.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) + { + newSubPath = newSubPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); + } + + if (!newSubPath.EndsWith(newDirectorySeparatorChar)) + { + newSubPath += newDirectorySeparatorChar; + } + + if (!path.Contains(subPath, StringComparison.OrdinalIgnoreCase)) + { + newPath = null; + return false; + } + + newPath = path.Replace(subPath, newSubPath, StringComparison.OrdinalIgnoreCase); + return true; + } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs index 6d768af890..a96a053771 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs @@ -24,5 +24,28 @@ namespace Jellyfin.Server.Implementations.Tests.Library { Assert.Throws(() => PathExtensions.GetAttributeValue(input, attribute)); } + + [Theory] + [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff", "/home/jeff", true, "/home/jeff/myfile.mkv")] + [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff/", "/home/jeff", true, "/home/jeff/myfile.mkv")] + [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/not jeff's band", "/home/not jeff", false, null)] + [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/jeff's band", "/home/not jeff", true, "/home/not jeff/consistently inconsistent.mp3")] + [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff", true, "/home/jeff/myfile.mkv")] + public void TryReplaceSubPath_ValidArgs_Correct(string path, string subPath, string newSubPath, bool succeeded, string? expectedResult) + { + var status = PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result); + Assert.Equal(succeeded, status); + Assert.Equal(expectedResult, result); + } + + [Theory] + [InlineData("", "", "")] + [InlineData("/my/path", "", "")] + [InlineData("", "/another/path", "")] + [InlineData("", "", "/new/subpath")] + public void TryReplaceSubPath_EmptyString_ThrowsArgumentNullException(string path, string subPath, string newSubPath) + { + Assert.Throws(() => PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out _)); + } } } From fd0b3ca5ef82164f5551369b789b9677f30af172 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 5 Mar 2021 07:48:45 -0700 Subject: [PATCH 1206/1930] Add JsonVersionConverter and tests --- .../Json/Converters/JsonVersionConverter.cs | 23 ++++++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 1 + .../MediaBrowser.Common.csproj | 2 +- .../Json/JsonVersionConverterTests.cs | 36 +++++++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs new file mode 100644 index 0000000000..b8aecf8b84 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs @@ -0,0 +1,23 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// + /// Converts a Version object or value to/from JSON. + /// + /// + /// Required to send as a string instead of an object. + /// + public class JsonVersionConverter : JsonConverter + { + /// + public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => new Version(reader.GetString()); + + /// + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) + => writer.WriteStringValue(value.ToString()); + } +} \ No newline at end of file diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index a3999e7e25..2ef24a884a 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -35,6 +35,7 @@ namespace MediaBrowser.Common.Json { new JsonGuidConverter(), new JsonNullableGuidConverter(), + new JsonVersionConverter(), new JsonStringEnumConverter(), new JsonNullableStructConverterFactory(), new JsonBoolNumberConverter(), diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index e469436a93..8bb30c565b 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -14,7 +14,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs new file mode 100644 index 0000000000..83dfb0a4fb --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs @@ -0,0 +1,36 @@ +using System; +using System.Text.Json; +using MediaBrowser.Common.Json.Converters; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public class JsonVersionConverterTests + { + private readonly JsonSerializerOptions _options; + + public JsonVersionConverterTests() + { + _options = new JsonSerializerOptions(); + _options.Converters.Add(new JsonVersionConverter()); + } + + [Fact] + public void Deserialize_Version_Success() + { + var input = "\"1.025.222\""; + var output = new Version(1, 25, 222); + var deserializedInput = JsonSerializer.Deserialize(input, _options); + Assert.Equal(output, deserializedInput); + } + + [Fact] + public void Serialize_Version_Success() + { + var input = new Version(1, 09, 59); + var output = "\"1.9.59\""; + var serializedInput = JsonSerializer.Serialize(input, _options); + Assert.Equal(output, serializedInput); + } + } +} \ No newline at end of file From df1951cfe2baae539758b9592af1a16e51b69897 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Fri, 5 Mar 2021 08:30:49 -0700 Subject: [PATCH 1207/1930] Apply suggestions from code review Co-authored-by: dkanada --- MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs | 2 +- tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs index b8aecf8b84..f69e868cc4 100644 --- a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs @@ -20,4 +20,4 @@ namespace MediaBrowser.Common.Json.Converters public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString()); } -} \ No newline at end of file +} diff --git a/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs index 83dfb0a4fb..f2cefdbf8e 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonVersionConverterTests.cs @@ -33,4 +33,4 @@ namespace Jellyfin.Common.Tests.Json Assert.Equal(output, serializedInput); } } -} \ No newline at end of file +} From d0a2d00b29d87e7f71e85efd38d2b6c8beafe4ea Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Fri, 5 Mar 2021 16:56:21 +0100 Subject: [PATCH 1208/1930] Fix UpdateMediaPath model binding (#5378) --- .../Controllers/LibraryStructureController.cs | 13 ++++------- .../UpdateMediaPathRequestDto.cs | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) create mode 100644 Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs diff --git a/Jellyfin.Api/Controllers/LibraryStructureController.cs b/Jellyfin.Api/Controllers/LibraryStructureController.cs index 328efea26e..be9127dd39 100644 --- a/Jellyfin.Api/Controllers/LibraryStructureController.cs +++ b/Jellyfin.Api/Controllers/LibraryStructureController.cs @@ -241,23 +241,20 @@ namespace Jellyfin.Api.Controllers /// /// Updates a media path. /// - /// The name of the library. - /// The path info. + /// The name of the library and path infos. /// A . /// Media path updated. /// The name of the library may not be empty. [HttpPost("Paths/Update")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult UpdateMediaPath( - [FromQuery] string? name, - [FromBody] MediaPathInfo? pathInfo) + public ActionResult UpdateMediaPath([FromBody, Required] UpdateMediaPathRequestDto mediaPathRequestDto) { - if (string.IsNullOrWhiteSpace(name)) + if (string.IsNullOrWhiteSpace(mediaPathRequestDto.Name)) { - throw new ArgumentNullException(nameof(name)); + throw new ArgumentNullException(nameof(mediaPathRequestDto), "Name must not be null or empty"); } - _libraryManager.UpdateMediaPath(name, pathInfo); + _libraryManager.UpdateMediaPath(mediaPathRequestDto.Name, mediaPathRequestDto.PathInfo); return NoContent(); } diff --git a/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs b/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs new file mode 100644 index 0000000000..fbd4985f9c --- /dev/null +++ b/Jellyfin.Api/Models/LibraryStructureDto/UpdateMediaPathRequestDto.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations; +using MediaBrowser.Model.Configuration; + +namespace Jellyfin.Api.Models.LibraryStructureDto +{ + /// + /// Update library options dto. + /// + public class UpdateMediaPathRequestDto + { + /// + /// Gets or sets the library name. + /// + [Required] + public string Name { get; set; } = null!; + + /// + /// Gets or sets library folder path information. + /// + [Required] + public MediaPathInfo PathInfo { get; set; } = null!; + } +} From 59814bd55e8c6c5fbd167e90403b9bd2e390c78c Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 5 Mar 2021 19:57:48 +0100 Subject: [PATCH 1209/1930] do not pick a linked item as primary when merging versions --- Jellyfin.Api/Controllers/VideosController.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 44dc639523..195a96a561 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -217,9 +217,7 @@ namespace Jellyfin.Api.Controllers return BadRequest("Please supply at least two videos to merge."); } - var videosWithVersions = items.Where(i => i.MediaSourceCount > 1).ToList(); - - var primaryVersion = videosWithVersions.FirstOrDefault(); + var primaryVersion = items.FirstOrDefault(i => i.MediaSourceCount > 1 && string.IsNullOrEmpty(i.PrimaryVersionId)); if (primaryVersion == null) { primaryVersion = items From 6293629d3263722c49c14f7642fb33b2986b0e19 Mon Sep 17 00:00:00 2001 From: Smith00101010 Date: Fri, 5 Mar 2021 22:51:08 +0100 Subject: [PATCH 1210/1930] Apply suggested formatting changes Co-authored-by: BaronGreenback --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index d111e1a1c6..d3f6fa34d8 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -232,7 +232,10 @@ namespace Emby.Server.Implementations.TV IsPlayed = false, IsVirtualItem = false, DtoOptions = dtoOptions - }).Cast().Where(episode => episode.AirsBeforeSeasonNumber != null || episode.AirsAfterSeasonNumber != null).ToList(); + }) + .Cast() + .Where(episode => episode.AirsBeforeSeasonNumber != null || episode.AirsAfterSeasonNumber != null) + .ToList(); if (lastWatchedEpisode != null) { @@ -245,7 +248,8 @@ namespace Emby.Server.Implementations.TV consideredEpisodes.Add(nextEpisode); } - var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) }).Cast(); + var sortedConsideredEpisodes = _libraryManager.Sort(consideredEpisodes, user, new[] { (ItemSortBy.AiredEpisodeOrder, SortOrder.Ascending) }) + .Cast(); if (lastWatchedEpisode != null) { sortedConsideredEpisodes = sortedConsideredEpisodes.SkipWhile(episode => episode.Id != lastWatchedEpisode.Id).Skip(1); From e8413ed8c0cc401447b880dea96e94092bbefe88 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 6 Mar 2021 03:33:52 +0100 Subject: [PATCH 1211/1930] Use XDocument.LoadAsync instead of XDocument.Parse --- Emby.Dlna/PlayTo/SsdpHttpClient.cs | 16 ++++++++-------- Emby.Dlna/PlayTo/TransportCommands.cs | 6 ++---- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index 557bc69a73..b7643fb279 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -45,10 +45,10 @@ namespace Emby.Dlna.PlayTo cancellationToken) .ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - using var reader = new StreamReader(stream, Encoding.UTF8); - return XDocument.Parse( - await reader.ReadToEndAsync().ConfigureAwait(false), - LoadOptions.PreserveWhitespace); + return await XDocument.LoadAsync( + stream, + LoadOptions.PreserveWhitespace, + cancellationToken).ConfigureAwait(false); } private static string NormalizeServiceUrl(string baseUrl, string serviceUrl) @@ -94,10 +94,10 @@ namespace Emby.Dlna.PlayTo options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - using var reader = new StreamReader(stream, Encoding.UTF8); - return XDocument.Parse( - await reader.ReadToEndAsync().ConfigureAwait(false), - LoadOptions.PreserveWhitespace); + return await XDocument.LoadAsync( + stream, + LoadOptions.PreserveWhitespace, + cancellationToken).ConfigureAwait(false); } private async Task PostSoapDataAsync( diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index 0865968ad1..cbcf66e45c 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -13,12 +13,10 @@ namespace Emby.Dlna.PlayTo public class TransportCommands { private const string CommandBase = "\r\n" + "" + "" + "" + "{2}" + "" + ""; - private List _stateVariables = new List(); - private List _serviceActions = new List(); - public List StateVariables => _stateVariables; + public List StateVariables { get; } = new List(); - public List ServiceActions => _serviceActions; + public List ServiceActions { get; } = new List(); public static TransportCommands Create(XDocument document) { From 10229e1afe7e2403c59f508a667cafbb2c85a9ce Mon Sep 17 00:00:00 2001 From: Nathan Mascitelli Date: Fri, 5 Mar 2021 23:09:35 -0500 Subject: [PATCH 1212/1930] Link to jellyfin-ffmpeg --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5af312ad70..cba88c8d2b 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ Before the project can be built, you must first install the [.NET 5.0 SDK](https Instructions to run this project from the command line are included here, but you will also need to install an IDE if you want to debug the server while it is running. Any IDE that supports .NET Core development will work, but two options are recent versions of [Visual Studio](https://visualstudio.microsoft.com/downloads/) (at least 2017) and [Visual Studio Code](https://code.visualstudio.com/Download). -[ffmpeg](https://ffmpeg.org/download.html) will also need to be installed. +[ffmpeg](https://github.com/jellyfin/jellyfin-ffmpeg) will also need to be installed. ### Cloning the Repository From bc661c16e19413cbe6a94832280e3a24b6cf3c20 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 6 Mar 2021 14:01:37 +0100 Subject: [PATCH 1213/1930] simplify --- .../Library/PathExtensions.cs | 26 ++++++------------- .../Library/PathExtensionsTests.cs | 23 +++++++++------- 2 files changed, 21 insertions(+), 28 deletions(-) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 1fc5526ae1..41e64abf32 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -103,28 +103,18 @@ namespace Emby.Server.Implementations.Library // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results // when the sub path matches a similar but in-complete subpath - if (!subPath.EndsWith(newDirectorySeparatorChar)) + var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar; + if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase) + || (!oldSubPathEndsWithSeparator && path[subPath.Length] != newDirectorySeparatorChar)) { - subPath += newDirectorySeparatorChar; - } - - if (newSubPath.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) - { - newSubPath = newSubPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); - } - - if (!newSubPath.EndsWith(newDirectorySeparatorChar)) - { - newSubPath += newDirectorySeparatorChar; - } - - if (!path.Contains(subPath, StringComparison.OrdinalIgnoreCase)) - { - newPath = null; return false; } - newPath = path.Replace(subPath, newSubPath, StringComparison.OrdinalIgnoreCase); + var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar); + // Ensure that the path with the old subpath removed starts with a leading dir separator + int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length; + newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx)); + return true; } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs index a96a053771..a6fe905668 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs @@ -26,15 +26,16 @@ namespace Jellyfin.Server.Implementations.Tests.Library } [Theory] - [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff", "/home/jeff", true, "/home/jeff/myfile.mkv")] - [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff/", "/home/jeff", true, "/home/jeff/myfile.mkv")] - [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/not jeff's band", "/home/not jeff", false, null)] - [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/jeff's band", "/home/not jeff", true, "/home/not jeff/consistently inconsistent.mp3")] - [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff", true, "/home/jeff/myfile.mkv")] - public void TryReplaceSubPath_ValidArgs_Correct(string path, string subPath, string newSubPath, bool succeeded, string? expectedResult) + [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff", "/home/jeff", "/home/jeff/myfile.mkv")] + [InlineData("C:/Users/jeff/myfile.mkv", "C:/Users/jeff/", "/home/jeff", "/home/jeff/myfile.mkv")] + [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/jeff's band", "/home/not jeff", "/home/not jeff/consistently inconsistent.mp3")] + [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff", "/home/jeff/myfile.mkv")] + [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff/", "/home/jeff/myfile.mkv")] + [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/home/jeff/", "/home/jeff/myfile.mkv")] + [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/", "/myfile.mkv")] + public void TryReplaceSubPath_ValidArgs_Correct(string path, string subPath, string newSubPath, string? expectedResult) { - var status = PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result); - Assert.Equal(succeeded, status); + Assert.True(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result)); Assert.Equal(expectedResult, result); } @@ -43,9 +44,11 @@ namespace Jellyfin.Server.Implementations.Tests.Library [InlineData("/my/path", "", "")] [InlineData("", "/another/path", "")] [InlineData("", "", "/new/subpath")] - public void TryReplaceSubPath_EmptyString_ThrowsArgumentNullException(string path, string subPath, string newSubPath) + [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/not jeff's band", "/home/not jeff")] + public void TryReplaceSubPath_InvalidInput_ReturnsFalseAndNull(string path, string subPath, string newSubPath) { - Assert.Throws(() => PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out _)); + Assert.False(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result)); + Assert.Null(result); } } } From 6f898145afe013d7dfcd47fbc6adab9316e2dd63 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 6 Mar 2021 14:50:27 +0100 Subject: [PATCH 1214/1930] Use Uri.TryCreate and ImageType helper method --- .../Parsers/BaseNfoParser.cs | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index aa89936d0c..2e222c0a40 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -803,25 +803,11 @@ namespace MediaBrowser.XbmcMetadata.Parsers break; } - ImageType imageType = artType switch - { - "banner" => ImageType.Banner, - "clearlogo" => ImageType.Logo, - "discart" => ImageType.Disc, - "landscape" => ImageType.Thumb, - "clearart" => ImageType.Art, - // unknown type (including "poster") --> primary - _ => ImageType.Primary, - }; + ImageType imageType = GetImageType(artType); - Uri uri; - try + if (!Uri.TryCreate(val, UriKind.Absolute, out var uri) || uri == null) { - uri = new Uri(val); - } - catch (UriFormatException ex) - { - Logger.LogError(ex, "Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file path.", val, item.Name); + Logger.LogError("Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file path.", val, item.Name); break; } @@ -1256,5 +1242,24 @@ namespace MediaBrowser.XbmcMetadata.Parsers return string.IsNullOrWhiteSpace(value) ? Array.Empty() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries); } + + /// + /// Parses the ImageType from the nfo aspect property. + /// + /// The nfo aspect property. + /// The image type. + private static ImageType GetImageType(string aspect) + { + return aspect switch + { + "banner" => ImageType.Banner, + "clearlogo" => ImageType.Logo, + "discart" => ImageType.Disc, + "landscape" => ImageType.Thumb, + "clearart" => ImageType.Art, + // unknown type (including "poster") --> primary + _ => ImageType.Primary, + }; + } } } From b8d52dafa9047403cb7bde221baf9d39baf24e18 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Sat, 6 Mar 2021 16:02:52 +0100 Subject: [PATCH 1215/1930] Update MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs Co-authored-by: Bond-009 --- MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 2e222c0a40..18b4ffac99 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -805,7 +805,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers ImageType imageType = GetImageType(artType); - if (!Uri.TryCreate(val, UriKind.Absolute, out var uri) || uri == null) + if (!Uri.TryCreate(val, UriKind.Absolute, out var uri)) { Logger.LogError("Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file path.", val, item.Name); break; From 54211b921c86a4aa69e7390a662a48bf99011de1 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 6 Mar 2021 19:07:02 +0100 Subject: [PATCH 1216/1930] rider is a prick --- .../Library/PathExtensions.cs | 26 +++++-------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 41e64abf32..d9e20e19ac 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Text.RegularExpressions; namespace Emby.Server.Implementations.Library @@ -60,19 +61,11 @@ namespace Emby.Server.Implementations.Library /// , or is empty. public static bool TryReplaceSubPath(this string path, string subPath, string newSubPath, [NotNullWhen(true)] out string? newPath) { - if (string.IsNullOrWhiteSpace(path)) - { - throw new ArgumentNullException(nameof(path)); - } + newPath = null; - if (string.IsNullOrWhiteSpace(subPath)) + if (path.Length == 0 || subPath.Length == 0 || newSubPath.Length == 0 || subPath.Length > path.Length) { - throw new ArgumentNullException(nameof(subPath)); - } - - if (string.IsNullOrWhiteSpace(newSubPath)) - { - throw new ArgumentNullException(nameof(newSubPath)); + return false; } char oldDirectorySeparatorChar; @@ -91,15 +84,8 @@ namespace Emby.Server.Implementations.Library newDirectorySeparatorChar = '\\'; } - if (path.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) - { - path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); - } - - if (subPath.Contains(oldDirectorySeparatorChar, StringComparison.Ordinal)) - { - subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); - } + path = path.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); + subPath = subPath.Replace(oldDirectorySeparatorChar, newDirectorySeparatorChar); // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results // when the sub path matches a similar but in-complete subpath From 67af30d1ff41734215db4c64f777568c647c2ad3 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 6 Mar 2021 20:53:50 +0100 Subject: [PATCH 1217/1930] Remove redundant checks --- Emby.Server.Implementations/Library/LibraryManager.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 973b2df8ae..9a43405f45 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2783,11 +2783,6 @@ namespace Emby.Server.Implementations.Library { foreach (var pathInfo in libraryOptions.PathInfos) { - if (string.IsNullOrWhiteSpace(pathInfo.Path) || string.IsNullOrWhiteSpace(pathInfo.NetworkPath)) - { - continue; - } - if (path.TryReplaceSubPath(pathInfo.Path, pathInfo.NetworkPath, out var newPath)) { return newPath; @@ -2809,11 +2804,6 @@ namespace Emby.Server.Implementations.Library foreach (var map in _configurationManager.Configuration.PathSubstitutions) { - if (string.IsNullOrWhiteSpace(map.From)) - { - continue; - } - if (path.TryReplaceSubPath(map.From, map.To, out var newPath)) { return newPath; From 946411be8e85344ad4f33fb7ffb9a1666cf8e6be Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 6 Mar 2021 21:18:20 +0100 Subject: [PATCH 1218/1930] Remove redundant check --- .../Library/LibraryManager.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 9a43405f45..0957b8cf7a 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2776,6 +2776,7 @@ namespace Emby.Server.Implementations.Library public string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem) { + string newPath; if (ownerItem != null) { var libraryOptions = GetLibraryOptions(ownerItem); @@ -2783,7 +2784,7 @@ namespace Emby.Server.Implementations.Library { foreach (var pathInfo in libraryOptions.PathInfos) { - if (path.TryReplaceSubPath(pathInfo.Path, pathInfo.NetworkPath, out var newPath)) + if (path.TryReplaceSubPath(pathInfo.Path, pathInfo.NetworkPath, out newPath)) { return newPath; } @@ -2794,17 +2795,14 @@ namespace Emby.Server.Implementations.Library var metadataPath = _configurationManager.Configuration.MetadataPath; var metadataNetworkPath = _configurationManager.Configuration.MetadataNetworkPath; - if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath)) + if (path.TryReplaceSubPath(metadataPath, metadataNetworkPath, out newPath)) { - if (path.TryReplaceSubPath(metadataPath, metadataNetworkPath, out var newPath)) - { - return newPath; - } + return newPath; } foreach (var map in _configurationManager.Configuration.PathSubstitutions) { - if (path.TryReplaceSubPath(map.From, map.To, out var newPath)) + if (path.TryReplaceSubPath(map.From, map.To, out newPath)) { return newPath; } From 287dab4655176b09b0cd5b7607bfaff74e48d20d Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 6 Mar 2021 16:17:19 -0500 Subject: [PATCH 1219/1930] Remove constructor side effects and remove unneeded parameterless constructors --- Jellyfin.Data/Entities/AccessSchedule.cs | 9 ----- Jellyfin.Data/Entities/ActivityLog.cs | 13 +------ .../Entities/CustomItemDisplayPreferences.cs | 17 +++----- Jellyfin.Data/Entities/DisplayPreferences.cs | 7 ---- Jellyfin.Data/Entities/Group.cs | 10 ----- Jellyfin.Data/Entities/ImageInfo.cs | 10 ----- .../Entities/ItemDisplayPreferences.cs | 7 ---- Jellyfin.Data/Entities/Libraries/Artwork.cs | 15 +------ Jellyfin.Data/Entities/Libraries/Book.cs | 3 +- .../Entities/Libraries/BookMetadata.cs | 21 +--------- Jellyfin.Data/Entities/Libraries/Chapter.cs | 20 +--------- .../Entities/Libraries/CollectionItem.cs | 39 ------------------- Jellyfin.Data/Entities/Libraries/Company.cs | 15 +------ .../Entities/Libraries/CompanyMetadata.cs | 17 +------- .../Entities/Libraries/CustomItem.cs | 3 +- .../Entities/Libraries/CustomItemMetadata.cs | 19 +-------- Jellyfin.Data/Entities/Libraries/Episode.cs | 22 +---------- .../Entities/Libraries/EpisodeMetadata.cs | 20 +--------- Jellyfin.Data/Entities/Libraries/Genre.cs | 26 +------------ .../Entities/Libraries/ItemMetadata.cs | 10 ----- Jellyfin.Data/Entities/Libraries/Library.cs | 10 ----- .../Entities/Libraries/LibraryItem.cs | 7 ---- Jellyfin.Data/Entities/Libraries/MediaFile.cs | 20 +--------- .../Entities/Libraries/MediaFileStream.cs | 21 +--------- .../Entities/Libraries/MetadataProvider.cs | 10 ----- .../Entities/Libraries/MetadataProviderId.cs | 20 +--------- Jellyfin.Data/Entities/Libraries/Movie.cs | 3 +- .../Entities/Libraries/MovieMetadata.cs | 15 +------ .../Entities/Libraries/MusicAlbum.cs | 3 +- .../Entities/Libraries/MusicAlbumMetadata.cs | 15 +------ Jellyfin.Data/Entities/Libraries/Person.cs | 10 ----- .../Entities/Libraries/PersonRole.cs | 22 +---------- Jellyfin.Data/Entities/Libraries/Photo.cs | 3 +- .../Entities/Libraries/PhotoMetadata.cs | 21 +--------- Jellyfin.Data/Entities/Libraries/Rating.cs | 21 +--------- .../Entities/Libraries/RatingSource.cs | 21 +--------- Jellyfin.Data/Entities/Libraries/Release.cs | 15 +------ Jellyfin.Data/Entities/Libraries/Season.cs | 22 +---------- .../Entities/Libraries/SeasonMetadata.cs | 20 +--------- Jellyfin.Data/Entities/Libraries/Series.cs | 3 +- .../Entities/Libraries/SeriesMetadata.cs | 21 +--------- Jellyfin.Data/Entities/Libraries/Track.cs | 22 +---------- .../Entities/Libraries/TrackMetadata.cs | 21 +--------- Jellyfin.Data/Entities/Permission.cs | 8 ---- Jellyfin.Data/Entities/Preference.cs | 8 ---- Jellyfin.Data/Entities/User.cs | 8 ---- 46 files changed, 46 insertions(+), 627 deletions(-) diff --git a/Jellyfin.Data/Entities/AccessSchedule.cs b/Jellyfin.Data/Entities/AccessSchedule.cs index 7d1b76a3f8..72bca061da 100644 --- a/Jellyfin.Data/Entities/AccessSchedule.cs +++ b/Jellyfin.Data/Entities/AccessSchedule.cs @@ -1,7 +1,6 @@ using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -using System.Text.Json.Serialization; using System.Xml.Serialization; using Jellyfin.Data.Enums; @@ -27,14 +26,6 @@ namespace Jellyfin.Data.Entities EndHour = endHour; } - /// - /// Initializes a new instance of the class. - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected AccessSchedule() - { - } - /// /// Gets or sets the id of this instance. /// diff --git a/Jellyfin.Data/Entities/ActivityLog.cs b/Jellyfin.Data/Entities/ActivityLog.cs index e2d5c71879..80e32db30e 100644 --- a/Jellyfin.Data/Entities/ActivityLog.cs +++ b/Jellyfin.Data/Entities/ActivityLog.cs @@ -18,8 +18,7 @@ namespace Jellyfin.Data.Entities /// The name. /// The type. /// The user id. - /// The log level. - public ActivityLog(string name, string type, Guid userId, LogLevel logLevel = LogLevel.Information) + public ActivityLog(string name, string type, Guid userId) { if (string.IsNullOrEmpty(name)) { @@ -35,15 +34,7 @@ namespace Jellyfin.Data.Entities Type = type; UserId = userId; DateCreated = DateTime.UtcNow; - LogSeverity = logLevel; - } - - /// - /// Initializes a new instance of the class. - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected ActivityLog() - { + LogSeverity = LogLevel.Information; } /// diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs index 511e3b281a..d407180d46 100644 --- a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -15,22 +15,15 @@ namespace Jellyfin.Data.Entities /// The user id. /// The item id. /// The client. - /// The preference key. - /// The preference value. - public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string preferenceKey, string preferenceValue) + /// The preference key. + /// The preference value. + public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string key, string value) { UserId = userId; ItemId = itemId; Client = client; - Key = preferenceKey; - Value = preferenceValue; - } - - /// - /// Initializes a new instance of the class. - /// - protected CustomItemDisplayPreferences() - { + Key = key; + Value = value; } /// diff --git a/Jellyfin.Data/Entities/DisplayPreferences.cs b/Jellyfin.Data/Entities/DisplayPreferences.cs index 1a8ca1da37..d186deb293 100644 --- a/Jellyfin.Data/Entities/DisplayPreferences.cs +++ b/Jellyfin.Data/Entities/DisplayPreferences.cs @@ -36,13 +36,6 @@ namespace Jellyfin.Data.Entities HomeSections = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - protected DisplayPreferences() - { - } - /// /// Gets or sets the Id. /// diff --git a/Jellyfin.Data/Entities/Group.cs b/Jellyfin.Data/Entities/Group.cs index 878811e59c..8c45dde928 100644 --- a/Jellyfin.Data/Entities/Group.cs +++ b/Jellyfin.Data/Entities/Group.cs @@ -32,16 +32,6 @@ namespace Jellyfin.Data.Entities Preferences = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Group() - { - } - /// /// Gets or sets the id of this group. /// diff --git a/Jellyfin.Data/Entities/ImageInfo.cs b/Jellyfin.Data/Entities/ImageInfo.cs index ab8452e62c..f9ae1a955f 100644 --- a/Jellyfin.Data/Entities/ImageInfo.cs +++ b/Jellyfin.Data/Entities/ImageInfo.cs @@ -19,16 +19,6 @@ namespace Jellyfin.Data.Entities LastModified = DateTime.UtcNow; } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected ImageInfo() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs index 2b25bb25f2..f0a04f8ea6 100644 --- a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs @@ -28,13 +28,6 @@ namespace Jellyfin.Data.Entities RememberIndexing = false; } - /// - /// Initializes a new instance of the class. - /// - protected ItemDisplayPreferences() - { - } - /// /// Gets or sets the Id. /// diff --git a/Jellyfin.Data/Entities/Libraries/Artwork.cs b/Jellyfin.Data/Entities/Libraries/Artwork.cs index 06cd333301..df28ce7374 100644 --- a/Jellyfin.Data/Entities/Libraries/Artwork.cs +++ b/Jellyfin.Data/Entities/Libraries/Artwork.cs @@ -18,8 +18,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The path. /// The kind of art. - /// The owner. - public Artwork(string path, ArtKind kind, IHasArtwork owner) + public Artwork(string path, ArtKind kind) { if (string.IsNullOrEmpty(path)) { @@ -28,18 +27,6 @@ namespace Jellyfin.Data.Entities.Libraries Path = path; Kind = kind; - - owner?.Artwork.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Artwork() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/Book.cs b/Jellyfin.Data/Entities/Libraries/Book.cs index 2e63f75bd9..aea3d58d58 100644 --- a/Jellyfin.Data/Entities/Libraries/Book.cs +++ b/Jellyfin.Data/Entities/Libraries/Book.cs @@ -13,7 +13,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public Book() + /// The library. + public Book(Library library) : base(library) { BookMetadata = new HashSet(); Releases = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs index 4a3d290f01..8b0c965306 100644 --- a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -17,29 +16,11 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The book. - public BookMetadata(string title, string language, Book book) : base(title, language) + public BookMetadata(string title, string language) : base(title, language) { - if (book == null) - { - throw new ArgumentNullException(nameof(book)); - } - - book.BookMetadata.Add(this); - Publishers = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected BookMetadata() - { - } - /// /// Gets or sets the ISBN. /// diff --git a/Jellyfin.Data/Entities/Libraries/Chapter.cs b/Jellyfin.Data/Entities/Libraries/Chapter.cs index f503de3794..f253143d74 100644 --- a/Jellyfin.Data/Entities/Libraries/Chapter.cs +++ b/Jellyfin.Data/Entities/Libraries/Chapter.cs @@ -17,8 +17,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// ISO-639-3 3-character language codes. /// The start time for this chapter. - /// The release. - public Chapter(string language, long startTime, Release release) + public Chapter(string language, long startTime) { if (string.IsNullOrEmpty(language)) { @@ -27,23 +26,6 @@ namespace Jellyfin.Data.Entities.Libraries Language = language; StartTime = startTime; - - if (release == null) - { - throw new ArgumentNullException(nameof(release)); - } - - release.Chapters.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Chapter() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs index f9539964d0..1157de442b 100644 --- a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -10,44 +9,6 @@ namespace Jellyfin.Data.Entities.Libraries /// public class CollectionItem : IHasConcurrencyToken { - /// - /// Initializes a new instance of the class. - /// - /// The collection. - /// The previous item. - /// The next item. - public CollectionItem(Collection collection, CollectionItem previous, CollectionItem next) - { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - collection.Items.Add(this); - - if (next != null) - { - Next = next; - next.Previous = this; - } - - if (previous != null) - { - Previous = previous; - previous.Next = this; - } - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected CollectionItem() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/Company.cs b/Jellyfin.Data/Entities/Libraries/Company.cs index 3b6ed3309a..499ba3800a 100644 --- a/Jellyfin.Data/Entities/Libraries/Company.cs +++ b/Jellyfin.Data/Entities/Libraries/Company.cs @@ -15,24 +15,11 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - /// The owner of this company. - public Company(IHasCompanies owner) + public Company() { - owner?.Companies.Add(this); - CompanyMetadata = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Company() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs index 8aa0486afa..86642b38a5 100644 --- a/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; namespace Jellyfin.Data.Entities.Libraries @@ -13,21 +12,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The company. - public CompanyMetadata(string title, string language, Company company) : base(title, language) - { - if (company == null) - { - throw new ArgumentNullException(nameof(company)); - } - - company.CompanyMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - protected CompanyMetadata() + public CompanyMetadata(string title, string language) : base(title, language) { } diff --git a/Jellyfin.Data/Entities/Libraries/CustomItem.cs b/Jellyfin.Data/Entities/Libraries/CustomItem.cs index 115489c786..88d1a0c258 100644 --- a/Jellyfin.Data/Entities/Libraries/CustomItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CustomItem.cs @@ -13,7 +13,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public CustomItem() + /// The library. + public CustomItem(Library library) : base(library) { CustomItemMetadata = new HashSet(); Releases = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs index f0daedfbe8..a69a8eafa4 100644 --- a/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs @@ -12,24 +12,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The item. - public CustomItemMetadata(string title, string language, CustomItem item) : base(title, language) - { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - item.CustomItemMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected CustomItemMetadata() + public CustomItemMetadata(string title, string language) : base(title, language) { } } diff --git a/Jellyfin.Data/Entities/Libraries/Episode.cs b/Jellyfin.Data/Entities/Libraries/Episode.cs index 0bdc2d7642..458c7d9f5a 100644 --- a/Jellyfin.Data/Entities/Libraries/Episode.cs +++ b/Jellyfin.Data/Entities/Libraries/Episode.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -14,30 +13,13 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - /// The season. - public Episode(Season season) + /// The library. + public Episode(Library library) : base(library) { - if (season == null) - { - throw new ArgumentNullException(nameof(season)); - } - - season.Episodes.Add(this); - Releases = new HashSet(); EpisodeMetadata = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Episode() - { - } - /// /// Gets or sets the episode number. /// diff --git a/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs index 7efb840f0b..5662decdb8 100644 --- a/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; namespace Jellyfin.Data.Entities.Libraries @@ -13,24 +12,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The episode. - public EpisodeMetadata(string title, string language, Episode episode) : base(title, language) - { - if (episode == null) - { - throw new ArgumentNullException(nameof(episode)); - } - - episode.EpisodeMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected EpisodeMetadata() + public EpisodeMetadata(string title, string language) : base(title, language) { } diff --git a/Jellyfin.Data/Entities/Libraries/Genre.cs b/Jellyfin.Data/Entities/Libraries/Genre.cs index 2a2dbd1a5d..befa75550a 100644 --- a/Jellyfin.Data/Entities/Libraries/Genre.cs +++ b/Jellyfin.Data/Entities/Libraries/Genre.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -14,32 +13,9 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The name. - /// The metadata. - public Genre(string name, ItemMetadata itemMetadata) + public Genre(string name) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentNullException(nameof(name)); - } - Name = name; - - if (itemMetadata == null) - { - throw new ArgumentNullException(nameof(itemMetadata)); - } - - itemMetadata.Genres.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Genre() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs index d74330c051..a0efa66e46 100644 --- a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs @@ -42,16 +42,6 @@ namespace Jellyfin.Data.Entities.Libraries Sources = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to being abstract. - /// - protected ItemMetadata() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/Library.cs b/Jellyfin.Data/Entities/Libraries/Library.cs index 4f82a2e2a7..3ec4341a48 100644 --- a/Jellyfin.Data/Entities/Libraries/Library.cs +++ b/Jellyfin.Data/Entities/Libraries/Library.cs @@ -24,16 +24,6 @@ namespace Jellyfin.Data.Entities.Libraries Name = name; } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Library() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs index a9167aa7fd..504b9c853b 100644 --- a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs +++ b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs @@ -20,13 +20,6 @@ namespace Jellyfin.Data.Entities.Libraries Library = library; } - /// - /// Initializes a new instance of the class. - /// - protected LibraryItem() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/MediaFile.cs b/Jellyfin.Data/Entities/Libraries/MediaFile.cs index 9924d5728d..7f64978e24 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFile.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFile.cs @@ -19,8 +19,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The path relative to the LibraryRoot. /// The file kind. - /// The release. - public MediaFile(string path, MediaFileKind kind, Release release) + public MediaFile(string path, MediaFileKind kind) { if (string.IsNullOrEmpty(path)) { @@ -30,26 +29,9 @@ namespace Jellyfin.Data.Entities.Libraries Path = path; Kind = kind; - if (release == null) - { - throw new ArgumentNullException(nameof(release)); - } - - release.MediaFiles.Add(this); - MediaFileStreams = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MediaFile() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs index 5b03e260e2..c4468766f9 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -14,27 +13,9 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The number of this stream. - /// The media file. - public MediaFileStream(int streamNumber, MediaFile mediaFile) + public MediaFileStream(int streamNumber) { StreamNumber = streamNumber; - - if (mediaFile == null) - { - throw new ArgumentNullException(nameof(mediaFile)); - } - - mediaFile.MediaFileStreams.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MediaFileStream() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs index a18a612bcd..20de5bf4bb 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs @@ -24,16 +24,6 @@ namespace Jellyfin.Data.Entities.Libraries Name = name; } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MetadataProvider() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs index fcfb35bfac..12672dd25b 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs @@ -14,8 +14,7 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The provider id. - /// The metadata entity. - public MetadataProviderId(string providerId, ItemMetadata itemMetadata) + public MetadataProviderId(string providerId) { if (string.IsNullOrEmpty(providerId)) { @@ -23,23 +22,6 @@ namespace Jellyfin.Data.Entities.Libraries } ProviderId = providerId; - - if (itemMetadata == null) - { - throw new ArgumentNullException(nameof(itemMetadata)); - } - - itemMetadata.Sources.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MetadataProviderId() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/Movie.cs b/Jellyfin.Data/Entities/Libraries/Movie.cs index 08db904fa8..f89cacff44 100644 --- a/Jellyfin.Data/Entities/Libraries/Movie.cs +++ b/Jellyfin.Data/Entities/Libraries/Movie.cs @@ -13,7 +13,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public Movie() + /// The library. + public Movie(Library library) : base(library) { Releases = new HashSet(); MovieMetadata = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs index aa1501a5cc..8cf7ca6a7f 100644 --- a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs @@ -17,22 +17,9 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the movie. /// ISO-639-3 3-character language codes. - /// The movie. - public MovieMetadata(string title, string language, Movie movie) : base(title, language) + public MovieMetadata(string title, string language) : base(title, language) { Studios = new HashSet(); - - movie.MovieMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MovieMetadata() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs index 06aff6f457..4049cdac8e 100644 --- a/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs +++ b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs @@ -12,7 +12,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public MusicAlbum() + /// The library. + public MusicAlbum(Library library) : base(library) { MusicAlbumMetadata = new HashSet(); Tracks = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs index 05c0b0374b..9e44e550af 100644 --- a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs @@ -15,22 +15,9 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the album. /// ISO-639-3 3-character language codes. - /// The music album. - public MusicAlbumMetadata(string title, string language, MusicAlbum album) : base(title, language) + public MusicAlbumMetadata(string title, string language) : base(title, language) { Labels = new HashSet(); - - album.MusicAlbumMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected MusicAlbumMetadata() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/Person.cs b/Jellyfin.Data/Entities/Libraries/Person.cs index af4c87b73c..cc4b9e0f9f 100644 --- a/Jellyfin.Data/Entities/Libraries/Person.cs +++ b/Jellyfin.Data/Entities/Libraries/Person.cs @@ -31,16 +31,6 @@ namespace Jellyfin.Data.Entities.Libraries Sources = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Person() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/PersonRole.cs b/Jellyfin.Data/Entities/Libraries/PersonRole.cs index cd38ee83d0..3ae2e4a685 100644 --- a/Jellyfin.Data/Entities/Libraries/PersonRole.cs +++ b/Jellyfin.Data/Entities/Libraries/PersonRole.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -18,31 +17,12 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The role type. - /// The metadata. - public PersonRole(PersonRoleType type, ItemMetadata itemMetadata) + public PersonRole(PersonRoleType type) { Type = type; - - if (itemMetadata == null) - { - throw new ArgumentNullException(nameof(itemMetadata)); - } - - itemMetadata.PersonRoles.Add(this); - Sources = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected PersonRole() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/Photo.cs b/Jellyfin.Data/Entities/Libraries/Photo.cs index 25562ec96f..eb5c962675 100644 --- a/Jellyfin.Data/Entities/Libraries/Photo.cs +++ b/Jellyfin.Data/Entities/Libraries/Photo.cs @@ -13,7 +13,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public Photo() + /// The library. + public Photo(Library library) : base(library) { PhotoMetadata = new HashSet(); Releases = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs b/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs index ffc790b574..6c284307d7 100644 --- a/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/PhotoMetadata.cs @@ -1,5 +1,3 @@ -using System; - namespace Jellyfin.Data.Entities.Libraries { /// @@ -12,24 +10,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the photo. /// ISO-639-3 3-character language codes. - /// The photo. - public PhotoMetadata(string title, string language, Photo photo) : base(title, language) - { - if (photo == null) - { - throw new ArgumentNullException(nameof(photo)); - } - - photo.PhotoMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected PhotoMetadata() + public PhotoMetadata(string title, string language) : base(title, language) { } } diff --git a/Jellyfin.Data/Entities/Libraries/Rating.cs b/Jellyfin.Data/Entities/Libraries/Rating.cs index 98226cd802..0ea933fd79 100644 --- a/Jellyfin.Data/Entities/Libraries/Rating.cs +++ b/Jellyfin.Data/Entities/Libraries/Rating.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -14,27 +13,9 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The value. - /// The metadata. - public Rating(double value, ItemMetadata itemMetadata) + public Rating(double value) { Value = value; - - if (itemMetadata == null) - { - throw new ArgumentNullException(nameof(itemMetadata)); - } - - itemMetadata.Ratings.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Rating() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/RatingSource.cs b/Jellyfin.Data/Entities/Libraries/RatingSource.cs index 549f418042..7e1a5a8f46 100644 --- a/Jellyfin.Data/Entities/Libraries/RatingSource.cs +++ b/Jellyfin.Data/Entities/Libraries/RatingSource.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -15,28 +14,10 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The minimum value. /// The maximum value. - /// The rating. - public RatingSource(double minimumValue, double maximumValue, Rating rating) + public RatingSource(double minimumValue, double maximumValue) { MinimumValue = minimumValue; MaximumValue = maximumValue; - - if (rating == null) - { - throw new ArgumentNullException(nameof(rating)); - } - - rating.RatingType = this; - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected RatingSource() - { } /// diff --git a/Jellyfin.Data/Entities/Libraries/Release.cs b/Jellyfin.Data/Entities/Libraries/Release.cs index b633e08fb3..1871e0f10b 100644 --- a/Jellyfin.Data/Entities/Libraries/Release.cs +++ b/Jellyfin.Data/Entities/Libraries/Release.cs @@ -17,8 +17,7 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The name of this release. - /// The owner of this release. - public Release(string name, IHasReleases owner) + public Release(string name) { if (string.IsNullOrEmpty(name)) { @@ -27,22 +26,10 @@ namespace Jellyfin.Data.Entities.Libraries Name = name; - owner?.Releases.Add(this); - MediaFiles = new HashSet(); Chapters = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Release() - { - } - /// /// Gets or sets the id. /// diff --git a/Jellyfin.Data/Entities/Libraries/Season.cs b/Jellyfin.Data/Entities/Libraries/Season.cs index eb6674dbc3..04f723a1d1 100644 --- a/Jellyfin.Data/Entities/Libraries/Season.cs +++ b/Jellyfin.Data/Entities/Libraries/Season.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; namespace Jellyfin.Data.Entities.Libraries @@ -13,30 +12,13 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - /// The series. - public Season(Series series) + /// The library. + public Season(Library library) : base(library) { - if (series == null) - { - throw new ArgumentNullException(nameof(series)); - } - - series.Seasons.Add(this); - Episodes = new HashSet(); SeasonMetadata = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Season() - { - } - /// /// Gets or sets the season number. /// diff --git a/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs index 7ce79756b2..61714f9095 100644 --- a/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; namespace Jellyfin.Data.Entities.Libraries @@ -13,24 +12,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The season. - public SeasonMetadata(string title, string language, Season season) : base(title, language) - { - if (season == null) - { - throw new ArgumentNullException(nameof(season)); - } - - season.SeasonMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected SeasonMetadata() + public SeasonMetadata(string title, string language) : base(title, language) { } diff --git a/Jellyfin.Data/Entities/Libraries/Series.cs b/Jellyfin.Data/Entities/Libraries/Series.cs index 8c8317d14b..59508831e4 100644 --- a/Jellyfin.Data/Entities/Libraries/Series.cs +++ b/Jellyfin.Data/Entities/Libraries/Series.cs @@ -13,7 +13,8 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - public Series() + /// The library. + public Series(Library library) : base(library) { DateAdded = DateTime.UtcNow; Seasons = new HashSet(); diff --git a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs index 877dbfc69c..e1acd2d457 100644 --- a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -18,29 +17,11 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The series. - public SeriesMetadata(string title, string language, Series series) : base(title, language) + public SeriesMetadata(string title, string language) : base(title, language) { - if (series == null) - { - throw new ArgumentNullException(nameof(series)); - } - - series.SeriesMetadata.Add(this); - Networks = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected SeriesMetadata() - { - } - /// /// Gets or sets the outline. /// diff --git a/Jellyfin.Data/Entities/Libraries/Track.cs b/Jellyfin.Data/Entities/Libraries/Track.cs index 782bfb5ce7..86a3edff83 100644 --- a/Jellyfin.Data/Entities/Libraries/Track.cs +++ b/Jellyfin.Data/Entities/Libraries/Track.cs @@ -1,6 +1,5 @@ #pragma warning disable CA2227 -using System; using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -14,30 +13,13 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Initializes a new instance of the class. /// - /// The album. - public Track(MusicAlbum album) + /// The library. + public Track(Library library) : base(library) { - if (album == null) - { - throw new ArgumentNullException(nameof(album)); - } - - album.Tracks.Add(this); - Releases = new HashSet(); TrackMetadata = new HashSet(); } - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Track() - { - } - /// /// Gets or sets the track number. /// diff --git a/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs b/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs index 321f93bf2e..042d2b90db 100644 --- a/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/TrackMetadata.cs @@ -1,5 +1,3 @@ -using System; - namespace Jellyfin.Data.Entities.Libraries { /// @@ -12,24 +10,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// The title or name of the object. /// ISO-639-3 3-character language codes. - /// The track. - public TrackMetadata(string title, string language, Track track) : base(title, language) - { - if (track == null) - { - throw new ArgumentNullException(nameof(track)); - } - - track.TrackMetadata.Add(this); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected TrackMetadata() + public TrackMetadata(string title, string language) : base(title, language) { } } diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs index d92e5d9d25..17e3bf50e1 100644 --- a/Jellyfin.Data/Entities/Permission.cs +++ b/Jellyfin.Data/Entities/Permission.cs @@ -22,14 +22,6 @@ namespace Jellyfin.Data.Entities Value = value; } - /// - /// Initializes a new instance of the class. - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Permission() - { - } - /// /// Gets or sets the id of this permission. /// diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs index 4efddf2a41..40f2f8ede9 100644 --- a/Jellyfin.Data/Entities/Preference.cs +++ b/Jellyfin.Data/Entities/Preference.cs @@ -23,14 +23,6 @@ namespace Jellyfin.Data.Entities Value = value ?? throw new ArgumentNullException(nameof(value)); } - /// - /// Initializes a new instance of the class. - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected Preference() - { - } - /// /// Gets or sets the id of this preference. /// diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 362f3b4ebb..28e12adde6 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -77,14 +77,6 @@ namespace Jellyfin.Data.Entities AddDefaultPreferences(); } - /// - /// Initializes a new instance of the class. - /// Default constructor. Protected due to required properties, but present because EF needs it. - /// - protected User() - { - } - /// /// Gets or sets the Id of the user. /// From f638ee6b0918c2ef05ec11cfa43584d3efad68d1 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 6 Mar 2021 17:43:01 -0500 Subject: [PATCH 1220/1930] Enable nullable for Jellyfin.Data and remove unnecessary attributes --- Emby.Drawing/ImageProcessor.cs | 7 ++++++- Jellyfin.Api/Controllers/ImageController.cs | 12 +++++++++++- Jellyfin.Api/Controllers/StartupController.cs | 5 ++++- Jellyfin.Data/Entities/AccessSchedule.cs | 7 ------- Jellyfin.Data/Entities/ActivityLog.cs | 8 +++----- .../Entities/CustomItemDisplayPreferences.cs | 3 --- Jellyfin.Data/Entities/DisplayPreferences.cs | 7 ++----- Jellyfin.Data/Entities/Group.cs | 1 - Jellyfin.Data/Entities/HomeSection.cs | 1 - Jellyfin.Data/Entities/ImageInfo.cs | 1 - .../Entities/ItemDisplayPreferences.cs | 2 -- Jellyfin.Data/Entities/Libraries/Artwork.cs | 1 - .../Entities/Libraries/BookMetadata.cs | 2 -- Jellyfin.Data/Entities/Libraries/Chapter.cs | 3 +-- Jellyfin.Data/Entities/Libraries/Collection.cs | 2 +- .../Entities/Libraries/CollectionItem.cs | 13 +++++++++++-- Jellyfin.Data/Entities/Libraries/Company.cs | 2 +- .../Entities/Libraries/CompanyMetadata.cs | 8 ++++---- .../Entities/Libraries/CustomItemMetadata.cs | 2 -- .../Entities/Libraries/EpisodeMetadata.cs | 6 +++--- Jellyfin.Data/Entities/Libraries/Genre.cs | 1 - .../Entities/Libraries/ItemMetadata.cs | 6 ++---- Jellyfin.Data/Entities/Libraries/Library.cs | 12 +++--------- Jellyfin.Data/Entities/Libraries/LibraryItem.cs | 1 - Jellyfin.Data/Entities/Libraries/MediaFile.cs | 1 - .../Entities/Libraries/MetadataProvider.cs | 1 - .../Entities/Libraries/MetadataProviderId.cs | 5 +++-- .../Entities/Libraries/MovieMetadata.cs | 10 ++++------ .../Entities/Libraries/MusicAlbumMetadata.cs | 6 +++--- Jellyfin.Data/Entities/Libraries/Person.cs | 3 +-- Jellyfin.Data/Entities/Libraries/PersonRole.cs | 8 +++++--- Jellyfin.Data/Entities/Libraries/Rating.cs | 2 +- .../Entities/Libraries/RatingSource.cs | 4 ++-- Jellyfin.Data/Entities/Libraries/Release.cs | 1 - .../Entities/Libraries/SeasonMetadata.cs | 2 +- .../Entities/Libraries/SeriesMetadata.cs | 9 ++++----- Jellyfin.Data/Entities/Preference.cs | 1 - Jellyfin.Data/Entities/User.cs | 17 +++++++---------- Jellyfin.Data/Jellyfin.Data.csproj | 1 + .../Consumers/Session/PlaybackStartLogger.cs | 4 ++-- .../Users/UserManager.cs | 6 +++--- .../Migrations/Routines/MigrateUserDb.cs | 4 +--- .../Drawing/IImageProcessor.cs | 2 +- tests/Jellyfin.Api.Tests/TestHelpers.cs | 4 ++-- 44 files changed, 93 insertions(+), 111 deletions(-) diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 8a2301d2d6..aa8a3d212a 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -352,8 +352,13 @@ namespace Emby.Drawing } /// - public string GetImageCacheTag(User user) + public string? GetImageCacheTag(User user) { + if (user.ProfileImage == null) + { + return null; + } + return (user.ProfileImage.Path + user.ProfileImage.LastModified.Ticks).GetMD5() .ToString("N", CultureInfo.InvariantCulture); } diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index a50d6e46bf..b016f24500 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -196,6 +196,11 @@ namespace Jellyfin.Api.Controllers } var user = _userManager.GetUserById(userId); + if (user?.ProfileImage == null) + { + return NoContent(); + } + try { System.IO.File.Delete(user.ProfileImage.Path); @@ -235,6 +240,11 @@ namespace Jellyfin.Api.Controllers } var user = _userManager.GetUserById(userId); + if (user?.ProfileImage == null) + { + return NoContent(); + } + try { System.IO.File.Delete(user.ProfileImage.Path); @@ -1469,7 +1479,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageIndex) { var user = _userManager.GetUserById(userId); - if (user == null) + if (user?.ProfileImage == null) { return NotFound(); } diff --git a/Jellyfin.Api/Controllers/StartupController.cs b/Jellyfin.Api/Controllers/StartupController.cs index d9cb34557b..a01a617fc0 100644 --- a/Jellyfin.Api/Controllers/StartupController.cs +++ b/Jellyfin.Api/Controllers/StartupController.cs @@ -132,7 +132,10 @@ namespace Jellyfin.Api.Controllers { var user = _userManager.Users.First(); - user.Username = startupUserDto.Name; + if (startupUserDto.Name != null) + { + user.Username = startupUserDto.Name; + } await _userManager.UpdateUserAsync(user).ConfigureAwait(false); diff --git a/Jellyfin.Data/Entities/AccessSchedule.cs b/Jellyfin.Data/Entities/AccessSchedule.cs index 72bca061da..9ac0666ac3 100644 --- a/Jellyfin.Data/Entities/AccessSchedule.cs +++ b/Jellyfin.Data/Entities/AccessSchedule.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Xml.Serialization; using Jellyfin.Data.Enums; @@ -33,8 +32,6 @@ namespace Jellyfin.Data.Entities /// Identity, Indexed, Required. /// [XmlIgnore] - [Key] - [Required] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; protected set; } @@ -42,28 +39,24 @@ namespace Jellyfin.Data.Entities /// Gets or sets the id of the associated user. /// [XmlIgnore] - [Required] public Guid UserId { get; protected set; } /// /// Gets or sets the day of week. /// /// The day of week. - [Required] public DynamicDayOfWeek DayOfWeek { get; set; } /// /// Gets or sets the start hour. /// /// The start hour. - [Required] public double StartHour { get; set; } /// /// Gets or sets the end hour. /// /// The end hour. - [Required] public double EndHour { get; set; } /// diff --git a/Jellyfin.Data/Entities/ActivityLog.cs b/Jellyfin.Data/Entities/ActivityLog.cs index 80e32db30e..e4534e8b5e 100644 --- a/Jellyfin.Data/Entities/ActivityLog.cs +++ b/Jellyfin.Data/Entities/ActivityLog.cs @@ -50,7 +50,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 512. /// - [Required] [MaxLength(512)] [StringLength(512)] public string Name { get; set; } @@ -63,7 +62,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(512)] [StringLength(512)] - public string Overview { get; set; } + public string? Overview { get; set; } /// /// Gets or sets the short overview. @@ -73,7 +72,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(512)] [StringLength(512)] - public string ShortOverview { get; set; } + public string? ShortOverview { get; set; } /// /// Gets or sets the type. @@ -81,7 +80,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 256. /// - [Required] [MaxLength(256)] [StringLength(256)] public string Type { get; set; } @@ -102,7 +100,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(256)] [StringLength(256)] - public string ItemId { get; set; } + public string? ItemId { get; set; } /// /// Gets or sets the date created. This should be in UTC. diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs index d407180d46..cc46248c75 100644 --- a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -57,7 +57,6 @@ namespace Jellyfin.Data.Entities /// /// Required. Max Length = 32. /// - [Required] [MaxLength(32)] [StringLength(32)] public string Client { get; set; } @@ -68,7 +67,6 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - [Required] public string Key { get; set; } /// @@ -77,7 +75,6 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - [Required] public string Value { get; set; } } } diff --git a/Jellyfin.Data/Entities/DisplayPreferences.cs b/Jellyfin.Data/Entities/DisplayPreferences.cs index d186deb293..64cd6812a4 100644 --- a/Jellyfin.Data/Entities/DisplayPreferences.cs +++ b/Jellyfin.Data/Entities/DisplayPreferences.cs @@ -30,8 +30,6 @@ namespace Jellyfin.Data.Entities SkipBackwardLength = 10000; ScrollDirection = ScrollDirection.Horizontal; ChromecastVersion = ChromecastVersion.Stable; - DashboardTheme = string.Empty; - TvHome = string.Empty; HomeSections = new HashSet(); } @@ -67,7 +65,6 @@ namespace Jellyfin.Data.Entities /// /// Required. Max Length = 32. /// - [Required] [MaxLength(32)] [StringLength(32)] public string Client { get; set; } @@ -138,14 +135,14 @@ namespace Jellyfin.Data.Entities /// [MaxLength(32)] [StringLength(32)] - public string DashboardTheme { get; set; } + public string? DashboardTheme { get; set; } /// /// Gets or sets the tv home screen. /// [MaxLength(32)] [StringLength(32)] - public string TvHome { get; set; } + public string? TvHome { get; set; } /// /// Gets or sets the home sections. diff --git a/Jellyfin.Data/Entities/Group.cs b/Jellyfin.Data/Entities/Group.cs index 8c45dde928..b14e22b7b3 100644 --- a/Jellyfin.Data/Entities/Group.cs +++ b/Jellyfin.Data/Entities/Group.cs @@ -46,7 +46,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string Name { get; set; } diff --git a/Jellyfin.Data/Entities/HomeSection.cs b/Jellyfin.Data/Entities/HomeSection.cs index 0620462602..5adc52491c 100644 --- a/Jellyfin.Data/Entities/HomeSection.cs +++ b/Jellyfin.Data/Entities/HomeSection.cs @@ -15,7 +15,6 @@ namespace Jellyfin.Data.Entities /// /// Identity. Required. /// - [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; protected set; } diff --git a/Jellyfin.Data/Entities/ImageInfo.cs b/Jellyfin.Data/Entities/ImageInfo.cs index f9ae1a955f..e0c37047d8 100644 --- a/Jellyfin.Data/Entities/ImageInfo.cs +++ b/Jellyfin.Data/Entities/ImageInfo.cs @@ -39,7 +39,6 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - [Required] [MaxLength(512)] [StringLength(512)] public string Path { get; set; } diff --git a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs index f0a04f8ea6..4bfeb2fa30 100644 --- a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs @@ -59,7 +59,6 @@ namespace Jellyfin.Data.Entities /// /// Required. Max Length = 32. /// - [Required] [MaxLength(32)] [StringLength(32)] public string Client { get; set; } @@ -99,7 +98,6 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - [Required] [MaxLength(64)] [StringLength(64)] public string SortBy { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/Artwork.cs b/Jellyfin.Data/Entities/Libraries/Artwork.cs index df28ce7374..84a524de2c 100644 --- a/Jellyfin.Data/Entities/Libraries/Artwork.cs +++ b/Jellyfin.Data/Entities/Libraries/Artwork.cs @@ -44,7 +44,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 65535. /// - [Required] [MaxLength(65535)] [StringLength(65535)] public string Path { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs index 8b0c965306..1ff4327b01 100644 --- a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs @@ -1,7 +1,6 @@ #pragma warning disable CA2227 using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; namespace Jellyfin.Data.Entities.Libraries @@ -32,7 +31,6 @@ namespace Jellyfin.Data.Entities.Libraries public virtual ICollection Publishers { get; protected set; } /// - [NotMapped] public ICollection Companies => Publishers; } } diff --git a/Jellyfin.Data/Entities/Libraries/Chapter.cs b/Jellyfin.Data/Entities/Libraries/Chapter.cs index f253143d74..11f53ae20a 100644 --- a/Jellyfin.Data/Entities/Libraries/Chapter.cs +++ b/Jellyfin.Data/Entities/Libraries/Chapter.cs @@ -45,7 +45,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the language. @@ -54,7 +54,6 @@ namespace Jellyfin.Data.Entities.Libraries /// Required, Min length = 3, Max length = 3 /// ISO-639-3 3-character language codes. /// - [Required] [MinLength(3)] [MaxLength(3)] [StringLength(3)] diff --git a/Jellyfin.Data/Entities/Libraries/Collection.cs b/Jellyfin.Data/Entities/Libraries/Collection.cs index 39eded752d..d230eeb2fe 100644 --- a/Jellyfin.Data/Entities/Libraries/Collection.cs +++ b/Jellyfin.Data/Entities/Libraries/Collection.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Name { get; set; } + public string? Name { get; set; } /// [ConcurrencyCheck] diff --git a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs index 1157de442b..e19362bdf1 100644 --- a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs @@ -9,6 +9,15 @@ namespace Jellyfin.Data.Entities.Libraries /// public class CollectionItem : IHasConcurrencyToken { + /// + /// Initializes a new instance of the class. + /// + /// The library item. + public CollectionItem(LibraryItem libraryItem) + { + LibraryItem = libraryItem; + } + /// /// Gets or sets the id. /// @@ -36,7 +45,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// TODO check if this properly updated Dependant and has the proper principal relationship. /// - public virtual CollectionItem Next { get; set; } + public virtual CollectionItem? Next { get; set; } /// /// Gets or sets the previous item in the collection. @@ -44,7 +53,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// TODO check if this properly updated Dependant and has the proper principal relationship. /// - public virtual CollectionItem Previous { get; set; } + public virtual CollectionItem? Previous { get; set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Company.cs b/Jellyfin.Data/Entities/Libraries/Company.cs index 499ba3800a..09050bb522 100644 --- a/Jellyfin.Data/Entities/Libraries/Company.cs +++ b/Jellyfin.Data/Entities/Libraries/Company.cs @@ -18,6 +18,7 @@ namespace Jellyfin.Data.Entities.Libraries public Company() { CompanyMetadata = new HashSet(); + ChildCompanies = new HashSet(); } /// @@ -44,7 +45,6 @@ namespace Jellyfin.Data.Entities.Libraries public virtual ICollection ChildCompanies { get; protected set; } /// - [NotMapped] public ICollection Companies => ChildCompanies; /// diff --git a/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs index 86642b38a5..a29f08c7f6 100644 --- a/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/CompanyMetadata.cs @@ -24,7 +24,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(65535)] [StringLength(65535)] - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the headquarters. @@ -34,7 +34,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(255)] [StringLength(255)] - public string Headquarters { get; set; } + public string? Headquarters { get; set; } /// /// Gets or sets the country code. @@ -44,7 +44,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(2)] [StringLength(2)] - public string Country { get; set; } + public string? Country { get; set; } /// /// Gets or sets the homepage. @@ -54,6 +54,6 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Homepage { get; set; } + public string? Homepage { get; set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs index a69a8eafa4..af2393870f 100644 --- a/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/CustomItemMetadata.cs @@ -1,5 +1,3 @@ -using System; - namespace Jellyfin.Data.Entities.Libraries { /// diff --git a/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs index 5662decdb8..b0ef11e0f2 100644 --- a/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/EpisodeMetadata.cs @@ -24,7 +24,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Outline { get; set; } + public string? Outline { get; set; } /// /// Gets or sets the plot. @@ -34,7 +34,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(65535)] [StringLength(65535)] - public string Plot { get; set; } + public string? Plot { get; set; } /// /// Gets or sets the tagline. @@ -44,6 +44,6 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Tagline { get; set; } + public string? Tagline { get; set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Genre.cs b/Jellyfin.Data/Entities/Libraries/Genre.cs index befa75550a..9f3d650283 100644 --- a/Jellyfin.Data/Entities/Libraries/Genre.cs +++ b/Jellyfin.Data/Entities/Libraries/Genre.cs @@ -33,7 +33,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Indexed, Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string Name { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs index a0efa66e46..d12e011a8b 100644 --- a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs @@ -57,7 +57,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 1024. /// - [Required] [MaxLength(1024)] [StringLength(1024)] public string Title { get; set; } @@ -70,7 +69,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string OriginalTitle { get; set; } + public string? OriginalTitle { get; set; } /// /// Gets or sets the sort title. @@ -80,7 +79,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string SortTitle { get; set; } + public string? SortTitle { get; set; } /// /// Gets or sets the language. @@ -89,7 +88,6 @@ namespace Jellyfin.Data.Entities.Libraries /// Required, Min length = 3, Max length = 3. /// ISO-639-3 3-character language codes. /// - [Required] [MinLength(3)] [MaxLength(3)] [StringLength(3)] diff --git a/Jellyfin.Data/Entities/Libraries/Library.cs b/Jellyfin.Data/Entities/Libraries/Library.cs index 3ec4341a48..e453849020 100644 --- a/Jellyfin.Data/Entities/Libraries/Library.cs +++ b/Jellyfin.Data/Entities/Libraries/Library.cs @@ -1,4 +1,3 @@ -using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; @@ -14,14 +13,11 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The name of the library. - public Library(string name) + /// The path of the library. + public Library(string name, string path) { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentNullException(nameof(name)); - } - Name = name; + Path = path; } /// @@ -39,7 +35,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 128. /// - [Required] [MaxLength(128)] [StringLength(128)] public string Name { get; set; } @@ -50,7 +45,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required. /// - [Required] public string Path { get; set; } /// diff --git a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs index 504b9c853b..67ffad944b 100644 --- a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs +++ b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs @@ -44,7 +44,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required. /// - [Required] public virtual Library Library { get; set; } /// diff --git a/Jellyfin.Data/Entities/Libraries/MediaFile.cs b/Jellyfin.Data/Entities/Libraries/MediaFile.cs index 7f64978e24..f3e2fe6539 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFile.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFile.cs @@ -47,7 +47,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 65535. /// - [Required] [MaxLength(65535)] [StringLength(65535)] public string Path { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs index 20de5bf4bb..fb2587882d 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs @@ -39,7 +39,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 1024. /// - [Required] [MaxLength(1024)] [StringLength(1024)] public string Name { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs index 12672dd25b..2a9c904c88 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs @@ -14,7 +14,8 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The provider id. - public MetadataProviderId(string providerId) + /// The metadata provider. + public MetadataProviderId(string providerId, MetadataProvider metadataProvider) { if (string.IsNullOrEmpty(providerId)) { @@ -22,6 +23,7 @@ namespace Jellyfin.Data.Entities.Libraries } ProviderId = providerId; + MetadataProvider = metadataProvider; } /// @@ -39,7 +41,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string ProviderId { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs index 8cf7ca6a7f..fb181dea60 100644 --- a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; namespace Jellyfin.Data.Entities.Libraries @@ -30,7 +29,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Outline { get; set; } + public string? Outline { get; set; } /// /// Gets or sets the tagline. @@ -40,7 +39,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Tagline { get; set; } + public string? Tagline { get; set; } /// /// Gets or sets the plot. @@ -50,7 +49,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(65535)] [StringLength(65535)] - public string Plot { get; set; } + public string? Plot { get; set; } /// /// Gets or sets the country code. @@ -60,7 +59,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(2)] [StringLength(2)] - public string Country { get; set; } + public string? Country { get; set; } /// /// Gets or sets the studios that produced this movie. @@ -68,7 +67,6 @@ namespace Jellyfin.Data.Entities.Libraries public virtual ICollection Studios { get; protected set; } /// - [NotMapped] public ICollection Companies => Studios; } } diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs index 9e44e550af..3080bd692d 100644 --- a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs @@ -28,7 +28,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(255)] [StringLength(255)] - public string Barcode { get; set; } + public string? Barcode { get; set; } /// /// Gets or sets the label number. @@ -38,7 +38,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(255)] [StringLength(255)] - public string LabelNumber { get; set; } + public string? LabelNumber { get; set; } /// /// Gets or sets the country code. @@ -48,7 +48,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(2)] [StringLength(2)] - public string Country { get; set; } + public string? Country { get; set; } /// /// Gets or sets a collection containing the labels. diff --git a/Jellyfin.Data/Entities/Libraries/Person.cs b/Jellyfin.Data/Entities/Libraries/Person.cs index cc4b9e0f9f..159bd47be7 100644 --- a/Jellyfin.Data/Entities/Libraries/Person.cs +++ b/Jellyfin.Data/Entities/Libraries/Person.cs @@ -46,7 +46,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 1024. /// - [Required] [MaxLength(1024)] [StringLength(1024)] public string Name { get; set; } @@ -59,7 +58,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(256)] [StringLength(256)] - public string SourceId { get; set; } + public string? SourceId { get; set; } /// /// Gets or sets the date added. diff --git a/Jellyfin.Data/Entities/Libraries/PersonRole.cs b/Jellyfin.Data/Entities/Libraries/PersonRole.cs index 3ae2e4a685..988aa84bae 100644 --- a/Jellyfin.Data/Entities/Libraries/PersonRole.cs +++ b/Jellyfin.Data/Entities/Libraries/PersonRole.cs @@ -17,9 +17,12 @@ namespace Jellyfin.Data.Entities.Libraries /// Initializes a new instance of the class. /// /// The role type. - public PersonRole(PersonRoleType type) + /// The person. + public PersonRole(PersonRoleType type, Person person) { Type = type; + Person = person; + Artwork = new HashSet(); Sources = new HashSet(); } @@ -40,7 +43,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Role { get; set; } + public string? Role { get; set; } /// /// Gets or sets the person's role type. @@ -60,7 +63,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required. /// - [Required] public virtual Person Person { get; set; } /// diff --git a/Jellyfin.Data/Entities/Libraries/Rating.cs b/Jellyfin.Data/Entities/Libraries/Rating.cs index 0ea933fd79..6862012a80 100644 --- a/Jellyfin.Data/Entities/Libraries/Rating.cs +++ b/Jellyfin.Data/Entities/Libraries/Rating.cs @@ -48,7 +48,7 @@ namespace Jellyfin.Data.Entities.Libraries /// Gets or sets the rating type. /// If this is null it's the internal user rating. /// - public virtual RatingSource RatingType { get; set; } + public virtual RatingSource? RatingType { get; set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/RatingSource.cs b/Jellyfin.Data/Entities/Libraries/RatingSource.cs index 7e1a5a8f46..ae0d806ff0 100644 --- a/Jellyfin.Data/Entities/Libraries/RatingSource.cs +++ b/Jellyfin.Data/Entities/Libraries/RatingSource.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the minimum value. @@ -62,7 +62,7 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Gets or sets the metadata source. /// - public virtual MetadataProviderId Source { get; set; } + public virtual MetadataProviderId? Source { get; set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Release.cs b/Jellyfin.Data/Entities/Libraries/Release.cs index 1871e0f10b..21d4039793 100644 --- a/Jellyfin.Data/Entities/Libraries/Release.cs +++ b/Jellyfin.Data/Entities/Libraries/Release.cs @@ -45,7 +45,6 @@ namespace Jellyfin.Data.Entities.Libraries /// /// Required, Max length = 1024. /// - [Required] [MaxLength(1024)] [StringLength(1024)] public string Name { get; set; } diff --git a/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs index 61714f9095..da40a075f5 100644 --- a/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeasonMetadata.cs @@ -24,6 +24,6 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Outline { get; set; } + public string? Outline { get; set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs index e1acd2d457..730deccaed 100644 --- a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs @@ -30,7 +30,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Outline { get; set; } + public string? Outline { get; set; } /// /// Gets or sets the plot. @@ -40,7 +40,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(65535)] [StringLength(65535)] - public string Plot { get; set; } + public string? Plot { get; set; } /// /// Gets or sets the tagline. @@ -50,7 +50,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(1024)] [StringLength(1024)] - public string Tagline { get; set; } + public string? Tagline { get; set; } /// /// Gets or sets the country code. @@ -60,7 +60,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [MaxLength(2)] [StringLength(2)] - public string Country { get; set; } + public string? Country { get; set; } /// /// Gets or sets a collection containing the networks. @@ -68,7 +68,6 @@ namespace Jellyfin.Data.Entities.Libraries public virtual ICollection Networks { get; protected set; } /// - [NotMapped] public ICollection Companies => Networks; } } diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs index 40f2f8ede9..a8813ab88d 100644 --- a/Jellyfin.Data/Entities/Preference.cs +++ b/Jellyfin.Data/Entities/Preference.cs @@ -46,7 +46,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 65535. /// - [Required] [MaxLength(65535)] [StringLength(65535)] public string Value { get; set; } diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 28e12adde6..9aa8091640 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -51,6 +51,7 @@ namespace Jellyfin.Data.Entities PasswordResetProviderId = passwordResetProviderId; AccessSchedules = new HashSet(); + DisplayPreferences = new HashSet(); ItemDisplayPreferences = new HashSet(); // Groups = new HashSet(); Permissions = new HashSet(); @@ -92,7 +93,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string Username { get; set; } @@ -105,7 +105,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(65535)] [StringLength(65535)] - public string Password { get; set; } + public string? Password { get; set; } /// /// Gets or sets the user's easy password, or null if none is set. @@ -115,7 +115,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(65535)] [StringLength(65535)] - public string EasyPassword { get; set; } + public string? EasyPassword { get; set; } /// /// Gets or sets a value indicating whether the user must update their password. @@ -133,7 +133,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(255)] [StringLength(255)] - public string AudioLanguagePreference { get; set; } + public string? AudioLanguagePreference { get; set; } /// /// Gets or sets the authentication provider id. @@ -141,7 +141,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string AuthenticationProviderId { get; set; } @@ -152,7 +151,6 @@ namespace Jellyfin.Data.Entities /// /// Required, Max length = 255. /// - [Required] [MaxLength(255)] [StringLength(255)] public string PasswordResetProviderId { get; set; } @@ -209,7 +207,7 @@ namespace Jellyfin.Data.Entities /// [MaxLength(255)] [StringLength(255)] - public string SubtitleLanguagePreference { get; set; } + public string? SubtitleLanguagePreference { get; set; } /// /// Gets or sets a value indicating whether missing episodes should be displayed. @@ -304,7 +302,7 @@ namespace Jellyfin.Data.Entities /// Gets or sets the user's profile image. Can be null. /// // [ForeignKey("UserId")] - public virtual ImageInfo ProfileImage { get; set; } + public virtual ImageInfo? ProfileImage { get; set; } /// /// Gets or sets the user's display preferences. @@ -312,8 +310,7 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - [Required] - public virtual DisplayPreferences DisplayPreferences { get; set; } + public virtual ICollection DisplayPreferences { get; set; } /// /// Gets or sets the level of sync play permissions this user has. diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index a8ac45645f..a2b6f074e4 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -5,6 +5,7 @@ false true true + enable true true true diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs index 0340248bbd..aa6015caae 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Session/PlaybackStartLogger.cs @@ -86,7 +86,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session return name; } - private static string? GetPlaybackNotificationType(string mediaType) + private static string GetPlaybackNotificationType(string mediaType) { if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)) { @@ -98,7 +98,7 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Session return NotificationType.VideoPlayback.ToString(); } - return null; + return "Playback"; } } } diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 76d1389caf..b400a0dd1b 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -184,8 +184,8 @@ namespace Jellyfin.Server.Implementations.Users var user = new User( name, - _defaultAuthenticationProvider.GetType().FullName, - _defaultPasswordResetProvider.GetType().FullName) + _defaultAuthenticationProvider.GetType().FullName!, + _defaultPasswordResetProvider.GetType().FullName!) { InternalId = max + 1 }; @@ -444,7 +444,7 @@ namespace Jellyfin.Server.Implementations.Users { var providerId = authenticationProvider.GetType().FullName; - if (!string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase)) + if (providerId != null && !string.Equals(providerId, user.AuthenticationProviderId, StringComparison.OrdinalIgnoreCase)) { user.AuthenticationProviderId = providerId; await UpdateUserAsync(user).ConfigureAwait(false); diff --git a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs index 33f039c394..6d318d2329 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs @@ -1,7 +1,5 @@ using System; -using System.Globalization; using System.IO; -using System.Linq; using Emby.Server.Implementations.Data; using Emby.Server.Implementations.Serialization; using Jellyfin.Data.Entities; @@ -104,7 +102,7 @@ namespace Jellyfin.Server.Migrations.Routines _ => policy.LoginAttemptsBeforeLockout }; - var user = new User(mockup.Name, policy.AuthenticationProviderId, policy.PasswordResetProviderId) + var user = new User(mockup.Name, policy.AuthenticationProviderId!, policy.PasswordResetProviderId!) { Id = entry[1].ReadGuidFromBlob(), InternalId = entry[0].ToInt64(), diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index 935a790312..142cebd0c0 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -61,7 +61,7 @@ namespace MediaBrowser.Controller.Drawing string GetImageCacheTag(BaseItem item, ChapterInfo info); - string GetImageCacheTag(User user); + string? GetImageCacheTag(User user); /// /// Processes the image. diff --git a/tests/Jellyfin.Api.Tests/TestHelpers.cs b/tests/Jellyfin.Api.Tests/TestHelpers.cs index f27cdf7b63..c1549561db 100644 --- a/tests/Jellyfin.Api.Tests/TestHelpers.cs +++ b/tests/Jellyfin.Api.Tests/TestHelpers.cs @@ -26,8 +26,8 @@ namespace Jellyfin.Api.Tests { var user = new User( "jellyfin", - typeof(DefaultAuthenticationProvider).FullName, - typeof(DefaultPasswordResetProvider).FullName); + typeof(DefaultAuthenticationProvider).FullName!, + typeof(DefaultPasswordResetProvider).FullName!); // Set administrator flag. user.SetPermission(PermissionKind.IsAdministrator, role.Equals(UserRoles.Administrator, StringComparison.OrdinalIgnoreCase)); From 7b37ae94f7773069b1406728e297a012e3f726cc Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 6 Mar 2021 20:02:42 -0500 Subject: [PATCH 1221/1930] Remove unused factory method --- Jellyfin.Data/Entities/AccessSchedule.cs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/Jellyfin.Data/Entities/AccessSchedule.cs b/Jellyfin.Data/Entities/AccessSchedule.cs index 9ac0666ac3..7974d3addb 100644 --- a/Jellyfin.Data/Entities/AccessSchedule.cs +++ b/Jellyfin.Data/Entities/AccessSchedule.cs @@ -58,18 +58,5 @@ namespace Jellyfin.Data.Entities /// /// The end hour. public double EndHour { get; set; } - - /// - /// Static create function (for use in LINQ queries, etc.) - /// - /// The day of the week. - /// The start hour. - /// The end hour. - /// The associated user's id. - /// The newly created instance. - public static AccessSchedule Create(DynamicDayOfWeek dayOfWeek, double startHour, double endHour, Guid userId) - { - return new AccessSchedule(dayOfWeek, startHour, endHour, userId); - } } } From 7c413a323b0d22a59532687b854ea228d544ecb7 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Sat, 6 Mar 2021 20:07:55 -0500 Subject: [PATCH 1222/1930] Move EF Core dependency out of Jellyfin.Data --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 1 + Jellyfin.Data/Jellyfin.Data.csproj | 3 +-- .../Jellyfin.Server.Implementations.csproj | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index f03f04e021..93a4c3a7d8 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -27,6 +27,7 @@ + diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index a2b6f074e4..8651dee252 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -42,8 +42,7 @@ - - + diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 4f24da0ee4..e3278cfd02 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -26,6 +26,8 @@ + + all runtime; build; native; contentfiles; analyzers; buildtransitive From 60ffa6f514656ed7256b555d483771c36164fce7 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 7 Mar 2021 14:43:28 +0100 Subject: [PATCH 1223/1930] Use FileShare.None when creating files --- Emby.Dlna/DlnaManager.cs | 3 ++- Emby.Server.Implementations/AppBase/ConfigurationHelper.cs | 3 ++- Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs | 6 ++++-- Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 6 ++++-- .../LiveTv/EmbyTV/EncodedRecorder.cs | 3 ++- .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 3 ++- .../LiveTv/TunerHosts/SharedHttpStream.cs | 3 ++- Jellyfin.Api/Controllers/ItemLookupController.cs | 3 ++- Jellyfin.Api/Controllers/RemoteImageController.cs | 3 ++- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 3 ++- MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs | 3 ++- MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs | 3 ++- MediaBrowser.Providers/Manager/ImageSaver.cs | 3 ++- MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs | 3 ++- MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs | 3 ++- MediaBrowser.Providers/Subtitles/SubtitleManager.cs | 3 ++- 16 files changed, 36 insertions(+), 18 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 9ab3240388..d7b75f9796 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -395,7 +395,8 @@ namespace Emby.Dlna { Directory.CreateDirectory(systemProfilesPath); - using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { await stream.CopyToAsync(fileStream).ConfigureAwait(false); } diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 77819c7649..3f70763830 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -53,7 +53,8 @@ namespace Emby.Server.Implementations.AppBase Directory.CreateDirectory(directory); // Save it after load in case we got new items - using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { fs.Write(newBytes, 0, newBytesLen); } diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 341194f239..7a6b1d8b61 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -45,7 +45,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - using (var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.None)) { onStarted(); @@ -70,7 +71,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); - await using var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using var output = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.None); onStarted(); diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 13b5a1c552..91a21db60a 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1856,7 +1856,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return; } - using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.None)) { var settings = new XmlWriterSettings { @@ -1920,7 +1921,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV return; } - using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.None)) { var settings = new XmlWriterSettings { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 78a82118ed..40b934d32b 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -91,7 +91,8 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false); await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index b16ccc561a..08832bae14 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -193,7 +193,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var resolved = false; - using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { while (true) { diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index eeb2426f4f..233c3d83a3 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -136,7 +136,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using var message = response; await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.None); await StreamHelper.CopyToAsync( stream, fileStream, diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index dfc68ffcec..dabd4deb79 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -344,11 +344,12 @@ namespace Jellyfin.Api.Controllers Directory.CreateDirectory(directory); using (var stream = result.Content) { + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . await using var fileStream = new FileStream( fullCachePath, FileMode.Create, FileAccess.Write, - FileShare.Read, + FileShare.None, IODefaults.FileStreamBufferSize, true); diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index 5284888d82..e226adc646 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -259,7 +259,8 @@ namespace Jellyfin.Api.Controllers var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid."); Directory.CreateDirectory(fullCacheDirectory); - await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath)); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 240d132b15..7cd9024b08 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,7 +553,8 @@ namespace Jellyfin.Api.Helpers $"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false); diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index a337521c62..e59fcb965b 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -133,7 +133,8 @@ namespace MediaBrowser.LocalMetadata.Savers // On Windows, savint the file will fail if the file is hidden or readonly FileSystem.SetAttributes(path, false, false); - using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var filestream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { stream.CopyTo(filestream); } diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index d195387301..fbb1563bbf 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -677,7 +677,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (!string.Equals(text, newText, StringComparison.Ordinal)) { - using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) using (var writer = new StreamWriter(fileStream, encoding)) { await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index 9dd87aef53..5bb85be7bf 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -261,7 +261,8 @@ namespace MediaBrowser.Providers.Manager _fileSystem.SetAttributes(path, false, false); - await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous)) { await source.CopyToAsync(fs, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index f463a3566b..0a79f5bb59 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -171,7 +171,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 7a15adb8e8..4b1d915671 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -155,7 +155,8 @@ namespace MediaBrowser.Providers.Plugins.AudioDb Directory.CreateDirectory(Path.GetDirectoryName(path)); - await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + await using var xmlFileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); await stream.CopyToAsync(xmlFileStream, cancellationToken).ConfigureAwait(false); } diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 47e9d5ee8c..d4d79d27b5 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -228,7 +228,8 @@ namespace MediaBrowser.Providers.Subtitles { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); - using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, FileStreamBufferSize, true)) + // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . + using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, FileStreamBufferSize, true)) { await stream.CopyToAsync(fs).ConfigureAwait(false); } From 75c9659e05363f2e29e01757dc66f14f3f20f318 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 7 Mar 2021 14:17:32 +0000 Subject: [PATCH 1224/1930] Fix unreachable code & assign id to each profile. --- Emby.Dlna/Profiles/DefaultProfile.cs | 3 +++ Jellyfin.Api/Helpers/StreamingHelpers.cs | 17 +++++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/Profiles/DefaultProfile.cs b/Emby.Dlna/Profiles/DefaultProfile.cs index d4af72b626..8eaf12ba9a 100644 --- a/Emby.Dlna/Profiles/DefaultProfile.cs +++ b/Emby.Dlna/Profiles/DefaultProfile.cs @@ -1,5 +1,7 @@ #pragma warning disable CS1591 +using System; +using System.Globalization; using System.Linq; using MediaBrowser.Model.Dlna; @@ -10,6 +12,7 @@ namespace Emby.Dlna.Profiles { public DefaultProfile() { + Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); Name = "Generic Device"; ProtocolInfo = "http-get:*:video/mpeg:*,http-get:*:video/mp4:*,http-get:*:video/vnd.dlna.mpeg-tts:*,http-get:*:video/avi:*,http-get:*:video/x-matroska:*,http-get:*:video/x-ms-wmv:*,http-get:*:video/wtv:*,http-get:*:audio/mpeg:*,http-get:*:audio/mp3:*,http-get:*:audio/mp4:*,http-get:*:audio/x-ms-wma:*,http-get:*:audio/wav:*,http-get:*:audio/L16:*,http-get:*:image/jpeg:*,http-get:*:image/png:*,http-get:*:image/gif:*,http-get:*:image/tiff:*"; diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index d20a02cf5d..6bc5524cba 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -508,17 +508,18 @@ namespace Jellyfin.Api.Helpers private static void ApplyDeviceProfileSettings(StreamState state, IDlnaManager dlnaManager, IDeviceManager deviceManager, HttpRequest request, string? deviceProfileId, bool? @static) { - var headers = request.Headers; - if (!string.IsNullOrWhiteSpace(deviceProfileId)) { - state.DeviceProfile = dlnaManager.GetProfile(deviceProfileId); - } - else if (!string.IsNullOrWhiteSpace(deviceProfileId)) - { - var caps = deviceManager.GetCapabilities(deviceProfileId); + if (state.DeviceProfile == null) + { + state.DeviceProfile = dlnaManager.GetProfile(deviceProfileId); + } - state.DeviceProfile = caps == null ? dlnaManager.GetProfile(headers) : caps.DeviceProfile; + if (state.DeviceProfile == null) + { + var caps = deviceManager.GetCapabilities(deviceProfileId); + state.DeviceProfile = caps == null ? dlnaManager.GetProfile(request.Headers) : caps.DeviceProfile; + } } var profile = state.DeviceProfile; From e0db17a9354ff511c31c7bcf02c41d868ed91c5a Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 7 Mar 2021 22:49:31 +0100 Subject: [PATCH 1225/1930] do not throw ArgumentNullException in TryCleanString --- Emby.Naming/Video/CleanStringParser.cs | 11 +++++++++-- Emby.Naming/Video/VideoResolver.cs | 3 ++- tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs | 1 + 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index 09a0cd1893..deeea4ddac 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Emby.Naming.Video @@ -16,7 +17,7 @@ namespace Emby.Naming.Video /// List of regex to parse name and year from. /// Parsing result string. /// True if parsing was successful. - public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName) + public static bool TryClean(string name, IReadOnlyList expressions, [NotNullWhen(true)] out ReadOnlySpan newName) { var len = expressions.Count; for (int i = 0; i < len; i++) @@ -31,8 +32,14 @@ namespace Emby.Naming.Video return false; } - private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) + private static bool TryClean(string name, Regex expression, [NotNullWhen(true)] out ReadOnlySpan newName) { + if (string.IsNullOrEmpty(name)) + { + newName = null; + return false; + } + var match = expression.Match(name); int index = match.Index; if (match.Success && index != 0) diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 619d1520e4..d845d2ca6e 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Emby.Naming.Common; @@ -146,7 +147,7 @@ namespace Emby.Naming.Video /// Raw name. /// Clean name. /// True if cleaning of name was successful. - public bool TryCleanString(string name, out ReadOnlySpan newName) + public bool TryCleanString(string name, [NotNullWhen(true)] out ReadOnlySpan newName) { return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index fde06c5a17..4b363843ac 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -28,6 +28,7 @@ namespace Jellyfin.Naming.Tests.Video [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] + [InlineData(null, null)] // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] public void CleanStringTest(string input, string expectedName) { From fcacae8cdeb3be15b27952d873ae08e29b6c7f94 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 7 Mar 2021 22:59:08 +0100 Subject: [PATCH 1226/1930] return empty span instead of null for backwards compat --- Emby.Naming/Video/CleanStringParser.cs | 9 ++++----- Emby.Naming/Video/VideoResolver.cs | 3 +-- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index deeea4ddac..bd7553a91c 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Emby.Naming.Video @@ -17,7 +16,7 @@ namespace Emby.Naming.Video /// List of regex to parse name and year from. /// Parsing result string. /// True if parsing was successful. - public static bool TryClean(string name, IReadOnlyList expressions, [NotNullWhen(true)] out ReadOnlySpan newName) + public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName) { var len = expressions.Count; for (int i = 0; i < len; i++) @@ -32,11 +31,11 @@ namespace Emby.Naming.Video return false; } - private static bool TryClean(string name, Regex expression, [NotNullWhen(true)] out ReadOnlySpan newName) + private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) { if (string.IsNullOrEmpty(name)) { - newName = null; + newName = ReadOnlySpan.Empty; return false; } @@ -48,7 +47,7 @@ namespace Emby.Naming.Video return true; } - newName = string.Empty; + newName = ReadOnlySpan.Empty; return false; } } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index d845d2ca6e..619d1520e4 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Emby.Naming.Common; @@ -147,7 +146,7 @@ namespace Emby.Naming.Video /// Raw name. /// Clean name. /// True if cleaning of name was successful. - public bool TryCleanString(string name, [NotNullWhen(true)] out ReadOnlySpan newName) + public bool TryCleanString(string name, out ReadOnlySpan newName) { return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } From bc95268bd6a81db3f8e1c192aad48df5b879d231 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Sun, 7 Mar 2021 21:40:56 +0000 Subject: [PATCH 1227/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- Emby.Server.Implementations/Localization/Core/kk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index a321e35d03..bdfb786c94 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -109,7 +109,7 @@ "TasksMaintenanceCategory": "Qyzmet körsetu", "Undefined": "Anyqtalmağan", "Forced": "Mäjbürlı", - "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımderı negızınde joq subtitrlerdı Internetten ızdeidı.", + "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımderı negızınde joq subtitrlerdı İnternetten ızdeidı.", "TaskRefreshChannelsDescription": "Internet-arnalar mälımetterın jaŋğyrtady.", "TaskCleanTranscodeDescription": "Bіr künnen asqan qaita kodtau faildaryn joiady.", "TaskUpdatePluginsDescription": "Avtomatty türde jaŋartuğa teŋşelgen plaginder üşın jaŋartulardy jüktep alady jäne ornatady.", From 2e62c09f2e55b33c2ba8eeb97157495e2f8ab5a9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 8 Mar 2021 02:16:35 +0100 Subject: [PATCH 1228/1930] Fix casing CollectionType --- .../Entities/JsonLowerCaseConverter.cs | 29 ++++++++ .../Entities/VirtualFolderInfo.cs | 2 + .../Entities/JsonLowerCaseConverterTests.cs | 70 +++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 MediaBrowser.Model/Entities/JsonLowerCaseConverter.cs create mode 100644 tests/Jellyfin.Model.Tests/Entities/JsonLowerCaseConverterTests.cs diff --git a/MediaBrowser.Model/Entities/JsonLowerCaseConverter.cs b/MediaBrowser.Model/Entities/JsonLowerCaseConverter.cs new file mode 100644 index 0000000000..7c627f0e39 --- /dev/null +++ b/MediaBrowser.Model/Entities/JsonLowerCaseConverter.cs @@ -0,0 +1,29 @@ +#nullable disable +// THIS IS A HACK +// TODO: @bond Move to separate project + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Model.Entities +{ + /// + /// Converts an object to a lowercase string. + /// + /// The object type. + public class JsonLowerCaseConverter : JsonConverter + { + /// + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return JsonSerializer.Deserialize(ref reader, options); + } + + /// + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + writer.WriteStringValue(value?.ToString().ToLowerInvariant()); + } + } +} diff --git a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs index ea3df37265..8fed392b9d 100644 --- a/MediaBrowser.Model/Entities/VirtualFolderInfo.cs +++ b/MediaBrowser.Model/Entities/VirtualFolderInfo.cs @@ -2,6 +2,7 @@ #pragma warning disable CS1591 using System; +using System.Text.Json.Serialization; using MediaBrowser.Model.Configuration; namespace MediaBrowser.Model.Entities @@ -35,6 +36,7 @@ namespace MediaBrowser.Model.Entities /// Gets or sets the type of the collection. /// /// The type of the collection. + [JsonConverter(typeof(JsonLowerCaseConverter))] public CollectionTypeOptions? CollectionType { get; set; } public LibraryOptions LibraryOptions { get; set; } diff --git a/tests/Jellyfin.Model.Tests/Entities/JsonLowerCaseConverterTests.cs b/tests/Jellyfin.Model.Tests/Entities/JsonLowerCaseConverterTests.cs new file mode 100644 index 0000000000..955d296cc8 --- /dev/null +++ b/tests/Jellyfin.Model.Tests/Entities/JsonLowerCaseConverterTests.cs @@ -0,0 +1,70 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using MediaBrowser.Model.Entities; +using Xunit; + +namespace Jellyfin.Model.Tests.Entities +{ + public class JsonLowerCaseConverterTests + { + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions() + { + Converters = + { + new JsonStringEnumConverter() + } + }; + + [Theory] + [InlineData(null, "{\"CollectionType\":null}")] + [InlineData(CollectionTypeOptions.Movies, "{\"CollectionType\":\"movies\"}")] + [InlineData(CollectionTypeOptions.MusicVideos, "{\"CollectionType\":\"musicvideos\"}")] + public void Serialize_CollectionTypeOptions_Correct(CollectionTypeOptions? collectionType, string expected) + { + Assert.Equal(expected, JsonSerializer.Serialize(new TestContainer(collectionType), _jsonOptions)); + } + + [Theory] + [InlineData("{\"CollectionType\":null}", null)] + [InlineData("{\"CollectionType\":\"movies\"}", CollectionTypeOptions.Movies)] + [InlineData("{\"CollectionType\":\"musicvideos\"}", CollectionTypeOptions.MusicVideos)] + public void Deserialize_CollectionTypeOptions_Correct(string json, CollectionTypeOptions? result) + { + var res = JsonSerializer.Deserialize(json, _jsonOptions); + Assert.NotNull(res); + Assert.Equal(result, res!.CollectionType); + } + + [Theory] + [InlineData(null)] + [InlineData(CollectionTypeOptions.Movies)] + [InlineData(CollectionTypeOptions.MusicVideos)] + public void RoundTrip_CollectionTypeOptions_Correct(CollectionTypeOptions? value) + { + var res = JsonSerializer.Deserialize(JsonSerializer.Serialize(new TestContainer(value), _jsonOptions), _jsonOptions); + Assert.NotNull(res); + Assert.Equal(value, res!.CollectionType); + } + + [Theory] + [InlineData("{\"CollectionType\":null}")] + [InlineData("{\"CollectionType\":\"movies\"}")] + [InlineData("{\"CollectionType\":\"musicvideos\"}")] + public void RoundTrip_String_Correct(string json) + { + var res = JsonSerializer.Serialize(JsonSerializer.Deserialize(json, _jsonOptions), _jsonOptions); + Assert.Equal(json, res); + } + + private class TestContainer + { + public TestContainer(CollectionTypeOptions? collectionType) + { + CollectionType = collectionType; + } + + [JsonConverter(typeof(JsonLowerCaseConverter))] + public CollectionTypeOptions? CollectionType { get; set; } + } + } +} From d4201f812cac5d1b5f4cdd618770df421b3fad70 Mon Sep 17 00:00:00 2001 From: Ikomhoog Date: Mon, 8 Mar 2021 11:02:51 +0100 Subject: [PATCH 1229/1930] Changed string.Length == 0 to string.IsNullOrEmpty in case of null --- Emby.Server.Implementations/Library/PathExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index d9e20e19ac..7dcc925c2f 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -63,7 +63,7 @@ namespace Emby.Server.Implementations.Library { newPath = null; - if (path.Length == 0 || subPath.Length == 0 || newSubPath.Length == 0 || subPath.Length > path.Length) + if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(subPath) || string.IsNullOrEmpty(newSubPath) || subPath.Length > path.Length) { return false; } From 02122f28cc7dce1758f4a8e714dc8a8e7f4bb21f Mon Sep 17 00:00:00 2001 From: Ikomhoog Date: Mon, 8 Mar 2021 11:14:01 +0100 Subject: [PATCH 1230/1930] Update contributors --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 1200275d52..954315f0eb 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -49,6 +49,7 @@ - [h1nk](https://github.com/h1nk) - [hawken93](https://github.com/hawken93) - [HelloWorld017](https://github.com/HelloWorld017) + - [ikomhoog](https://github.com/ikomhoog) - [jftuga](https://github.com/jftuga) - [joern-h](https://github.com/joern-h) - [joshuaboniface](https://github.com/joshuaboniface) From 54f81c4da484e3bb3d62669f0216c2a3a239166d Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 8 Mar 2021 12:08:17 +0100 Subject: [PATCH 1231/1930] Call ToLower on CollectionTypeOptions.ToString --- Emby.Server.Implementations/Library/LibraryManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index d9ffe64b3b..6d92e12b3a 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1247,7 +1247,7 @@ namespace Emby.Server.Implementations.Library { // TODO: @bond use a ReadOnlySpan here when Enum.TryParse supports it // https://github.com/dotnet/runtime/issues/20008 - if (Enum.TryParse(Path.GetExtension(file), true, out var res)) + if (Enum.TryParse(Path.GetFileNameWithoutExtension(file), true, out var res)) { return res; } @@ -3001,7 +3001,7 @@ namespace Emby.Server.Implementations.Library if (collectionType != null) { - var path = Path.Combine(virtualFolderPath, collectionType.ToString() + ".collection"); + var path = Path.Combine(virtualFolderPath, collectionType.ToString().ToLowerInvariant() + ".collection"); File.WriteAllBytes(path, Array.Empty()); } From d3390302f9c3d62bb9c878f52cf11f9f00438cb1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 8 Mar 2021 11:43:59 +0000 Subject: [PATCH 1232/1930] Update ApplicationHost.cs --- Emby.Server.Implementations/ApplicationHost.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 37047a4f72..49febdb963 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -43,6 +43,7 @@ using Emby.Server.Implementations.Serialization; using Emby.Server.Implementations.Session; using Emby.Server.Implementations.SyncPlay; using Emby.Server.Implementations.TV; +using Emby.Server.Implementations.Udp; using Emby.Server.Implementations.Updates; using Jellyfin.Api.Helpers; using Jellyfin.Networking.Configuration; @@ -233,7 +234,7 @@ namespace Emby.Server.Implementations /// /// Gets the value of the PublishedServerUrl setting. /// - public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig["PublishedServerUrl"]; + public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey]; /// /// Gets the server configuration manager. From a031f7e410f7b599e1a50b2c54a7bd78f4187301 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 9 Mar 2021 00:07:21 +0000 Subject: [PATCH 1233/1930] Fix for multiple ip's in the same subnet per interface. --- Jellyfin.Networking/Manager/NetworkManager.cs | 37 ++++++++++--------- MediaBrowser.Common/Net/NetworkExtensions.cs | 5 ++- .../NetworkTesting/NetworkParseTests.cs | 2 + 3 files changed, 25 insertions(+), 19 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 51fcb6d9a0..17bbf9633a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -157,15 +157,16 @@ namespace Jellyfin.Networking.Manager /// Creates a new network collection. /// /// Items to assign the collection, or null. + /// True if subnets that overlap should be merged (default). /// The collection created. - public static Collection CreateCollection(IEnumerable? source = null) + public static Collection CreateCollection(IEnumerable? source = null, bool unique = true) { var result = new Collection(); if (source != null) { foreach (var item in source) { - result.AddItem(item); + result.AddItem(item, unique); } } @@ -386,10 +387,12 @@ namespace Jellyfin.Networking.Manager } // Get the first LAN interface address that isn't a loopback. - var interfaces = CreateCollection(_interfaceAddresses - .Exclude(_bindExclusions) - .Where(IsInLocalNetwork) - .OrderBy(p => p.Tag)); + var interfaces = CreateCollection( + _interfaceAddresses + .Exclude(_bindExclusions) + .Where(IsInLocalNetwork) + .OrderBy(p => p.Tag), + false); if (interfaces.Count > 0) { @@ -429,11 +432,11 @@ namespace Jellyfin.Networking.Manager if (_bindExclusions.Count > 0) { // Return all the internal interfaces except the ones excluded. - return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); + return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)), false); } // No bind address, so return all internal interfaces. - return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); + return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()), false); } return new Collection(_bindAddresses); @@ -555,7 +558,7 @@ namespace Jellyfin.Networking.Manager && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { - result.AddItem(iface); + result.AddItem(iface, false); } } @@ -599,8 +602,8 @@ namespace Jellyfin.Networking.Manager var address = IPNetAddress.Parse(parts[0]); var index = int.Parse(parts[1], CultureInfo.InvariantCulture); address.Tag = index; - _interfaceAddresses.AddItem(address); - _interfaceNames.Add(parts[2], Math.Abs(index)); + _interfaceAddresses.AddItem(address, false); + _interfaceNames[parts[2]] = Math.Abs(index); } } @@ -977,7 +980,7 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); // Internal interfaces must be private and not excluded. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)), false); // Subnets are the same as the calculated internal interface. _lanSubnets = new Collection(); @@ -1012,7 +1015,7 @@ namespace Jellyfin.Networking.Manager } // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i)), false); } _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); @@ -1071,7 +1074,7 @@ namespace Jellyfin.Networking.Manager nw.Tag *= -1; } - _interfaceAddresses.AddItem(nw); + _interfaceAddresses.AddItem(nw, false); // Store interface name so we can use the name in Collections. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; @@ -1092,7 +1095,7 @@ namespace Jellyfin.Networking.Manager nw.Tag *= -1; } - _interfaceAddresses.AddItem(nw); + _interfaceAddresses.AddItem(nw, false); // Store interface name so we can use the name in Collections. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; @@ -1126,10 +1129,10 @@ namespace Jellyfin.Networking.Manager { _logger.LogWarning("No interfaces information available. Using loopback."); // Last ditch attempt - use loopback address. - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); + _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback, false); if (IsIP6Enabled) { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback, false); } } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 9c1a0cf495..cd0c2ea242 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -27,9 +27,10 @@ namespace MediaBrowser.Common.Net /// /// The . /// Item to add. - public static void AddItem(this Collection source, IPObject item) + /// True if subnets that overlap should be merged (default). + public static void AddItem(this Collection source, IPObject item, bool unique = true) { - if (!source.ContainsAddress(item)) + if (!source.ContainsAddress(item) || !unique) { source.Add(item); } diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs index 9f928ded1b..a13822fcbd 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs @@ -38,6 +38,8 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] // vEthernet1 and vEthernet212 should be excluded. [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] + // Overlapping interface, + [InlineData("192.168.1.110/24,-20,br0|192.168.1.10/24,-16,br0|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.110/24,192.168.1.10/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) { var conf = new NetworkConfiguration() From 5241bd41ef4917e0a3071f961f08dd2eeec5a5dd Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 01:28:21 +0100 Subject: [PATCH 1234/1930] Add code analysis attributes where appropriate --- Emby.Naming/Video/CleanStringParser.cs | 15 ++++---- Emby.Naming/Video/VideoResolver.cs | 3 +- .../Library/PathExtensions.cs | 11 ++++-- .../Video/CleanStringTests.cs | 36 ++++++++++--------- .../Library/PathExtensionsTests.cs | 6 +++- 5 files changed, 43 insertions(+), 28 deletions(-) diff --git a/Emby.Naming/Video/CleanStringParser.cs b/Emby.Naming/Video/CleanStringParser.cs index bd7553a91c..4eef3ebc5e 100644 --- a/Emby.Naming/Video/CleanStringParser.cs +++ b/Emby.Naming/Video/CleanStringParser.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Emby.Naming.Video @@ -16,8 +17,14 @@ namespace Emby.Naming.Video /// List of regex to parse name and year from. /// Parsing result string. /// True if parsing was successful. - public static bool TryClean(string name, IReadOnlyList expressions, out ReadOnlySpan newName) + public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList expressions, out ReadOnlySpan newName) { + if (string.IsNullOrEmpty(name)) + { + newName = ReadOnlySpan.Empty; + return false; + } + var len = expressions.Count; for (int i = 0; i < len; i++) { @@ -33,12 +40,6 @@ namespace Emby.Naming.Video private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) { - if (string.IsNullOrEmpty(name)) - { - newName = ReadOnlySpan.Empty; - return false; - } - var match = expression.Match(name); int index = match.Index; if (match.Success && index != 0) diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 619d1520e4..79a6da8f7b 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Emby.Naming.Common; @@ -146,7 +147,7 @@ namespace Emby.Naming.Video /// Raw name. /// Clean name. /// True if cleaning of name was successful. - public bool TryCleanString(string name, out ReadOnlySpan newName) + public bool TryCleanString([NotNullWhen(true)] string? name, out ReadOnlySpan newName) { return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); } diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 7dcc925c2f..57d0c26b9c 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -59,11 +59,18 @@ namespace Emby.Server.Implementations.Library /// The result of the sub path replacement /// The path after replacing the sub path. /// , or is empty. - public static bool TryReplaceSubPath(this string path, string subPath, string newSubPath, [NotNullWhen(true)] out string? newPath) + public static bool TryReplaceSubPath( + [NotNullWhen(true)] this string? path, + [NotNullWhen(true)] string? subPath, + [NotNullWhen(true)] string? newSubPath, + [NotNullWhen(true)] out string? newPath) { newPath = null; - if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(subPath) || string.IsNullOrEmpty(newSubPath) || subPath.Length > path.Length) + if (string.IsNullOrEmpty(path) + || string.IsNullOrEmpty(subPath) + || string.IsNullOrEmpty(newSubPath) + || subPath.Length > path.Length) { return false; } diff --git a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs index 4b363843ac..a720bdadeb 100644 --- a/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/CleanStringTests.cs @@ -7,18 +7,13 @@ namespace Jellyfin.Naming.Tests.Video { public sealed class CleanStringTests { - private readonly NamingOptions _namingOptions = new NamingOptions(); + private readonly VideoResolver _videoResolver = new VideoResolver(new NamingOptions()); [Theory] [InlineData("Super movie 480p.mp4", "Super movie")] [InlineData("Super movie 480p 2001.mp4", "Super movie")] [InlineData("Super movie [480p].mp4", "Super movie")] [InlineData("480 Super movie [tmdbid=12345].mp4", "480 Super movie")] - [InlineData("Super movie(2009).mp4", "Super movie(2009).mp4")] - [InlineData("Run lola run (lola rennt) (2009).mp4", "Run lola run (lola rennt) (2009).mp4")] - [InlineData(@"American.Psycho.mkv", "American.Psycho.mkv")] - [InlineData(@"American Psycho.mkv", "American Psycho.mkv")] - [InlineData(@"[rec].mkv", "[rec].mkv")] [InlineData("Crouching.Tiger.Hidden.Dragon.4k.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.UltraHD.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.UHD.mkv", "Crouching.Tiger.Hidden.Dragon")] @@ -28,19 +23,26 @@ namespace Jellyfin.Naming.Tests.Video [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] [InlineData("Crouching.Tiger.Hidden.Dragon.4K.UltraHD.HDR.BDrip-HDC.mkv", "Crouching.Tiger.Hidden.Dragon")] - [InlineData(null, null)] // FIXME: [InlineData("After The Sunset - [0004].mkv", "After The Sunset")] - public void CleanStringTest(string input, string expectedName) + public void CleanStringTest_NeedsCleaning_Success(string input, string expectedName) { - if (new VideoResolver(_namingOptions).TryCleanString(input, out ReadOnlySpan newName)) - { - // TODO: compare spans when XUnit supports it - Assert.Equal(expectedName, newName.ToString()); - } - else - { - Assert.Equal(expectedName, input); - } + Assert.True(_videoResolver.TryCleanString(input, out ReadOnlySpan newName)); + // TODO: compare spans when XUnit supports it + Assert.Equal(expectedName, newName.ToString()); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("Super movie(2009).mp4")] + [InlineData("[rec].mkv")] + [InlineData("American.Psycho.mkv")] + [InlineData("American Psycho.mkv")] + [InlineData("Run lola run (lola rennt) (2009).mp4")] + public void CleanStringTest_DoesntNeedCleaning_False(string? input) + { + Assert.False(_videoResolver.TryCleanString(input, out ReadOnlySpan newName)); + Assert.True(newName.IsEmpty); } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs index a6fe905668..e5508243f0 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs @@ -40,12 +40,16 @@ namespace Jellyfin.Server.Implementations.Tests.Library } [Theory] + [InlineData(null, null, null)] + [InlineData(null, "/my/path", "/another/path")] + [InlineData("/my/path", null, "/another/path")] + [InlineData("/my/path", "/another/path", null)] [InlineData("", "", "")] [InlineData("/my/path", "", "")] [InlineData("", "/another/path", "")] [InlineData("", "", "/new/subpath")] [InlineData("/home/jeff/music/jeff's band/consistently inconsistent.mp3", "/home/jeff/music/not jeff's band", "/home/not jeff")] - public void TryReplaceSubPath_InvalidInput_ReturnsFalseAndNull(string path, string subPath, string newSubPath) + public void TryReplaceSubPath_InvalidInput_ReturnsFalseAndNull(string? path, string? subPath, string? newSubPath) { Assert.False(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result)); Assert.Null(result); From 9ed7f429c01c3f54a154442250d3447fd66d1b02 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 03:04:47 +0100 Subject: [PATCH 1235/1930] FxCop -> Net Analyzers (part 1) --- Emby.Dlna/Emby.Dlna.csproj | 1 - Emby.Drawing/Emby.Drawing.csproj | 1 - Emby.Naming/Emby.Naming.csproj | 1 - Emby.Notifications/Emby.Notifications.csproj | 1 - Emby.Photos/Emby.Photos.csproj | 1 - .../Emby.Server.Implementations.csproj | 1 - Jellyfin.Api/Jellyfin.Api.csproj | 1 - Jellyfin.Data/Jellyfin.Data.csproj | 1 - .../Jellyfin.Drawing.Skia.csproj | 1 - .../Jellyfin.Networking.csproj | 1 - .../Jellyfin.Server.Implementations.csproj | 1 - Jellyfin.Server/Jellyfin.Server.csproj | 1 - Jellyfin.sln | 14 +-- .../MediaBrowser.Common.csproj | 1 - .../MediaBrowser.Controller.csproj | 1 - .../MediaBrowser.LocalMetadata.csproj | 1 - .../BdInfo/BdInfoDirectoryInfo.cs | 2 +- .../Encoder/MediaEncoder.cs | 92 +++---------------- MediaBrowser.MediaEncoding/FfmpegException.cs | 39 ++++++++ .../MediaBrowser.MediaEncoding.csproj | 8 +- .../Probing/ProbeResultNormalizer.cs | 18 +++- .../Subtitles/SubtitleEncoder.cs | 6 +- MediaBrowser.Model/MediaBrowser.Model.csproj | 9 +- .../MediaBrowser.Providers.csproj | 8 +- .../MediaBrowser.XbmcMetadata.csproj | 8 +- .../Parsers/BaseNfoParser.cs | 4 +- .../Providers/BaseVideoNfoProvider.cs | 2 +- .../Savers/AlbumNfoSaver.cs | 18 ++-- .../Savers/ArtistNfoSaver.cs | 13 ++- .../Savers/BaseNfoSaver.cs | 16 +--- .../Savers/EpisodeNfoSaver.cs | 29 +++--- .../Savers/MovieNfoSaver.cs | 17 ++-- .../Savers/SeasonNfoSaver.cs | 11 +-- .../Savers/SeriesNfoSaver.cs | 21 ++--- jellyfin.ruleset | 8 +- .../Jellyfin.Api.Tests.csproj | 8 +- .../Jellyfin.Common.Tests.csproj | 8 +- .../Jellyfin.Controller.Tests.csproj | 8 +- .../Jellyfin.Dlna.Tests.csproj | 8 +- .../Jellyfin.MediaEncoding.Tests.csproj | 8 +- .../Jellyfin.Model.Tests.csproj | 8 +- .../AudioBook/AudioBookResolverTests.cs | 4 +- .../Jellyfin.Naming.Tests.csproj | 10 +- .../Video/VideoResolverTests.cs | 4 +- .../Jellyfin.Networking.Tests.csproj | 17 ++-- .../{NetworkTesting => }/NetworkParseTests.cs | 29 +++--- ...llyfin.Server.Implementations.Tests.csproj | 8 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 8 +- 48 files changed, 213 insertions(+), 273 deletions(-) create mode 100644 MediaBrowser.MediaEncoding/FfmpegException.cs rename tests/Jellyfin.Networking.Tests/{NetworkTesting => }/Jellyfin.Networking.Tests.csproj (73%) rename tests/Jellyfin.Networking.Tests/{NetworkTesting => }/NetworkParseTests.cs (98%) diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index 8b057a0950..480621dd70 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -25,7 +25,6 @@ - diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj index 7d479a5c65..5c5afe1c6e 100644 --- a/Emby.Drawing/Emby.Drawing.csproj +++ b/Emby.Drawing/Emby.Drawing.csproj @@ -25,7 +25,6 @@ - diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index b43203e9dd..63116f3680 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -44,7 +44,6 @@ - diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 16ee918c46..526a27229f 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -25,7 +25,6 @@ - diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index 62e33e6c44..e64a658c51 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -28,7 +28,6 @@ - diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index f03f04e021..5a9792b518 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -49,7 +49,6 @@ - diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 67d0a3b5ab..d5372d7526 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -28,7 +28,6 @@ - diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index a8ac45645f..42731bb119 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -34,7 +34,6 @@ - diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index 466a12e676..1a8415ae0e 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -32,7 +32,6 @@ - diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index cbda74361f..f89a184263 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -13,7 +13,6 @@ - diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 4f24da0ee4..19c7ac5672 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -14,7 +14,6 @@ - diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index bf4f806693..6bfb5b8786 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -26,7 +26,6 @@ - diff --git a/Jellyfin.sln b/Jellyfin.sln index d83013dab0..02ac1c7e98 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -68,14 +68,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Implementat EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jellyfin.Networking\Jellyfin.Networking.csproj", "{0A3FCC4D-C714-4072-B90F-E374A15F9FF9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\NetworkTesting\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -190,10 +190,6 @@ Global {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A3FCC4D-C714-4072-B90F-E374A15F9FF9}.Release|Any CPU.Build.0 = Release|Any CPU - {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Debug|Any CPU.Build.0 = Debug|Any CPU {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -206,6 +202,10 @@ Global {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Debug|Any CPU.Build.0 = Debug|Any CPU {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.ActiveCfg = Release|Any CPU {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}.Release|Any CPU.Build.0 = Release|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -217,10 +217,10 @@ Global {A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {2E3A1B4B-4225-4AAA-8B29-0181A84E7AEE} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {462584F7-5023-4019-9EAC-B98CA458C0A0} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} - {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {30922383-D513-4F4D-B890-A940B57FA353} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 8bb30c565b..34e1934e25 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -46,7 +46,6 @@ - diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 6b1c096acb..d487a324f4 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -47,7 +47,6 @@ - diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index 3ce9ff4cc4..1792f1d9b6 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -24,7 +24,6 @@ - diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs index 4a54b677dd..ef9943722d 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs @@ -71,7 +71,7 @@ namespace MediaBrowser.MediaEncoding.BdInfo _impl.FullName, new[] { searchPattern }, false, - searchOption.HasFlag(System.IO.SearchOption.AllDirectories)).ToArray(), + (searchOption & System.IO.SearchOption.AllDirectories) == System.IO.SearchOption.AllDirectories).ToArray(), x => new BdInfoFileInfo(x)); } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index a520193844..8a25a64c74 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -448,7 +448,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (result == null || (result.Streams == null && result.Format == null)) { - throw new Exception("ffprobe failed - streams and format are both null."); + throw new FfmpegException("ffprobe failed - streams and format are both null."); } if (result.Streams != null) @@ -571,32 +571,18 @@ namespace MediaBrowser.MediaEncoding.Encoder // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar - var vf = string.Empty; - - if (threedFormat.HasValue) + var vf = threedFormat switch { - switch (threedFormat.Value) - { - case Video3DFormat.HalfSideBySide: - vf = "-vf crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; - // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. - break; - case Video3DFormat.FullSideBySide: - vf = "-vf crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; - // fsbs crop width in half,set the display aspect,crop out any black bars we may have made - break; - case Video3DFormat.HalfTopAndBottom: - vf = "-vf crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; - // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made - break; - case Video3DFormat.FullTopAndBottom: - vf = "-vf crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1"; - // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made - break; - default: - break; - } - } + // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. + Video3DFormat.HalfSideBySide => "-vf crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1", + // fsbs crop width in half,set the display aspect,crop out any black bars we may have made + Video3DFormat.FullSideBySide => "-vf crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1", + // htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made + Video3DFormat.HalfTopAndBottom => "-vf crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1", + // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made + Video3DFormat.FullTopAndBottom => "-vf crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1", + _ => string.Empty + }; var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty; @@ -604,7 +590,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (enableHdrExtraction) { string tonemapFilters = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0:peak=100,zscale=t=bt709:m=bt709,format=yuv420p"; - if (string.IsNullOrEmpty(vf)) + if (vf.Length == 0) { vf = "-vf " + tonemapFilters; } @@ -633,35 +619,11 @@ namespace MediaBrowser.MediaEncoding.Encoder var args = string.Format(CultureInfo.InvariantCulture, "-i {0}{3} -threads {4} -v quiet -vframes 1 {2} -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, threads); - var probeSizeArgument = string.Empty; - var analyzeDurationArgument = string.Empty; - - if (!string.IsNullOrWhiteSpace(probeSizeArgument)) - { - args = probeSizeArgument + " " + args; - } - - if (!string.IsNullOrWhiteSpace(analyzeDurationArgument)) - { - args = analyzeDurationArgument + " " + args; - } - if (offset.HasValue) { args = string.Format(CultureInfo.InvariantCulture, "-ss {0} ", GetTimeParameter(offset.Value)) + args; } - if (videoStream != null) - { - /* fix - var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions()); - if (!string.IsNullOrWhiteSpace(decoder)) - { - args = decoder + " " + args; - } - */ - } - if (!string.IsNullOrWhiteSpace(container)) { var inputFormat = EncodingHelper.GetInputFormat(container); @@ -723,7 +685,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.LogError(msg); - throw new Exception(msg); + throw new FfmpegException(msg); } return tempExtractPath; @@ -770,30 +732,6 @@ namespace MediaBrowser.MediaEncoding.Encoder var args = string.Format(CultureInfo.InvariantCulture, "-i {0} -threads {3} -v quiet {2} -f image2 \"{1}\"", inputArgument, outputPath, vf, threads); - var probeSizeArgument = string.Empty; - var analyzeDurationArgument = string.Empty; - - if (!string.IsNullOrWhiteSpace(probeSizeArgument)) - { - args = probeSizeArgument + " " + args; - } - - if (!string.IsNullOrWhiteSpace(analyzeDurationArgument)) - { - args = analyzeDurationArgument + " " + args; - } - - if (videoStream != null) - { - /* fix - var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions()); - if (!string.IsNullOrWhiteSpace(decoder)) - { - args = decoder + " " + args; - } - */ - } - if (!string.IsNullOrWhiteSpace(container)) { var inputFormat = EncodingHelper.GetInputFormat(container); @@ -872,7 +810,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _logger.LogError(msg); - throw new Exception(msg); + throw new FfmpegException(msg); } } } diff --git a/MediaBrowser.MediaEncoding/FfmpegException.cs b/MediaBrowser.MediaEncoding/FfmpegException.cs new file mode 100644 index 0000000000..1697fd33a1 --- /dev/null +++ b/MediaBrowser.MediaEncoding/FfmpegException.cs @@ -0,0 +1,39 @@ +using System; + +namespace MediaBrowser.MediaEncoding +{ + /// + /// Represents errors that occur during interaction with FFmpeg. + /// + public class FfmpegException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public FfmpegException() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public FfmpegException(string message) : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if + /// no inner exception is specified. + /// + public FfmpegException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 3d6b4f98a7..de00920bab 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -10,6 +10,9 @@ false true true + true + AllEnabledByDefault + ../jellyfin.ruleset @@ -30,13 +33,8 @@ - - ../jellyfin.ruleset - - - diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index b9cb49cf2f..75067315f9 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -640,7 +640,7 @@ namespace MediaBrowser.MediaEncoding.Probing } // Filter out junk - if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && streamInfo.CodecTagString.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1) + if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && !streamInfo.CodecTagString.Contains("[0]", StringComparison.OrdinalIgnoreCase)) { stream.CodecTag = streamInfo.CodecTagString; } @@ -1500,11 +1500,23 @@ namespace MediaBrowser.MediaEncoding.Probing } else { - throw new Exception(); // Switch to default parsing + // Switch to default parsing + if (subtitle.Contains('.', StringComparison.Ordinal)) + { + // skip the comment, keep the subtitle + description = string.Join('.', subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first + } + else + { + description = subtitle.Trim(); // Clean up whitespaces and save it + } } } - catch // Default parsing + catch (Exception ex) { + _logger.LogError(ex, "Error while parsing subtitle field"); + + // Default parsing if (subtitle.Contains('.', StringComparison.Ordinal)) { // skip the comment, keep the subtitle diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index fbb1563bbf..39bec8da1c 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -25,7 +25,7 @@ using UtfUnknown; namespace MediaBrowser.MediaEncoding.Subtitles { - public class SubtitleEncoder : ISubtitleEncoder + public sealed class SubtitleEncoder : ISubtitleEncoder { private readonly ILogger _logger; private readonly IApplicationPaths _appPaths; @@ -484,7 +484,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath); - throw new Exception( + throw new FfmpegException( string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath)); } @@ -637,7 +637,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles _logger.LogError(msg); - throw new Exception(msg); + throw new FfmpegException(msg); } else { diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index b6d9169139..30403219f5 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -19,7 +19,9 @@ true true enable - latest + true + + ../jellyfin.ruleset true true true @@ -44,7 +46,6 @@ - @@ -53,8 +54,4 @@ - - ../jellyfin.ruleset - - diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 071a149db9..5e7b8043f1 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -30,20 +30,18 @@ false true true + true + AllEnabledByDefault + ../jellyfin.ruleset - - - ../jellyfin.ruleset - - diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 40f06c731f..95327d3ae8 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -20,18 +20,16 @@ true true enable + true + AllEnabledByDefault + ../jellyfin.ruleset - - - ../jellyfin.ruleset - - diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 6f164caf37..c4bbaf301c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -1168,11 +1168,9 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// IEnumerable{System.String}. private IEnumerable SplitNames(string value) { - value = value ?? string.Empty; - // Only split by comma if there is no pipe in the string // We have to be careful to not split names like Matthew, Jr. - var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1 + var separator = !value.Contains('|', StringComparison.Ordinal) && !value.Contains(';', StringComparison.Ordinal) ? new[] { ',' } : new[] { '|', ';' }; diff --git a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs index af722748b5..64cfc098f9 100644 --- a/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/BaseVideoNfoProvider.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.XbmcMetadata.Providers private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; - public BaseVideoNfoProvider( + protected BaseVideoNfoProvider( ILogger> logger, IFileSystem fileSystem, IConfigurationManager config, diff --git a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs index c22f77dcd5..2385e70485 100644 --- a/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/AlbumNfoSaver.cs @@ -96,18 +96,16 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange( - new string[] - { - "track", - "artist", - "albumartist" - }); + foreach (var tag in base.GetTagsUsed(item)) + { + yield return tag; + } - return list; + yield return "track"; + yield return "artist"; + yield return "albumartist"; } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs index 6365cdecb4..71b58cddb9 100644 --- a/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/ArtistNfoSaver.cs @@ -88,16 +88,15 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange(new string[] + foreach (var tag in base.GetTagsUsed(item)) { - "album", - "disbanded" - }); + yield return tag; + } - return list; + yield return "album"; + yield return "disbanded"; } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 0edab37878..3be35e2d9b 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -166,19 +166,16 @@ namespace MediaBrowser.XbmcMetadata.Savers /// public abstract bool IsEnabledFor(BaseItem item, ItemUpdateType updateType); - protected virtual List GetTagsUsed(BaseItem item) + protected virtual IEnumerable GetTagsUsed(BaseItem item) { - var list = new List(); foreach (var providerKey in item.ProviderIds.Keys) { var providerIdTagName = GetTagForProviderKey(providerKey); if (!_commonTags.Contains(providerIdTagName)) { - list.Add(providerIdTagName); + yield return providerIdTagName; } } - - return list; } /// @@ -261,7 +258,7 @@ namespace MediaBrowser.XbmcMetadata.Savers AddMediaInfo(hasMediaSources, writer); } - var tagsUsed = GetTagsUsed(item); + var tagsUsed = GetTagsUsed(item).ToList(); try { @@ -351,10 +348,7 @@ namespace MediaBrowser.XbmcMetadata.Savers } var scanType = stream.IsInterlaced ? "interlaced" : "progressive"; - if (!string.IsNullOrEmpty(scanType)) - { - writer.WriteElementString("scantype", scanType); - } + writer.WriteElementString("scantype", scanType); if (stream.Channels.HasValue) { @@ -968,7 +962,7 @@ namespace MediaBrowser.XbmcMetadata.Savers => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase); - private void AddCustomTags(string path, List xmlTagsUsed, XmlWriter writer, ILogger logger) + private void AddCustomTags(string path, IReadOnlyCollection xmlTagsUsed, XmlWriter writer, ILogger logger) { var settings = new XmlReaderSettings() { diff --git a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs index 5d3d17893a..62f80e81bd 100644 --- a/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/EpisodeNfoSaver.cs @@ -111,24 +111,23 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange(new string[] + foreach (var tag in base.GetTagsUsed(item)) { - "aired", - "season", - "episode", - "episodenumberend", - "airsafter_season", - "airsbefore_episode", - "airsbefore_season", - "displayseason", - "displayepisode", - "showtitle" - }); + yield return tag; + } - return list; + yield return "aired"; + yield return "season"; + yield return "episode"; + yield return "episodenumberend"; + yield return "airsafter_season"; + yield return "airsbefore_episode"; + yield return "airsbefore_season"; + yield return "displayseason"; + yield return "displayepisode"; + yield return "showtitle"; } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs index 8411217352..412e8031b2 100644 --- a/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/MovieNfoSaver.cs @@ -123,18 +123,17 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange(new string[] + foreach (var tag in base.GetTagsUsed(item)) { - "album", - "artist", - "set", - "id" - }); + yield return tag; + } - return list; + yield return "album"; + yield return "artist"; + yield return "set"; + yield return "id"; } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs index 925a230bdb..b9d73ba822 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeasonNfoSaver.cs @@ -72,15 +72,14 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange(new string[] + foreach (var tag in base.GetTagsUsed(item)) { - "seasonnumber" - }); + yield return tag; + } - return list; + yield return "seasonnumber"; } } } diff --git a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs index 42285db76d..083f22e5d2 100644 --- a/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/SeriesNfoSaver.cs @@ -90,20 +90,19 @@ namespace MediaBrowser.XbmcMetadata.Savers } /// - protected override List GetTagsUsed(BaseItem item) + protected override IEnumerable GetTagsUsed(BaseItem item) { - var list = base.GetTagsUsed(item); - list.AddRange(new string[] + foreach (var tag in base.GetTagsUsed(item)) { - "id", - "episodeguide", - "season", - "episode", - "status", - "displayorder" - }); + yield return tag; + } - return list; + yield return "id"; + yield return "episodeguide"; + yield return "season"; + yield return "episode"; + yield return "status"; + yield return "displayorder"; } } } diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 81337390cc..b012d2b003 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -38,7 +38,7 @@ - + @@ -53,6 +53,8 @@ + + @@ -61,7 +63,11 @@ + + + + diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 873ff0ab4a..0d8176bb2a 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -10,6 +10,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -27,7 +30,6 @@ - @@ -37,10 +39,6 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 278f341099..78e3061f76 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -10,6 +10,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -21,7 +24,6 @@ - @@ -32,8 +34,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index b02a68a3d9..df1eb86172 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -10,6 +10,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -21,7 +24,6 @@ - @@ -31,8 +33,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 850db1c75b..d173d5c93e 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -5,6 +5,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -16,7 +19,6 @@ - @@ -26,8 +28,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index e729dbb09e..84306e0f73 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -10,6 +10,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -27,7 +30,6 @@ - @@ -37,8 +39,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index b6d2c63bd8..b458c06fff 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -5,6 +5,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -16,7 +19,6 @@ - @@ -26,8 +28,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index b3257ace3b..ad63adadc3 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -10,7 +10,7 @@ namespace Jellyfin.Naming.Tests.AudioBook { private readonly NamingOptions _namingOptions = new NamingOptions(); - public static IEnumerable GetResolveFileTestData() + public static IEnumerable Resolve_ValidFileNameTestData() { yield return new object[] { @@ -36,7 +36,7 @@ namespace Jellyfin.Naming.Tests.AudioBook } [Theory] - [MemberData(nameof(GetResolveFileTestData))] + [MemberData(nameof(Resolve_ValidFileNameTestData))] public void Resolve_ValidFileName_Success(AudioBookFileInfo expectedResult) { var result = new AudioBookResolver(_namingOptions).Resolve(expectedResult.Path); diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 99185c975d..0f8a0333a9 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -8,8 +8,11 @@ net5.0 false - enable true + enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -25,14 +28,9 @@ - - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index ba5eaf1aff..9bbbe29709 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Naming.Tests.Video { private readonly VideoResolver _videoResolver = new VideoResolver(new NamingOptions()); - public static IEnumerable GetResolveFileTestData() + public static IEnumerable ResolveFile_ValidFileNameTestData() { yield return new object[] { @@ -156,7 +156,7 @@ namespace Jellyfin.Naming.Tests.Video } [Theory] - [MemberData(nameof(GetResolveFileTestData))] + [MemberData(nameof(ResolveFile_ValidFileNameTestData))] public void ResolveFile_ValidFileName_Success(VideoFileInfo expectedResult) { var result = _videoResolver.ResolveFile(expectedResult.Path); diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj similarity index 73% rename from tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj rename to tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj index fd77397bae..61eead0e95 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj @@ -8,8 +8,11 @@ net5.0 false - enable true + enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -22,18 +25,18 @@ - + + - - + + - - ../../jellyfin-tests.ruleset - + DEBUG + diff --git a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs similarity index 98% rename from tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs rename to tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 9f928ded1b..c3469035eb 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkTesting/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,13 +1,13 @@ using System; +using System.Collections.ObjectModel; using System.Net; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; -using Moq; using Microsoft.Extensions.Logging.Abstractions; +using Moq; using Xunit; -using System.Collections.ObjectModel; namespace Jellyfin.Networking.Tests { @@ -124,7 +124,6 @@ namespace Jellyfin.Networking.Tests Assert.True(IPNetAddress.TryParse(address, out _)); } - /// /// All should be invalid address strings. /// @@ -141,7 +140,6 @@ namespace Jellyfin.Networking.Tests Assert.False(IPHost.TryParse(address, out _)); } - /// /// Test collection parsing. /// @@ -152,19 +150,22 @@ namespace Jellyfin.Networking.Tests /// Excluded IP4 addresses from the collection. /// Network addresses of the collection. [Theory] - [InlineData("127.0.0.1#", + [InlineData( + "127.0.0.1#", "[]", "[]", "[]", "[]", "[]")] - [InlineData("!127.0.0.1", + [InlineData( + "!127.0.0.1", "[]", "[]", "[127.0.0.1/32]", "[127.0.0.1/32]", "[]")] - [InlineData("", + [InlineData( + "", "[]", "[]", "[]", @@ -177,7 +178,8 @@ namespace Jellyfin.Networking.Tests "[10.10.10.10/32]", "[10.10.10.10/32]", "[192.158.0.0/16,127.0.0.1/32,::1/128,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] - [InlineData("192.158.1.2/255.255.0.0,192.169.1.2/8", + [InlineData( + "192.158.1.2/255.255.0.0,192.169.1.2/8", "[192.158.1.2/16,192.169.1.2/8]", "[192.158.1.2/16,192.169.1.2/8]", "[]", @@ -194,12 +196,12 @@ namespace Jellyfin.Networking.Tests { EnableIPV6 = true, EnableIPV4 = true, - }; + }; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); // Test included. - Collection nc = nm.CreateIPCollection(settings.Split(","), false); + Collection nc = nm.CreateIPCollection(settings.Split(","), false); Assert.Equal(nc.AsString(), result1); // Test excluded. @@ -208,7 +210,7 @@ namespace Jellyfin.Networking.Tests conf.EnableIPV6 = false; nm.UpdateSettings(conf); - + // Test IP4 included. nc = nm.CreateIPCollection(settings.Split(","), false); Assert.Equal(nc.AsString(), result2); @@ -252,7 +254,6 @@ namespace Jellyfin.Networking.Tests throw new ArgumentNullException(nameof(result)); } - var conf = new NetworkConfiguration() { EnableIPV6 = true, @@ -378,7 +379,6 @@ namespace Jellyfin.Networking.Tests Assert.True(ncResult.Compare(resultCollection)); } - [Theory] [InlineData("10.1.1.1/32", "10.1.1.1")] [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")] @@ -455,7 +455,7 @@ namespace Jellyfin.Networking.Tests // On my system eth16 is internal, eth11 external (Windows defines the indexes). // // This test is to replicate how subnet bound ServerPublisherUri work throughout the system. - + // User on internal network, we're bound internal and external - so result is internal override. [InlineData("192.168.1.1", "192.168.1.0/24", "eth16,eth11", false, "192.168.1.0/24=internal.jellyfin", "internal.jellyfin")] @@ -479,7 +479,6 @@ namespace Jellyfin.Networking.Tests // User is internal, no binding - so result is the 1st internal, which is then overridden. [InlineData("192.168.1.1", "192.168.1.0/24", "", false, "eth16=http://helloworld.com", "http://helloworld.com")] - public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result) { if (lan == null) diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 1ad8171bee..8debb08c52 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -10,6 +10,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset Jellyfin.Server.Implementations.Tests @@ -31,7 +34,6 @@ - @@ -42,8 +44,4 @@ - - ../jellyfin-tests.ruleset - - diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index d6aab3f85e..2bb94c81f3 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -5,6 +5,9 @@ false true enable + true + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -23,7 +26,6 @@ - @@ -34,8 +36,4 @@ - - ../jellyfin-tests.ruleset - - From d202df6e8a1f36a253e9780e7ec1521bc0c4b75e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 03:22:51 +0100 Subject: [PATCH 1236/1930] Remove useless line --- MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj | 1 - MediaBrowser.Model/MediaBrowser.Model.csproj | 1 - MediaBrowser.Providers/MediaBrowser.Providers.csproj | 1 - MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj | 1 - tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 1 - tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 1 - tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 1 - tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 1 - .../Jellyfin.MediaEncoding.Tests.csproj | 1 - tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 1 - tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 1 - tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj | 1 - .../Jellyfin.Server.Implementations.Tests.csproj | 1 - .../Jellyfin.XbmcMetadata.Tests.csproj | 1 - 14 files changed, 14 deletions(-) diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index de00920bab..39fb0b47c1 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -10,7 +10,6 @@ false true true - true AllEnabledByDefault ../jellyfin.ruleset diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 30403219f5..f622a042ac 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -19,7 +19,6 @@ true true enable - true ../jellyfin.ruleset true diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 5e7b8043f1..152ea664a1 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -30,7 +30,6 @@ false true true - true AllEnabledByDefault ../jellyfin.ruleset diff --git a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj index 95327d3ae8..2904b40ecf 100644 --- a/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj +++ b/MediaBrowser.XbmcMetadata/MediaBrowser.XbmcMetadata.csproj @@ -20,7 +20,6 @@ true true enable - true AllEnabledByDefault ../jellyfin.ruleset diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 0d8176bb2a..a336d2aee8 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 78e3061f76..017a67e9f9 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index df1eb86172..6dec25aa4e 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index d173d5c93e..5d52f94c02 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -5,7 +5,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 84306e0f73..4cc1d37ee9 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index b458c06fff..0c7e262f59 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -5,7 +5,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index 0f8a0333a9..cc12a99a61 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj index 61eead0e95..a76c0e9a06 100644 --- a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 8debb08c52..c3c258b680 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -10,7 +10,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset Jellyfin.Server.Implementations.Tests diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index 2bb94c81f3..9380fe2af4 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -5,7 +5,6 @@ false true enable - true AllEnabledByDefault ../jellyfin-tests.ruleset From e89bd8ba02cd5d5a98bba1bd8b1562af8fdaf5cf Mon Sep 17 00:00:00 2001 From: pkreuzt Date: Tue, 9 Mar 2021 01:58:03 +0000 Subject: [PATCH 1237/1930] Translated using Weblate (Galician) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/gl/ --- .../Localization/Core/gl.json | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/gl.json b/Emby.Server.Implementations/Localization/Core/gl.json index 12bcd793e3..11139d32a8 100644 --- a/Emby.Server.Implementations/Localization/Core/gl.json +++ b/Emby.Server.Implementations/Localization/Core/gl.json @@ -57,5 +57,27 @@ "DeviceOnlineWithName": "{0} conectouse", "DeviceOfflineWithName": "{0} desconectouse", "Default": "Por defecto", - "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}" + "AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}", + "TaskCleanLogs": "Limpar Carpeta de Rexistros", + "TaskCleanActivityLog": "Limpar Rexistro de Actividade", + "TasksChannelsCategory": "Canáis de Internet", + "TaskUpdatePlugins": "Actualizar Plugins", + "User": "Usuario", + "Undefined": "Sen definir", + "TvShows": "Programas de TV", + "System": "Sistema", + "Sync": "Sincronizar", + "SubtitleDownloadFailureFromForItem": "Fallou a descarga de subtítulos para {1} dende {0}", + "StartupEmbyServerIsLoading": "O Servidor Jellyfin está cargando. Por favor, reinténteo en breve.", + "Songs": "Cancións", + "Shows": "Programas", + "ServerNameNeedsToBeRestarted": "{0} precisa ser reiniciado", + "ScheduledTaskStartedWithName": "{0} comezou", + "ScheduledTaskFailedWithName": "{0} fallou", + "ProviderValue": "Provedor: {0}", + "PluginUpdatedWithName": "{0} foi actualizado", + "PluginUninstalledWithName": "{0} foi desinstalado", + "PluginInstalledWithName": "{0} foi instalado", + "Playlists": "Listas de reproducción", + "Photos": "Fotos" } From 80fb52e64f9da4884eb9de5ff52865a3b7af6fc0 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 9 Mar 2021 10:46:54 +0100 Subject: [PATCH 1238/1930] Default to the searchinfo year, fallback to parsed year --- MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 2 +- MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 9a3e3d5fad..14be428ce0 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -140,7 +140,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies // ParseName is required here. // Caller provides the filename with extension stripped and NOT the parsed filename var parsedName = _libraryManager.ParseName(info.Name); - var searchResults = await _tmdbClientManager.SearchMovieAsync(parsedName.Name, parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + var searchResults = await _tmdbClientManager.SearchMovieAsync(parsedName.Name, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); if (searchResults.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index 0238d0574b..e18614524c 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -207,7 +207,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV // ParseName is required here. // Caller provides the filename with extension stripped and NOT the parsed filename var parsedName = _libraryManager.ParseName(info.Name); - var searchResults = await _tmdbClientManager.SearchSeriesAsync(parsedName.Name, info.MetadataLanguage, info.Year ?? 0, cancellationToken).ConfigureAwait(false); + var searchResults = await _tmdbClientManager.SearchSeriesAsync(parsedName.Name, info.MetadataLanguage, info.Year ?? parsedName.Year ?? 0, cancellationToken).ConfigureAwait(false); if (searchResults.Count > 0) { From 880c8636bcfcbc14f60f8247105b3aa41de55c91 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 9 Mar 2021 11:44:39 +0100 Subject: [PATCH 1239/1930] Use imdbid as fallback in movie provider Includes post-ProviderIdExtensions cleanup --- .../Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 9 ++ .../Plugins/Tmdb/TV/TmdbSeriesProvider.cs | 82 ++++++++----------- 2 files changed, 42 insertions(+), 49 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 9a3e3d5fad..8b5e2ddcaa 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -148,6 +148,15 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies } } + if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId)) + { + var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + if (movieResultFromImdbId?.MovieResults.Count > 0) + { + tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString(); + } + } + if (string.IsNullOrEmpty(tmdbId)) { return new MetadataResult(); diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index 0238d0574b..5d3c94d714 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -43,9 +43,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV public async Task> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken) { - var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb); - - if (!string.IsNullOrEmpty(tmdbId)) + if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var tmdbId)) { var series = await _tmdbClientManager .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, cancellationToken) @@ -59,9 +57,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV } } - var imdbId = searchInfo.GetProviderId(MetadataProvider.Imdb); - - if (!string.IsNullOrEmpty(imdbId)) + if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out var imdbId)) { var findResult = await _tmdbClientManager .FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, searchInfo.MetadataLanguage, cancellationToken) @@ -82,9 +78,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV } } - var tvdbId = searchInfo.GetProviderId(MetadataProvider.Tvdb); - - if (!string.IsNullOrEmpty(tvdbId)) + if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId)) { var findResult = await _tmdbClientManager .FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, searchInfo.MetadataLanguage, cancellationToken) @@ -171,33 +165,21 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV var tmdbId = info.GetProviderId(MetadataProvider.Tmdb); - if (string.IsNullOrEmpty(tmdbId)) + if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Imdb, out var imdbId)) { - var imdbId = info.GetProviderId(MetadataProvider.Imdb); - - if (!string.IsNullOrEmpty(imdbId)) + var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + if (searchResult?.TvResults.Count > 0) { - var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); - - if (searchResult != null) - { - tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture); - } + tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture); } } - if (string.IsNullOrEmpty(tmdbId)) + if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId)) { - var tvdbId = info.GetProviderId(MetadataProvider.Tvdb); - - if (!string.IsNullOrEmpty(tvdbId)) + var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + if (searchResult?.TvResults.Count > 0) { - var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); - - if (searchResult != null) - { - tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture); - } + tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture); } } @@ -215,32 +197,34 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV } } - if (!string.IsNullOrEmpty(tmdbId)) + if (string.IsNullOrEmpty(tmdbId)) { - cancellationToken.ThrowIfCancellationRequested(); - - var tvShow = await _tmdbClientManager - .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken) - .ConfigureAwait(false); - - result = new MetadataResult - { - Item = MapTvShowToSeries(tvShow, info.MetadataCountryCode), - ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage - }; - - foreach (var person in GetPersons(tvShow)) - { - result.AddPerson(person); - } - - result.HasMetadata = result.Item != null; + return result; } + cancellationToken.ThrowIfCancellationRequested(); + + var tvShow = await _tmdbClientManager + .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken) + .ConfigureAwait(false); + + result = new MetadataResult + { + Item = MapTvShowToSeries(tvShow, info.MetadataCountryCode), + ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage + }; + + foreach (var person in GetPersons(tvShow)) + { + result.AddPerson(person); + } + + result.HasMetadata = result.Item != null; + return result; } - private Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode) + private static Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode) { var series = new Series { From fa8bfece4e72c32f8350aaa947c81b2494f6bb77 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 1 Mar 2021 19:35:58 +0100 Subject: [PATCH 1240/1930] Split integration tests from unit tests --- Jellyfin.Server/Properties/AssemblyInfo.cs | 2 +- Jellyfin.sln | 2 + .../Jellyfin.Api.Tests.csproj | 7 +--- .../Controllers/BrandingControllerTests.cs | 2 +- .../Controllers/DashboardControllerTests.cs | 4 +- .../Jellyfin.Server.Integration.Tests.csproj | 40 +++++++++++++++++++ .../JellyfinApplicationFactory.cs | 2 +- .../OpenApiSpecTests.cs | 2 +- .../TestAppHost.cs | 2 +- .../TestPage.html | 0 .../TestPlugin.cs | 2 +- .../Jellyfin.Server.Tests.csproj | 39 ++++++++++++++++++ .../ParseNetworkTests.cs | 2 +- 13 files changed, 92 insertions(+), 14 deletions(-) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/Controllers/BrandingControllerTests.cs (97%) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/Controllers/DashboardControllerTests.cs (95%) create mode 100644 tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/JellyfinApplicationFactory.cs (99%) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/OpenApiSpecTests.cs (97%) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/TestAppHost.cs (98%) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/TestPage.html (100%) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/TestPlugin.cs (96%) create mode 100644 tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Tests}/ParseNetworkTests.cs (98%) diff --git a/Jellyfin.Server/Properties/AssemblyInfo.cs b/Jellyfin.Server/Properties/AssemblyInfo.cs index 7abf298b12..fe2d5c5f97 100644 --- a/Jellyfin.Server/Properties/AssemblyInfo.cs +++ b/Jellyfin.Server/Properties/AssemblyInfo.cs @@ -21,4 +21,4 @@ using System.Runtime.InteropServices; // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] -[assembly: InternalsVisibleTo("Jellyfin.Api.Tests")] +[assembly: InternalsVisibleTo("Jellyfin.Server.Tests")] diff --git a/Jellyfin.sln b/Jellyfin.sln index 02ac1c7e98..c749c51e69 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -76,6 +76,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index a336d2aee8..577b61d02a 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -35,11 +35,8 @@ - - - - - + + diff --git a/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs similarity index 97% rename from tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs rename to tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs index 40933562db..fdd93f20ef 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/BrandingControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs @@ -5,7 +5,7 @@ using System.Threading.Tasks; using MediaBrowser.Model.Branding; using Xunit; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { public sealed class BrandingControllerTests : IClassFixture { diff --git a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs similarity index 95% rename from tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs rename to tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs index 300b2697f2..88905fc6d0 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs @@ -8,7 +8,7 @@ using Jellyfin.Api.Models; using MediaBrowser.Common.Json; using Xunit; -namespace Jellyfin.Api.Tests.Controllers +namespace Jellyfin.Server.Integration.Tests.Controllers { public sealed class DashboardControllerTests : IClassFixture { @@ -39,7 +39,7 @@ namespace Jellyfin.Api.Tests.Controllers Assert.True(response.IsSuccessStatusCode); Assert.Equal(MediaTypeNames.Text.Html, response.Content.Headers.ContentType?.MediaType); - StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Api.Tests.TestPage.html")!); + StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Server.Integration.Tests.TestPage.html")!); Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd()); } diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj new file mode 100644 index 0000000000..49004966b9 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -0,0 +1,40 @@ + + + net5.0 + false + true + enable + AllEnabledByDefault + ../jellyfin-tests.ruleset + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs similarity index 99% rename from tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs rename to tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs index 92c5495c83..94e6181023 100644 --- a/tests/Jellyfin.Api.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs @@ -15,7 +15,7 @@ using Microsoft.Extensions.Logging; using Serilog; using Serilog.Extensions.Logging; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { /// /// Factory for bootstrapping the Jellyfin application in memory for functional end to end tests. diff --git a/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs similarity index 97% rename from tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs rename to tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs index 03ab56d1f4..3cbd638f90 100644 --- a/tests/Jellyfin.Api.Tests/OpenApiSpecTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs @@ -6,7 +6,7 @@ using MediaBrowser.Model.Branding; using Xunit; using Xunit.Abstractions; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { public sealed class OpenApiSpecTests : IClassFixture { diff --git a/tests/Jellyfin.Api.Tests/TestAppHost.cs b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs similarity index 98% rename from tests/Jellyfin.Api.Tests/TestAppHost.cs rename to tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs index eb4c9b3055..4e5d0fcb63 100644 --- a/tests/Jellyfin.Api.Tests/TestAppHost.cs +++ b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs @@ -8,7 +8,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { /// /// Implementation of the abstract class. diff --git a/tests/Jellyfin.Api.Tests/TestPage.html b/tests/Jellyfin.Server.Integration.Tests/TestPage.html similarity index 100% rename from tests/Jellyfin.Api.Tests/TestPage.html rename to tests/Jellyfin.Server.Integration.Tests/TestPage.html diff --git a/tests/Jellyfin.Api.Tests/TestPlugin.cs b/tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs similarity index 96% rename from tests/Jellyfin.Api.Tests/TestPlugin.cs rename to tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs index a3b4b6994f..1d67ac4870 100644 --- a/tests/Jellyfin.Api.Tests/TestPlugin.cs +++ b/tests/Jellyfin.Server.Integration.Tests/TestPlugin.cs @@ -7,7 +7,7 @@ using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { public class TestPlugin : BasePlugin, IHasWebPages { diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj new file mode 100644 index 0000000000..65ea28e94d --- /dev/null +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -0,0 +1,39 @@ + + + + net5.0 + false + true + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../jellyfin-tests.ruleset + + + diff --git a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs similarity index 98% rename from tests/Jellyfin.Api.Tests/ParseNetworkTests.cs rename to tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index 3984407ee9..0b714e80a2 100644 --- a/tests/Jellyfin.Api.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -10,7 +10,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Tests { public class ParseNetworkTests { From afc70b28d4e1b13e75d12a40eab9455460be1c47 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 1 Mar 2021 19:42:22 +0100 Subject: [PATCH 1241/1930] Add Jellyfin.Server.Tests to solution --- Jellyfin.sln | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Jellyfin.sln b/Jellyfin.sln index c749c51e69..415d024901 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -78,6 +78,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -208,6 +210,10 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU + {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -223,6 +229,7 @@ Global {30922383-D513-4F4D-B890-A940B57FA353} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} From bbbb811e72fef85f0ae95f195da42a924ef1f642 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 1 Mar 2021 20:03:15 +0100 Subject: [PATCH 1242/1930] Fix azure --- .ci/azure-pipelines-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/azure-pipelines-test.yml b/.ci/azure-pipelines-test.yml index 95e0d8c58d..7838b3b026 100644 --- a/.ci/azure-pipelines-test.yml +++ b/.ci/azure-pipelines-test.yml @@ -94,5 +94,5 @@ jobs: displayName: 'Publish OpenAPI Artifact' condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) inputs: - targetPath: "tests/Jellyfin.Api.Tests/bin/Release/net5.0/openapi.json" + targetPath: "tests/Jellyfin.Server.Integration.Tests/bin/Release/net5.0/openapi.json" artifactName: 'OpenAPI Spec' From 3471ddfc84b409a876ebdc71582195de8ad6934f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 2 Mar 2021 02:36:50 +0100 Subject: [PATCH 1243/1930] Fix duplicate project id in sln --- Jellyfin.sln | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 415d024901..7b81f43462 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -76,7 +76,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{A2FD0A10-8F62-4F9D-B171-FFDF9F0AFA9D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject From b9577d0fd986fcadd656a9438eba81f49f375ad8 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 2 Mar 2021 02:57:36 +0100 Subject: [PATCH 1244/1930] Check for specific status code instead of success --- .../Controllers/BrandingControllerTests.cs | 3 ++- .../Controllers/DashboardControllerTests.cs | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs index fdd93f20ef..87136dfc8a 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/BrandingControllerTests.cs @@ -1,3 +1,4 @@ +using System.Net; using System.Net.Mime; using System.Text; using System.Text.Json; @@ -26,7 +27,7 @@ namespace Jellyfin.Server.Integration.Tests var response = await client.GetAsync("/Branding/Configuration"); // Assert - Assert.True(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet); var responseBody = await response.Content.ReadAsStreamAsync(); diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs index 88905fc6d0..86d6326d84 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPage?name=TestPlugin").ConfigureAwait(false); - Assert.True(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(MediaTypeNames.Text.Html, response.Content.Headers.ContentType?.MediaType); StreamReader reader = new StreamReader(typeof(TestPlugin).Assembly.GetManifestResourceStream("Jellyfin.Server.Integration.Tests.TestPage.html")!); Assert.Equal(await response.Content.ReadAsStringAsync(), reader.ReadToEnd()); @@ -60,7 +60,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages").ConfigureAwait(false); - Assert.True(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); var res = await response.Content.ReadAsStreamAsync(); _ = await JsonSerializer.DeserializeAsync(res, _jsonOpions); @@ -74,7 +74,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers var response = await client.GetAsync("/web/ConfigurationPages?enableInMainMenu=true").ConfigureAwait(false); - Assert.True(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); Assert.Equal(Encoding.UTF8.BodyName, response.Content.Headers.ContentType?.CharSet); From 37eb7d6d49b35067c6711ba6f74a64242da419b0 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 5 Mar 2021 12:34:22 +0100 Subject: [PATCH 1245/1930] Perform static initialization only once --- .../JellyfinApplicationFactory.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs index 94e6181023..d9ec81a271 100644 --- a/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs +++ b/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs @@ -4,7 +4,6 @@ using System.IO; using System.Threading; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; -using Jellyfin.Server; using MediaBrowser.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; @@ -26,9 +25,9 @@ namespace Jellyfin.Server.Integration.Tests private readonly ConcurrentBag _disposableComponents = new ConcurrentBag(); /// - /// Initializes a new instance of the class. + /// Initializes static members of the class. /// - public JellyfinApplicationFactory() + static JellyfinApplicationFactory() { // Perform static initialization that only needs to happen once per test-run Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger(); From a618d6053f78664ecb27cb01216ddb21833f5f89 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 14:09:28 +0100 Subject: [PATCH 1246/1930] Move TestPluginWithoutPages to the correct project --- .../TestPluginWithoutPages.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename tests/{Jellyfin.Api.Tests => Jellyfin.Server.Integration.Tests}/TestPluginWithoutPages.cs (94%) diff --git a/tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs b/tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs similarity index 94% rename from tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs rename to tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs index 2d2f78a981..ac10c47845 100644 --- a/tests/Jellyfin.Api.Tests/TestPluginWithoutPages.cs +++ b/tests/Jellyfin.Server.Integration.Tests/TestPluginWithoutPages.cs @@ -6,7 +6,7 @@ using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; -namespace Jellyfin.Api.Tests +namespace Jellyfin.Server.Integration.Tests { public class TestPluginWithoutPages : BasePlugin { From eca3b37d6eae727bd46b7a719cbf5b70a84627f8 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 9 Mar 2021 17:01:05 +0100 Subject: [PATCH 1247/1930] Use FileShare.Read to fix HdHomeRun --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs | 3 +-- .../LiveTv/TunerHosts/SharedHttpStream.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index 08832bae14..b16ccc561a 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -193,8 +193,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var resolved = false; - // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . - using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read)) { while (true) { diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index 233c3d83a3..eeb2426f4f 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -136,8 +136,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath); using var message = response; await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . - await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.None); + await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read); await StreamHelper.CopyToAsync( stream, fileStream, From ece0d67f99240324aafdcde85def3e933e413b69 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 9 Mar 2021 17:31:31 +0100 Subject: [PATCH 1248/1930] Use FileShare.Read for log files --- Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs | 3 +-- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 40b934d32b..78a82118ed 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -91,8 +91,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . - _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); + _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false); await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false); diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 7cd9024b08..240d132b15 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -553,8 +553,7 @@ namespace Jellyfin.Api.Helpers $"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log"); // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. - // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . - Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, true); + Stream logStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(request.Path + Environment.NewLine + Environment.NewLine + JsonSerializer.Serialize(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); await logStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false); From 235b36a4c7f5e2dbb682bb7e6588b8f06219ce6c Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Tue, 9 Mar 2021 12:41:51 -0500 Subject: [PATCH 1249/1930] Remove Microsoft repo from install step This was breaking Fedora builds due to a mismatch. We can use the .NET SDK 5.0 from the Fedora 33 repos instead and this seems to work. --- deployment/Dockerfile.fedora.amd64 | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/deployment/Dockerfile.fedora.amd64 b/deployment/Dockerfile.fedora.amd64 index 2549f25ee7..137e56ecf2 100644 --- a/deployment/Dockerfile.fedora.amd64 +++ b/deployment/Dockerfile.fedora.amd64 @@ -13,9 +13,7 @@ RUN dnf update -y \ && dnf install -y @buildsys-build rpmdevtools git dnf-plugins-core libcurl-devel fontconfig-devel freetype-devel openssl-devel glibc-devel libicu-devel systemd # Install DotNET SDK -RUN rpm --import https://packages.microsoft.com/keys/microsoft.asc \ - && curl -o /etc/yum.repos.d/microsoft-prod.repo https://packages.microsoft.com/config/fedora/$(rpm -E %fedora)/prod.repo \ - && dnf install -y dotnet-sdk-${SDK_VERSION} dotnet-runtime-${SDK_VERSION} +RUN dnf install -y dotnet-sdk-${SDK_VERSION} dotnet-runtime-${SDK_VERSION} # Create symlinks and directories RUN ln -sf ${SOURCE_DIR}/deployment/build.fedora.amd64 /build.sh \ From c5a870051a097e346360b66d063d2f3492f25b0b Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 10 Mar 2021 08:20:02 +0100 Subject: [PATCH 1250/1930] Use distinct for artists to avoid double refreshing --- .../Entities/Audio/IHasAlbumArtist.cs | 12 +++--------- MediaBrowser.Controller/Library/NameExtensions.cs | 8 ++++---- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs index f6d3cd6cc2..20fad4cb0e 100644 --- a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs @@ -1,6 +1,8 @@ #pragma warning disable CS1591 using System.Collections.Generic; +using System.Linq; +using MediaBrowser.Controller.Library; namespace MediaBrowser.Controller.Entities.Audio { @@ -23,15 +25,7 @@ namespace MediaBrowser.Controller.Entities.Audio public static IEnumerable GetAllArtists(this T item) where T : IHasArtist, IHasAlbumArtist { - foreach (var i in item.AlbumArtists) - { - yield return i; - } - - foreach (var i in item.Artists) - { - yield return i; - } + return item.AlbumArtists.Concat(item.Artists).DistinctNames(); } } } diff --git a/MediaBrowser.Controller/Library/NameExtensions.cs b/MediaBrowser.Controller/Library/NameExtensions.cs index 1c90bb4e02..6e79dc8ddf 100644 --- a/MediaBrowser.Controller/Library/NameExtensions.cs +++ b/MediaBrowser.Controller/Library/NameExtensions.cs @@ -10,6 +10,10 @@ namespace MediaBrowser.Controller.Library { public static class NameExtensions { + public static IEnumerable DistinctNames(this IEnumerable names) + => names.GroupBy(RemoveDiacritics, StringComparer.OrdinalIgnoreCase) + .Select(x => x.First()); + private static string RemoveDiacritics(string? name) { if (name == null) @@ -19,9 +23,5 @@ namespace MediaBrowser.Controller.Library return name.RemoveDiacritics(); } - - public static IEnumerable DistinctNames(this IEnumerable names) - => names.GroupBy(RemoveDiacritics, StringComparer.OrdinalIgnoreCase) - .Select(x => x.First()); } } From 84da57cd4811d3bda6b3341c0a8a3b45b3aa72de Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 09:07:11 +0000 Subject: [PATCH 1251/1930] Update StreamingHelpers.cs Updated condition --- Jellyfin.Api/Helpers/StreamingHelpers.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 6bc5524cba..e2306aa272 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -510,10 +510,7 @@ namespace Jellyfin.Api.Helpers { if (!string.IsNullOrWhiteSpace(deviceProfileId)) { - if (state.DeviceProfile == null) - { - state.DeviceProfile = dlnaManager.GetProfile(deviceProfileId); - } + state.DeviceProfile = dlnaManager.GetProfile(deviceProfileId); if (state.DeviceProfile == null) { From 3824c09e774f35df18f37b56e2fc6101dc2022fe Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 10 Mar 2021 10:47:35 +0100 Subject: [PATCH 1252/1930] fix multiversion eligibility check for complex folder names --- Emby.Naming/Video/VideoListResolver.cs | 19 ++++++++++-------- .../Video/MultiVersionTests.cs | 20 +++++++++++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 09a030d2de..0b44763a2f 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -221,20 +221,23 @@ namespace Emby.Naming.Video string testFilename = Path.GetFileNameWithoutExtension(testFilePath); if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) { - if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName)) - { - testFilename = cleanName.ToString(); - } - + // Remove the folder name before cleaning as we don't care about cleaning that part if (folderName.Length <= testFilename.Length) { testFilename = testFilename.Substring(folderName.Length).Trim(); } + if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName)) + { + testFilename = cleanName.ToString(); + } + + // The CleanStringParser should have removed common keywords etc., so if it starts with -, _ or [ it's eligible. return string.IsNullOrEmpty(testFilename) - || testFilename[0] == '-' - || testFilename[0] == '_' - || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); + || testFilename[0] == '-' + || testFilename[0] == '_' + || testFilename[0] == '[' + || string.IsNullOrWhiteSpace(Regex.Replace(testFilename, @"\[([^]]*)\]", string.Empty)); } return false; diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index bc5e6fa631..a46caeca0a 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -368,6 +368,26 @@ namespace Jellyfin.Naming.Tests.Video Assert.Single(result[0].AlternateVersions); } + [Fact] + public void Resolve_GivenFolderNameWithBracketsAndHyphens_GroupsBasedOnFolderName() + { + var files = new[] + { + @"/movies/John Wick - Kapitel 3 (2019) [imdbid=tt6146586]/John Wick - Kapitel 3 (2019) [imdbid=tt6146586] - Version 1.mkv", + @"/movies/John Wick - Kapitel 3 (2019) [imdbid=tt6146586]/John Wick - Kapitel 3 (2019) [imdbid=tt6146586] - Version 2.mkv" + }; + + var result = _videoListResolver.Resolve(files.Select(i => new FileSystemMetadata + { + IsDirectory = false, + FullName = i + }).ToList()).ToList(); + + Assert.Single(result); + Assert.Empty(result[0].Extras); + Assert.Single(result[0].AlternateVersions); + } + [Fact] public void TestEmptyList() { From 2fe26ef136fb00a59362bec33f0a4c31335a330a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 13:28:18 +0000 Subject: [PATCH 1253/1930] removed parameter preset --- Jellyfin.Networking/Manager/NetworkManager.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 17bbf9633a..bf121737b6 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -157,16 +157,15 @@ namespace Jellyfin.Networking.Manager /// Creates a new network collection. /// /// Items to assign the collection, or null. - /// True if subnets that overlap should be merged (default). /// The collection created. - public static Collection CreateCollection(IEnumerable? source = null, bool unique = true) + public static Collection CreateCollection(IEnumerable? source = null) { var result = new Collection(); if (source != null) { foreach (var item in source) { - result.AddItem(item, unique); + result.AddItem(item, false); } } @@ -391,8 +390,7 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses .Exclude(_bindExclusions) .Where(IsInLocalNetwork) - .OrderBy(p => p.Tag), - false); + .OrderBy(p => p.Tag)); if (interfaces.Count > 0) { @@ -432,11 +430,11 @@ namespace Jellyfin.Networking.Manager if (_bindExclusions.Count > 0) { // Return all the internal interfaces except the ones excluded. - return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)), false); + return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); } // No bind address, so return all internal interfaces. - return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()), false); + return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } return new Collection(_bindAddresses); @@ -980,7 +978,7 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); // Internal interfaces must be private and not excluded. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)), false); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); // Subnets are the same as the calculated internal interface. _lanSubnets = new Collection(); @@ -1015,7 +1013,7 @@ namespace Jellyfin.Networking.Manager } // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i)), false); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); } _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); From 8a74d7659819be55fd60dc8d272b0cca2f5178e2 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 10 Mar 2021 17:03:19 +0100 Subject: [PATCH 1254/1930] Fix id tag setting IMDb id when it is TMDb id --- MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs index 2d0eb8433d..d30190a7e8 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/MovieNfoParser.cs @@ -47,12 +47,19 @@ namespace MediaBrowser.XbmcMetadata.Parsers { case "id": { + // get ids from attributes string? imdbId = reader.GetAttribute("IMDB"); string? tmdbId = reader.GetAttribute("TMDB"); - if (string.IsNullOrWhiteSpace(imdbId)) + // read id from content + var contentId = reader.ReadElementContentAsString(); + if (contentId.Contains("tt", StringComparison.Ordinal) && string.IsNullOrEmpty(imdbId)) { - imdbId = reader.ReadElementContentAsString(); + imdbId = contentId; + } + else if (string.IsNullOrEmpty(tmdbId)) + { + tmdbId = contentId; } if (!string.IsNullOrWhiteSpace(imdbId)) From 954148eb6de1f276fb584aa70b384babea0e58ce Mon Sep 17 00:00:00 2001 From: David Date: Wed, 10 Mar 2021 17:04:15 +0100 Subject: [PATCH 1255/1930] Fix Radarr url nfo files --- .../Parsers/BaseNfoParser.cs | 56 ++++++------------- .../Parsers/SeriesNfoParser.cs | 2 +- .../Parsers/MovieNfoParserTests.cs | 15 +++++ .../Test Data/Justice League.nfo | 3 +- .../Test Data/Radarr.nfo | 2 + 5 files changed, 38 insertions(+), 40 deletions(-) create mode 100644 tests/Jellyfin.XbmcMetadata.Tests/Test Data/Radarr.nfo diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index c4bbaf301c..3129c131d0 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -63,7 +63,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected virtual bool SupportsUrlAfterClosingXmlTag => false; - protected virtual string MovieDbParserSearchString => "themoviedb.org/movie/"; + protected virtual string TmdbRegex => "themoviedb\\.org\\/movie\\/([0-9]+)"; /// /// Fetches metadata for an item from one xml file. @@ -181,8 +181,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers } else { - // If the file is just an Imdb url, handle that - + // If the file is just provider urls, handle that ParseProviderLinks(item.Item, xml); return; @@ -221,50 +220,31 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected void ParseProviderLinks(T item, string xml) { - // Look for a match for the Regex pattern "tt" followed by 7 or 8 digits - var m = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.IgnoreCase); - if (m.Success) + // IMDB: + // https://www.imdb.com/title/tt4154796 + var imdbRegex = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.Compiled); + if (imdbRegex.Success) { - item.SetProviderId(MetadataProvider.Imdb, m.Value); + item.SetProviderId(MetadataProvider.Imdb, imdbRegex.Value); } - // Support Tmdb - // https://www.themoviedb.org/movie/30287-fallo - var srch = MovieDbParserSearchString; - var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase); - - if (index != -1) + // TMDB: + // https://www.themoviedb.org/movie/30287-fallo (movie) + // https://www.themoviedb.org/tv/1668-friends (tv) + var tmdbRegex = Regex.Match(xml, TmdbRegex, RegexOptions.Compiled); + if (tmdbRegex.Success) { - var tmdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/'); - index = tmdbId.IndexOf('-'); - if (index != -1) - { - tmdbId = tmdbId.Slice(0, index); - } - - if (!tmdbId.IsEmpty - && !tmdbId.IsWhiteSpace() - && int.TryParse(tmdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) - { - item.SetProviderId(MetadataProvider.Tmdb, value.ToString(UsCulture)); - } + item.SetProviderId(MetadataProvider.Tmdb, tmdbRegex.Groups[1].Value); } + // TVDB: + // https://www.thetvdb.com/?tab=series&id=121361 if (item is Series) { - srch = "thetvdb.com/?tab=series&id="; - - index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase); - - if (index != -1) + var tvdbRegex = Regex.Match(xml, "thetvdb\\.com\\/\\?tab=series\\&id=([0-9]+)", RegexOptions.Compiled); + if (tvdbRegex.Success) { - var tvdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/'); - if (!tvdbId.IsEmpty - && !tvdbId.IsWhiteSpace() - && int.TryParse(tvdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) - { - item.SetProviderId(MetadataProvider.Tvdb, value.ToString(UsCulture)); - } + item.SetProviderId(MetadataProvider.Tvdb, tvdbRegex.Groups[1].Value); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index fbab8b5214..c09781b1ae 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -36,7 +36,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected override bool SupportsUrlAfterClosingXmlTag => true; /// - protected override string MovieDbParserSearchString => "themoviedb.org/tv/"; + protected override string TmdbRegex => "themoviedb\\.org\\/tv\\/([0-9]+)"; /// protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult itemResult) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index ff4795569c..7496784eb9 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -152,6 +152,21 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal(id, item.ProviderIds[provider]); } + [Fact] + public void Parse_RadarrUrlFile_Success() + { + var result = new MetadataResult public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer) { - if (communicationsServer == null) - { - throw new ArgumentNullException(nameof(communicationsServer)); - } - _CommunicationsServer = communicationsServer; - _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; + + if (communicationsServer != null) + { + // This can occur is dlna is enabled, but defined to run over https. + _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; + } _Devices = new List(); } From 2f843b3b4885aa6c0397c560bf11cada7d17c5aa Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:32:13 +0000 Subject: [PATCH 1259/1930] Hide msg if dlna disabled --- Emby.Dlna/Main/DlnaEntryPoint.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 9a2d524d16..d3e9a41ec4 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -128,7 +128,8 @@ namespace Emby.Dlna.Main _netConfig = config.GetConfiguration("network"); _disabled = appHost.ListenWithHttps && _netConfig.RequireHttps; - if (_disabled) + + if (_disabled && _config.GetDlnaConfiguration().EnableServer) { _logger.LogError("The DLNA specification does not support HTTPS."); } From 1dd6036765f08892a39530ad73f5b046afbdaaaf Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:56:33 +0000 Subject: [PATCH 1260/1930] Fixed false starts --- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 +- RSSDP/SsdpDeviceLocator.cs | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 8c7d961f3e..d13871add8 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -69,7 +69,7 @@ namespace Emby.Dlna.Ssdp { lock (_syncLock) { - if (_listenerCount > 0 && _deviceLocator == null) + if (_listenerCount > 0 && _deviceLocator == null && _commsServer != null) { _deviceLocator = new SsdpDeviceLocator(_commsServer); diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index e2b524cf46..9a110683e5 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -27,14 +27,15 @@ namespace Rssdp.Infrastructure /// public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer) { + if (communicationsServer == null) + { + throw new ArgumentNullException(nameof(communicationsServer)); + } + _CommunicationsServer = communicationsServer; - if (communicationsServer != null) - { - // This can occur is dlna is enabled, but defined to run over https. - _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; - } - + // This can occur is dlna is enabled, but defined to run over https. + _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; _Devices = new List(); } From a324d8a9c5351ec2f101f66e2f511eaf208f1254 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:57:32 +0000 Subject: [PATCH 1261/1930] removed space --- Jellyfin.sln | 15 ++++++++++----- RSSDP/SsdpDeviceLocator.cs | 5 ++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 7b81f43462..3f8d8ce85b 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -1,4 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -70,15 +71,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -210,6 +211,10 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 9a110683e5..0cdc5ce3db 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -31,11 +31,10 @@ namespace Rssdp.Infrastructure { throw new ArgumentNullException(nameof(communicationsServer)); } - - _CommunicationsServer = communicationsServer; - // This can occur is dlna is enabled, but defined to run over https. + _CommunicationsServer = communicationsServer; _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; + _Devices = new List(); } From 0960c945d04249e7ec4af2d7f74f53f1cfdd5116 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:58:45 +0000 Subject: [PATCH 1262/1930] Revert "removed space" This reverts commit a324d8a9c5351ec2f101f66e2f511eaf208f1254. --- Jellyfin.sln | 15 +++++---------- RSSDP/SsdpDeviceLocator.cs | 5 +++-- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 3f8d8ce85b..7b81f43462 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -1,5 +1,4 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -71,15 +70,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -211,10 +210,6 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 0cdc5ce3db..9a110683e5 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -31,10 +31,11 @@ namespace Rssdp.Infrastructure { throw new ArgumentNullException(nameof(communicationsServer)); } - + _CommunicationsServer = communicationsServer; - _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; + // This can occur is dlna is enabled, but defined to run over https. + _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; _Devices = new List(); } From 5db998e1350ddd984c72624f882413c676bee6ef Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:59:18 +0000 Subject: [PATCH 1263/1930] removed space. --- RSSDP/SsdpDeviceLocator.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 9a110683e5..31d520ff7f 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -33,9 +33,8 @@ namespace Rssdp.Infrastructure } _CommunicationsServer = communicationsServer; - - // This can occur is dlna is enabled, but defined to run over https. _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; + _Devices = new List(); } From 1723ed1604a5ab6ae4d8e4dc243118c3267d879d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 10 Mar 2021 19:59:58 +0000 Subject: [PATCH 1264/1930] removed the space AGAIN!!! --- RSSDP/SsdpDeviceLocator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 31d520ff7f..0cdc5ce3db 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -31,7 +31,7 @@ namespace Rssdp.Infrastructure { throw new ArgumentNullException(nameof(communicationsServer)); } - + _CommunicationsServer = communicationsServer; _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; From e6f49f50090f91c2c910066b3dbfe1ce1d2c0585 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 10 Mar 2021 21:00:33 +0100 Subject: [PATCH 1265/1930] Remove BuildPackage dependeny for PublishNuget in CI --- .ci/azure-pipelines-package.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 20f4dfe33b..62018fd24b 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -186,9 +186,6 @@ jobs: - job: PublishNuget displayName: 'Publish NuGet packages' - dependsOn: - - BuildPackage - condition: succeeded('BuildPackage') pool: vmImage: 'ubuntu-latest' From b827913fcf298bac28e5ced081dca5e4ded3f3ac Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Wed, 10 Mar 2021 21:09:45 +0100 Subject: [PATCH 1266/1930] Run CollectArtifacts taks regardless of result from BuildPackage and BuildDocker --- .ci/azure-pipelines-package.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.ci/azure-pipelines-package.yml b/.ci/azure-pipelines-package.yml index 62018fd24b..543fd7fc6d 100644 --- a/.ci/azure-pipelines-package.yml +++ b/.ci/azure-pipelines-package.yml @@ -160,7 +160,6 @@ jobs: dependsOn: - BuildPackage - BuildDocker - condition: and(succeeded('BuildPackage'), succeeded('BuildDocker')) pool: vmImage: 'ubuntu-latest' From 8e09276d7d83304792dcbfc07ae511d42b90936d Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 10 Mar 2021 16:33:46 -0700 Subject: [PATCH 1267/1930] Add websocket session message type to generated openapi.json --- Jellyfin.Server/Filters/WebsocketModelFilter.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Server/Filters/WebsocketModelFilter.cs b/Jellyfin.Server/Filters/WebsocketModelFilter.cs index 2488028576..38afb201db 100644 --- a/Jellyfin.Server/Filters/WebsocketModelFilter.cs +++ b/Jellyfin.Server/Filters/WebsocketModelFilter.cs @@ -25,6 +25,8 @@ namespace Jellyfin.Server.Filters context.SchemaGenerator.GenerateSchema(typeof(GeneralCommandType), context.SchemaRepository); context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate), context.SchemaRepository); + + context.SchemaGenerator.GenerateSchema(typeof(SessionMessageType), context.SchemaRepository); } } } From e6407b414ba264ce277f3cf813fe5c2ca11c18ce Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Thu, 11 Mar 2021 09:34:10 -0500 Subject: [PATCH 1268/1930] Remove forum badge --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index cba88c8d2b..6859a8a76f 100644 --- a/README.md +++ b/README.md @@ -29,9 +29,6 @@ Submit Feature Requests - -Discuss on our Forum - Chat on Matrix From 3fdf0de6e3b3600e2825b6ee75634e906d102ce2 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 11 Mar 2021 21:36:58 +0000 Subject: [PATCH 1269/1930] Fix remote access --- Jellyfin.Networking/Manager/NetworkManager.cs | 40 +++++++++++++++++++ .../IpBasedAccessValidationMiddleware.cs | 26 +----------- Jellyfin.sln | 17 +++++--- MediaBrowser.Common/Net/INetworkManager.cs | 7 ++++ .../NetworkParseTests.cs | 20 ++++++++++ 5 files changed, 79 insertions(+), 31 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index d2e9dcf9e6..b874f5984b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -576,6 +576,46 @@ namespace Jellyfin.Networking.Manager return false; } + /// + /// Checks to see if has access. + /// + /// IP Address of client. + /// True if has access, otherwise false. + public bool HasRemoteAccess(IPAddress remoteIp) + { + var config = _configurationManager.GetNetworkConfiguration(); + if (config.EnableRemoteAccess) + { + // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. + // If left blank, all remote addresses will be allowed. + var remoteAddressFilter = RemoteAddressFilter; + + if (RemoteAddressFilter.Count > 0 && !IsInLocalNetwork(remoteIp)) + { + // remoteAddressFilter is a whitelist or blacklist. + bool isListed = RemoteAddressFilter.ContainsAddress(remoteIp); + if (config.IsRemoteIPFilterBlacklist) + { + // Black list, so flip over. + isListed = !isListed; + } + + if (!isListed) + { + // If your name isn't on the list, you arn't coming in. + return false; + } + } + } + else if (!IsInLocalNetwork(remoteIp)) + { + // Remote not enabled. So everyone should be LAN. + return false; + } + + return true; + } + /// /// Reloads all settings and re-initialises the instance. /// diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 525cd9ffe2..96e6fd8340 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -42,32 +42,8 @@ namespace Jellyfin.Server.Middleware var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; - if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess) + if (!networkManager.HasRemoteAccess(remoteIp)) { - // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. - // If left blank, all remote addresses will be allowed. - var remoteAddressFilter = networkManager.RemoteAddressFilter; - - if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp)) - { - // remoteAddressFilter is a whitelist or blacklist. - bool isListed = remoteAddressFilter.ContainsAddress(remoteIp); - if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist) - { - // Black list, so flip over. - isListed = !isListed; - } - - if (!isListed) - { - // If your name isn't on the list, you arn't coming in. - return; - } - } - } - else if (!networkManager.IsInLocalNetwork(remoteIp)) - { - // Remote not enabled. So everyone should be LAN. return; } diff --git a/Jellyfin.sln b/Jellyfin.sln index 7b81f43462..9d5cd98e26 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -1,4 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -70,15 +71,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -210,6 +211,10 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index b6c390d239..012824f652 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -229,5 +229,12 @@ namespace MediaBrowser.Common.Net /// Optional filter for the list. /// Returns a filtered list of LAN addresses. Collection GetFilteredLANSubnets(Collection? filter = null); + + /// + /// Checks to see if has access. + /// + /// IP Address of client. + /// True if has access, otherwise false. + bool HasRemoteAccess(IPAddress remoteIp); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index c3469035eb..96b9f5e765 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -514,5 +514,25 @@ namespace Jellyfin.Networking.Tests Assert.Equal(intf, result); } + + [Theory] + [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", false, true)] // whitelist + [InlineData("185.10.10.10", "185.10.10.10", false, false)] // whitelist + [InlineData("185.10.10.10", "79.2.3.4", true, false)] // blacklist + public void TestRemoteAccess(string addresses, string remoteIp, bool blacklist, bool denied) + { + // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. + // If left blank, all remote addresses will be allowed. + var conf = new NetworkConfiguration() + { + EnableIPV4 = true, + RemoteIPFilter = addresses.Split(","), + IsRemoteIPFilterBlacklist = blacklist + }; + + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + } } } From 034ee38583e613e7dd24282d02051f599b15cedc Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 11 Mar 2021 21:42:01 +0000 Subject: [PATCH 1270/1930] Update Jellyfin.sln reverted --- Jellyfin.sln | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 9d5cd98e26..7b81f43462 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -1,5 +1,4 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -71,15 +70,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -211,10 +210,6 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU From f66cb9777ddaf42f19ea452f85c5fa0b7e907391 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 11 Mar 2021 22:46:07 +0000 Subject: [PATCH 1271/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium --- Jellyfin.Networking/Manager/NetworkManager.cs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index b874f5984b..f42c0aeeb0 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -593,18 +593,7 @@ namespace Jellyfin.Networking.Manager if (RemoteAddressFilter.Count > 0 && !IsInLocalNetwork(remoteIp)) { // remoteAddressFilter is a whitelist or blacklist. - bool isListed = RemoteAddressFilter.ContainsAddress(remoteIp); - if (config.IsRemoteIPFilterBlacklist) - { - // Black list, so flip over. - isListed = !isListed; - } - - if (!isListed) - { - // If your name isn't on the list, you arn't coming in. - return false; - } + return RemoteAddressFilter.ContainsAddress(remoteIp) == !config.IsRemoteIPFilterBlacklist; } } else if (!IsInLocalNetwork(remoteIp)) From 3fa84500cf7430e3f56f04303e7e150f10e88dfb Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 11 Mar 2021 22:46:24 +0000 Subject: [PATCH 1272/1930] Update Jellyfin.Networking/Manager/NetworkManager.cs Co-authored-by: Claus Vium --- Jellyfin.Networking/Manager/NetworkManager.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index f42c0aeeb0..b0046af481 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -588,8 +588,6 @@ namespace Jellyfin.Networking.Manager { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. - var remoteAddressFilter = RemoteAddressFilter; - if (RemoteAddressFilter.Count > 0 && !IsInLocalNetwork(remoteIp)) { // remoteAddressFilter is a whitelist or blacklist. From e5914fd28c9f5073eeadff6fc6097297837b2544 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 11 Mar 2021 22:47:30 +0000 Subject: [PATCH 1273/1930] split tests --- .../NetworkParseTests.cs | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 96b9f5e765..8993d487aa 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -516,10 +516,9 @@ namespace Jellyfin.Networking.Tests } [Theory] - [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", false, true)] // whitelist - [InlineData("185.10.10.10", "185.10.10.10", false, false)] // whitelist - [InlineData("185.10.10.10", "79.2.3.4", true, false)] // blacklist - public void TestRemoteAccess(string addresses, string remoteIp, bool blacklist, bool denied) + [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", true)] + [InlineData("185.10.10.10", "185.10.10.10", false)] + public void HasRemoteAccess_GivenNonEmptyWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. @@ -527,7 +526,25 @@ namespace Jellyfin.Networking.Tests { EnableIPV4 = true, RemoteIPFilter = addresses.Split(","), - IsRemoteIPFilterBlacklist = blacklist + IsRemoteIPFilterBlacklist = false + }; + using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); + + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + } + + [Theory] + [InlineData("185.10.10.10", "79.2.3.4", false)] // blacklist + [InlineData("185.10.10.10", "185.10.10.10", true)] // blacklist + public void HasRemoteAccess_GivenNonEmptBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) + { + // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. + // If left blank, all remote addresses will be allowed. + var conf = new NetworkConfiguration() + { + EnableIPV4 = true, + RemoteIPFilter = addresses.Split(","), + IsRemoteIPFilterBlacklist = true }; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); From eef15dc7ac23f026f11334e2a262a572df126e48 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 11 Mar 2021 22:45:58 -0700 Subject: [PATCH 1274/1930] Fix third part integration --- Jellyfin.Api/Controllers/LibraryController.cs | 6 ++-- .../Controllers/NotificationsController.cs | 21 +++++-------- .../Models/LibraryDtos/MediaUpdateInfoDto.cs | 15 ++++------ .../LibraryDtos/MediaUpdateInfoPathDto.cs | 19 ++++++++++++ .../NotificationDtos/AdminNotificationDto.cs | 30 +++++++++++++++++++ 5 files changed, 65 insertions(+), 26 deletions(-) create mode 100644 Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs create mode 100644 Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 3443ebd72f..2bd2d4933d 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -590,15 +590,15 @@ namespace Jellyfin.Api.Controllers /// /// Reports that new movies have been added by an external source. /// - /// A list of updated media paths. + /// The update paths. /// Report success. /// A . [HttpPost("Library/Media/Updated")] [Authorize(Policy = Policies.DefaultAuthorization)] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult PostUpdatedMedia([FromBody, Required] MediaUpdateInfoDto[] updates) + public ActionResult PostUpdatedMedia([FromBody, Required] MediaUpdateInfoDto dto) { - foreach (var item in updates) + foreach (var item in dto.Updates) { _libraryMonitor.ReportFileSystemChanged(item.Path); } diff --git a/Jellyfin.Api/Controllers/NotificationsController.cs b/Jellyfin.Api/Controllers/NotificationsController.cs index 0ceda6815c..420630cdf4 100644 --- a/Jellyfin.Api/Controllers/NotificationsController.cs +++ b/Jellyfin.Api/Controllers/NotificationsController.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using Jellyfin.Api.Constants; @@ -86,26 +87,19 @@ namespace Jellyfin.Api.Controllers /// /// Sends a notification to all admins. /// - /// The URL of the notification. - /// The level of the notification. - /// The name of the notification. - /// The description of the notification. + /// The notification request. /// Notification sent. /// A . [HttpPost("Admin")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult CreateAdminNotification( - [FromQuery] string? url, - [FromQuery] NotificationLevel? level, - [FromQuery] string name = "", - [FromQuery] string description = "") + public ActionResult CreateAdminNotification([FromBody, Required] AdminNotificationDto notificationDto) { var notification = new NotificationRequest { - Name = name, - Description = description, - Url = url, - Level = level ?? NotificationLevel.Normal, + Name = notificationDto.Name, + Description = notificationDto.Description, + Url = notificationDto.Url, + Level = notificationDto.NotificationLevel ?? NotificationLevel.Normal, UserIds = _userManager.Users .Where(user => user.HasPermission(PermissionKind.IsAdministrator)) .Select(user => user.Id) @@ -114,7 +108,6 @@ namespace Jellyfin.Api.Controllers }; _notificationManager.SendNotification(notification, CancellationToken.None); - return NoContent(); } diff --git a/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs index 991dbfc502..f936388980 100644 --- a/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs +++ b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoDto.cs @@ -1,4 +1,7 @@ -namespace Jellyfin.Api.Models.LibraryDtos +using System; +using System.Collections.Generic; + +namespace Jellyfin.Api.Models.LibraryDtos { /// /// Media Update Info Dto. @@ -6,14 +9,8 @@ public class MediaUpdateInfoDto { /// - /// Gets or sets media path. + /// Gets or sets the list of updates. /// - public string? Path { get; set; } - - /// - /// Gets or sets media update type. - /// Created, Modified, Deleted. - /// - public string? UpdateType { get; set; } + public IReadOnlyList Updates { get; set; } = Array.Empty(); } } diff --git a/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs new file mode 100644 index 0000000000..852315b92d --- /dev/null +++ b/Jellyfin.Api/Models/LibraryDtos/MediaUpdateInfoPathDto.cs @@ -0,0 +1,19 @@ +namespace Jellyfin.Api.Models.LibraryDtos +{ + /// + /// The media update info path. + /// + public class MediaUpdateInfoPathDto + { + /// + /// Gets or sets media path. + /// + public string? Path { get; set; } + + /// + /// Gets or sets media update type. + /// Created, Modified, Deleted. + /// + public string? UpdateType { get; set; } + } +} diff --git a/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs b/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs new file mode 100644 index 0000000000..2c3a6282f2 --- /dev/null +++ b/Jellyfin.Api/Models/NotificationDtos/AdminNotificationDto.cs @@ -0,0 +1,30 @@ +using MediaBrowser.Model.Notifications; + +namespace Jellyfin.Api.Models.NotificationDtos +{ + /// + /// The admin notification dto. + /// + public class AdminNotificationDto + { + /// + /// Gets or sets the notification name. + /// + public string? Name { get; set; } + + /// + /// Gets or sets the notification description. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the notification level. + /// + public NotificationLevel? NotificationLevel { get; set; } + + /// + /// Gets or sets the notification url. + /// + public string? Url { get; set; } + } +} From 80846a1c66eb7f669d95d021786b5273ba3b15f6 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Fri, 12 Mar 2021 12:58:05 +0000 Subject: [PATCH 1275/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- Emby.Server.Implementations/Localization/Core/kk.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index bdfb786c94..829a29ad42 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -116,7 +116,7 @@ "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterın jaŋartady.", "TaskCleanLogsDescription": "{0} künnen asqan jūrnal faildaryn joiady.", "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaŋa faildardy skanerleidі jäne metaderekterdı jaŋğyrtady.", - "TaskRefreshChapterImagesDescription": "Sahnalary bar beineler üşіn nobailar jasaidy.", + "TaskRefreshChapterImagesDescription": "Sahnalary bar beineler üşın nobailar jasaidy.", "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.", "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teŋşelgen jasynan asqan jazbalary joiady." } From e814d8e2cfe41acb9269c048bbbd5f133dfcae7b Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 12 Mar 2021 06:43:57 -0700 Subject: [PATCH 1276/1930] Add JsonStringConverter --- .../Json/Converters/JsonStringConverter.cs | 38 ++++++++++++++++++ MediaBrowser.Common/Json/JsonDefaults.cs | 3 +- .../Json/JsonStringConverterTests.cs | 39 +++++++++++++++++++ 3 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 MediaBrowser.Common/Json/Converters/JsonStringConverter.cs create mode 100644 tests/Jellyfin.Common.Tests/Json/JsonStringConverterTests.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs new file mode 100644 index 0000000000..585f52b8f1 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs @@ -0,0 +1,38 @@ +using System; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// + /// Converter to allow the serializer to read strings. + /// + public class JsonStringConverter : JsonConverter + { + /// + public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return reader.TokenType switch + { + JsonTokenType.Null => null, + JsonTokenType.String => reader.GetString(), + _ => GetRawValue(reader) + }; + } + + /// + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + writer.WriteStringValue(value); + } + + private static string GetRawValue(Utf8JsonReader reader) + { + var utf8Bytes = reader.HasValueSequence + ? reader.ValueSequence.FirstSpan + : reader.ValueSpan; + return Encoding.UTF8.GetString(utf8Bytes); + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 2ef24a884a..61938fdf29 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -39,7 +39,8 @@ namespace MediaBrowser.Common.Json new JsonStringEnumConverter(), new JsonNullableStructConverterFactory(), new JsonBoolNumberConverter(), - new JsonDateTimeConverter() + new JsonDateTimeConverter(), + new JsonStringConverter() } }; diff --git a/tests/Jellyfin.Common.Tests/Json/JsonStringConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonStringConverterTests.cs new file mode 100644 index 0000000000..fd77694b30 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Json/JsonStringConverterTests.cs @@ -0,0 +1,39 @@ +using System.Text.Json; +using MediaBrowser.Common.Json.Converters; +using Xunit; + +namespace Jellyfin.Common.Tests.Json +{ + public class JsonStringConverterTests + { + private readonly JsonSerializerOptions _jsonSerializerOptions + = new () + { + Converters = + { + new JsonStringConverter() + } + }; + + [Theory] + [InlineData("\"test\"", "test")] + [InlineData("123", "123")] + [InlineData("123.45", "123.45")] + [InlineData("true", "true")] + [InlineData("false", "false")] + public void Deserialize_String_Valid_Success(string input, string output) + { + var deserialized = JsonSerializer.Deserialize(input, _jsonSerializerOptions); + Assert.Equal(deserialized, output); + } + + [Fact] + public void Deserialize_Int32asInt32_Valid_Success() + { + const string? input = "123"; + const int output = 123; + var deserialized = JsonSerializer.Deserialize(input, _jsonSerializerOptions); + Assert.Equal(deserialized, output); + } + } +} \ No newline at end of file From b7fb152faf6c01e20d9b8c46be13fc7cc5e0edbc Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 12 Mar 2021 14:44:05 +0000 Subject: [PATCH 1277/1930] Update tests/Jellyfin.Networking.Tests/NetworkParseTests.cs Co-authored-by: Claus Vium --- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 8993d487aa..19f0faa8fe 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -536,7 +536,7 @@ namespace Jellyfin.Networking.Tests [Theory] [InlineData("185.10.10.10", "79.2.3.4", false)] // blacklist [InlineData("185.10.10.10", "185.10.10.10", true)] // blacklist - public void HasRemoteAccess_GivenNonEmptBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenNonEmptyBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. From 4cf88f67baf8f76ce4ed630cc73ef73405c0212b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 12 Mar 2021 14:58:04 +0000 Subject: [PATCH 1278/1930] Update NetworkManager.cs --- Jellyfin.Networking/Manager/NetworkManager.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index b0046af481..785a058d3a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -576,11 +576,7 @@ namespace Jellyfin.Networking.Manager return false; } - /// - /// Checks to see if has access. - /// - /// IP Address of client. - /// True if has access, otherwise false. + /// public bool HasRemoteAccess(IPAddress remoteIp) { var config = _configurationManager.GetNetworkConfiguration(); From 1d5b7b61fb002dd4b2e3fe4cf8dd02df590f64e7 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 12 Mar 2021 22:20:13 +0000 Subject: [PATCH 1279/1930] Change First to FirstOrDefault --- Emby.Dlna/DlnaManager.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index d7b75f9796..3f49256609 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -333,7 +333,12 @@ namespace Emby.Dlna throw new ArgumentNullException(nameof(id)); } - var info = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase)); + var info = GetProfileInfosInternal().FirstOrDefault(i => string.Equals(i.Info.Id, id, StringComparison.OrdinalIgnoreCase)); + + if (info == null) + { + return null; + } return ParseProfileFile(info.Path, info.Info.Type); } From 500832bdfd3dbbb5367484561079b579cb853318 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 12 Mar 2021 17:11:43 -0700 Subject: [PATCH 1280/1930] Set openapi version to server version --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 1828f1a7eb..9670a2b2c7 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -260,15 +260,16 @@ namespace Jellyfin.Server.Extensions { return serviceCollection.AddSwaggerGen(c => { + var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(); c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", - Version = "v1", + Version = version, Extensions = new Dictionary { { "x-jellyfin-version", - new OpenApiString(typeof(ApplicationHost).Assembly.GetName().Version?.ToString()) + new OpenApiString(version) } } }); From fe2a310fe28bb893a855d1278845ce6539c39656 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Sat, 13 Mar 2021 09:13:45 +0100 Subject: [PATCH 1281/1930] fix refresh endpoint It was originally a POST https://github.com/jellyfin/jellyfin/blob/9af6eda0b495649e3a77694b2bb30abad1a26484/MediaBrowser.Api/Library/LibraryService.cs#L155 --- Jellyfin.Api/Controllers/LibraryController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 3443ebd72f..76f882b437 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -303,7 +303,7 @@ namespace Jellyfin.Api.Controllers /// /// Library scan started. /// A . - [HttpGet("Library/Refresh")] + [HttpPost("Library/Refresh")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] public async Task RefreshLibrary() From 37b1b31a46e818cb5d229ebf11d7db7895c3b964 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 13 Mar 2021 08:41:16 -0700 Subject: [PATCH 1282/1930] Convert full ValueSequence --- MediaBrowser.Common/Json/Converters/JsonStringConverter.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs index 585f52b8f1..669b3cd077 100644 --- a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -30,7 +31,7 @@ namespace MediaBrowser.Common.Json.Converters private static string GetRawValue(Utf8JsonReader reader) { var utf8Bytes = reader.HasValueSequence - ? reader.ValueSequence.FirstSpan + ? reader.ValueSequence.ToArray() : reader.ValueSpan; return Encoding.UTF8.GetString(utf8Bytes); } From 1169a0214b3ed166e53b9d6a80c8cbf707518e7b Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 13 Mar 2021 08:43:14 -0700 Subject: [PATCH 1283/1930] Set default version --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 9670a2b2c7..c2b3d9f5ef 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -260,7 +260,7 @@ namespace Jellyfin.Server.Extensions { return serviceCollection.AddSwaggerGen(c => { - var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(); + var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString() ?? "0.0.0.1"; c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", From 9ac9543ee2b69f423f0102f80671fb09893534ae Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 13 Mar 2021 09:09:22 -0700 Subject: [PATCH 1284/1930] Add missing InstantMix endpoints --- .../Controllers/InstantMixController.cs | 90 +++++++++++++++++-- 1 file changed, 82 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/InstantMixController.cs b/Jellyfin.Api/Controllers/InstantMixController.cs index f061755c30..f232dffaa5 100644 --- a/Jellyfin.Api/Controllers/InstantMixController.cs +++ b/Jellyfin.Api/Controllers/InstantMixController.cs @@ -86,7 +86,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given album. /// /// The item id. /// Optional. Filter by user id, and attach user data. @@ -122,7 +122,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given playlist. /// /// The item id. /// Optional. Filter by user id, and attach user data. @@ -158,7 +158,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given genre. /// /// The genre name. /// Optional. Filter by user id, and attach user data. @@ -172,7 +172,7 @@ namespace Jellyfin.Api.Controllers /// A with the playlist items. [HttpGet("MusicGenres/{name}/InstantMix")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> GetInstantMixFromMusicGenre( + public ActionResult> GetInstantMixFromMusicGenreByName( [FromRoute, Required] string name, [FromQuery] Guid? userId, [FromQuery] int? limit, @@ -193,7 +193,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given artist. /// /// The item id. /// Optional. Filter by user id, and attach user data. @@ -229,7 +229,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given genre. /// /// The item id. /// Optional. Filter by user id, and attach user data. @@ -243,7 +243,7 @@ namespace Jellyfin.Api.Controllers /// A with the playlist items. [HttpGet("MusicGenres/{id}/InstantMix")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult> GetInstantMixFromMusicGenres( + public ActionResult> GetInstantMixFromMusicGenreById( [FromRoute, Required] Guid id, [FromQuery] Guid? userId, [FromQuery] int? limit, @@ -265,7 +265,7 @@ namespace Jellyfin.Api.Controllers } /// - /// Creates an instant playlist based on a given song. + /// Creates an instant playlist based on a given item. /// /// The item id. /// Optional. Filter by user id, and attach user data. @@ -300,6 +300,80 @@ namespace Jellyfin.Api.Controllers return GetResult(items, user, limit, dtoOptions); } + /// + /// Creates an instant playlist based on a given artist. + /// + /// The item id. + /// Optional. Filter by user id, and attach user data. + /// Optional. The maximum number of records to return. + /// Optional. Specify additional fields of information to return in the output. + /// Optional. Include image information in output. + /// Optional. Include user data. + /// Optional. The max number of images to return, per image type. + /// Optional. The image types to include in the output. + /// Instant playlist returned. + /// A with the playlist items. + [HttpGet("Artists/InstantMix")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Obsolete("Use GetInstantMixFromArtists")] + public ActionResult> GetInstantMixFromArtists2( + [FromQuery, Required] Guid id, + [FromQuery] Guid? userId, + [FromQuery] int? limit, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, + [FromQuery] bool? enableImages, + [FromQuery] bool? enableUserData, + [FromQuery] int? imageTypeLimit, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) + { + return GetInstantMixFromArtists( + id, + userId, + limit, + fields, + enableImages, + enableUserData, + imageTypeLimit, + enableImageTypes); + } + + /// + /// Creates an instant playlist based on a given genre. + /// + /// The item id. + /// Optional. Filter by user id, and attach user data. + /// Optional. The maximum number of records to return. + /// Optional. Specify additional fields of information to return in the output. + /// Optional. Include image information in output. + /// Optional. Include user data. + /// Optional. The max number of images to return, per image type. + /// Optional. The image types to include in the output. + /// Instant playlist returned. + /// A with the playlist items. + [HttpGet("MusicGenres/InstantMix")] + [ProducesResponseType(StatusCodes.Status200OK)] + [Obsolete("Use GetInstantMixFromMusicGenres instead")] + public ActionResult> GetInstantMixFromMusicGenreById2( + [FromQuery, Required] Guid id, + [FromQuery] Guid? userId, + [FromQuery] int? limit, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields, + [FromQuery] bool? enableImages, + [FromQuery] bool? enableUserData, + [FromQuery] int? imageTypeLimit, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes) + { + return GetInstantMixFromMusicGenreById( + id, + userId, + limit, + fields, + enableImages, + enableUserData, + imageTypeLimit, + enableImageTypes); + } + private QueryResult GetResult(List items, User? user, int? limit, DtoOptions dtoOptions) { var list = items; From f5789483fd5288fe735057bbf6e38a260e6915d2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 19:18:11 +0100 Subject: [PATCH 1285/1930] Add test for HdHomerunManager.WriteSetMessage --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 2 +- .../LiveTv/HdHomerunManagerTests.cs | 37 ++++++++++++++++--- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 20a4d87fba..579333254e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -292,7 +292,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return FinishPacket(buffer, offset); } - private static int WriteSetMessage(Span buffer, int tuner, string name, string value, uint? lockkey) + internal static int WriteSetMessage(Span buffer, int tuner, string name, string value, uint? lockkey) { var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name); int offset = WriteHeaderAndPayload(buffer, byteName); diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index 7e04a1ec12..e8634be4c2 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -17,8 +17,9 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Span buffer = stackalloc byte[128]; int len = HdHomerunManager.WriteNullTerminatedString(buffer, string.Empty); - Assert.Equal(expected.Length, len); - Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + Assert.Equal( + Convert.ToHexString(expected), + Convert.ToHexString(buffer.Slice(0, len))); } [Fact] @@ -32,8 +33,9 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Span buffer = stackalloc byte[128]; int len = HdHomerunManager.WriteNullTerminatedString(buffer, "The quick"); - Assert.Equal(expected.Length, len); - Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + Assert.Equal( + Convert.ToHexString(expected), + Convert.ToHexString(buffer.Slice(0, len))); } [Fact] @@ -51,8 +53,31 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Span buffer = stackalloc byte[128]; int len = HdHomerunManager.WriteGetMessage(buffer, 0, "N"); - Assert.Equal(expected.Length, len); - Assert.True(expected.SequenceEqual(buffer.Slice(0, len))); + Assert.Equal( + Convert.ToHexString(expected), + Convert.ToHexString(buffer.Slice(0, len))); + } + + [Fact] + public void WriteSetMessage_NoLockKey_Success() + { + ReadOnlySpan expected = stackalloc byte[] + { + 0, 4, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xa9, 0x49, 0xd0, 0x68 + }; + + Span buffer = stackalloc byte[128]; + int len = HdHomerunManager.WriteSetMessage(buffer, 0, "N", "value", null); + + Assert.Equal( + Convert.ToHexString(expected), + Convert.ToHexString(buffer.Slice(0, len))); } } } From 4b17648df348ac17b359e2dcfe3e361798d45f2b Mon Sep 17 00:00:00 2001 From: Daniel Date: Sat, 13 Mar 2021 19:23:52 +0100 Subject: [PATCH 1286/1930] Remove empty line Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Collections/CollectionManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 449f8872fd..907b58886f 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -347,7 +347,6 @@ namespace Emby.Server.Implementations.Collections var alreadyInResults = false; foreach (var child in item.GetMediaSources(true)) { - if (results.ContainsKey(Guid.Parse(child.Id))) { alreadyInResults = true; From 7a3109104bf4154d285c94a48504083368556c55 Mon Sep 17 00:00:00 2001 From: Daniel Date: Sat, 13 Mar 2021 19:24:02 +0100 Subject: [PATCH 1287/1930] Remove empty line Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Collections/CollectionManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 907b58886f..151e869487 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -354,7 +354,6 @@ namespace Emby.Server.Implementations.Collections } if (!alreadyInResults) { - results[item.Id] = item; } } From 7fb3a354fd6dd8fa83832566f76bcf0a46a5e82f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 19:24:47 +0100 Subject: [PATCH 1288/1930] Add test for HdHomerunManager.WriteSetMessage with lockkey --- .../LiveTv/HdHomerunManagerTests.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index e8634be4c2..2991fe1ed6 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -79,5 +79,29 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Convert.ToHexString(expected), Convert.ToHexString(buffer.Slice(0, len))); } + + [Fact] + public void WriteSetMessage_LockKey_Success() + { + ReadOnlySpan expected = stackalloc byte[] + { + 0, 4, + 0, 26, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 21, + 4, 0x00, 0x01, 0x38, 0xd5, + 0x8e, 0xb6, 0x06, 0x82 + }; + + Span buffer = stackalloc byte[128]; + int len = HdHomerunManager.WriteSetMessage(buffer, 0, "N", "value", 80085); + + Assert.Equal( + Convert.ToHexString(expected), + Convert.ToHexString(buffer.Slice(0, len))); + } } } From e8b18e5f8fe87f981b11237d24032ab11589bcd2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 19:32:40 +0100 Subject: [PATCH 1289/1930] Add test for HdHomerunManager.ParseReturnMessage --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 2 +- .../LiveTv/HdHomerunManagerTests.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 579333254e..9c113bc7c4 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -355,7 +355,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return offset + 4; } - private static bool ParseReturnMessage(byte[] buf, int numBytes, out string returnVal) + internal static bool ParseReturnMessage(byte[] buf, int numBytes, out string returnVal) { returnVal = string.Empty; diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index 2991fe1ed6..355cfa6412 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -103,5 +103,23 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Convert.ToHexString(expected), Convert.ToHexString(buffer.Slice(0, len))); } + + [Fact] + public void ParseReturnMessage_Valid_Success() + { + ReadOnlySpan packet = stackalloc byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf3 + }; + + Assert.True(HdHomerunManager.ParseReturnMessage(packet.ToArray(), packet.Length, out var value)); + Assert.Equal("value", value); + } } } From 4cc3b938fa7913bccf7229dafce4b9f1d369dd16 Mon Sep 17 00:00:00 2001 From: Mister Rajoy Date: Sat, 13 Mar 2021 20:33:05 +0100 Subject: [PATCH 1290/1930] Change Guid.Parse to Guid.TryParse --- Emby.Server.Implementations/Collections/CollectionManager.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 449f8872fd..b5d95134bd 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -348,11 +348,13 @@ namespace Emby.Server.Implementations.Collections foreach (var child in item.GetMediaSources(true)) { - if (results.ContainsKey(Guid.Parse(child.Id))) + if (Guid.TryParse(child.Id, out var id) && results.ContainsKey(id)) { alreadyInResults = true; + break; } } + if (!alreadyInResults) { From f9640f43663fdf443c130f61cab3521fcb1c7823 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 21:12:11 +0100 Subject: [PATCH 1291/1930] Rewrite HdHomerunManager.ParseReturnMessage --- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 85 +++---- .../LiveTv/HdHomerunManagerTests.cs | 209 +++++++++++++++++- 2 files changed, 249 insertions(+), 45 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 9c113bc7c4..a7fda1d72e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -130,9 +130,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); - ParseReturnMessage(buffer, receivedBytes, out string returnVal); - - return string.Equals(returnVal, "none", StringComparison.OrdinalIgnoreCase); + return VerifyReturnValueOfGetSet(buffer.AsSpan(receivedBytes), "none"); } finally { @@ -173,7 +171,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked - if (!ParseReturnMessage(buffer, receivedBytes, out _)) + if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _)) { continue; } @@ -185,7 +183,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked - if (!ParseReturnMessage(buffer, receivedBytes, out _)) + if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _)) { await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false); continue; @@ -199,7 +197,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked - if (!ParseReturnMessage(buffer, receivedBytes, out _)) + if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _)) { await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false); continue; @@ -239,7 +237,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // parse response to make sure it worked - if (!ParseReturnMessage(buffer, receivedBytes, out _)) + if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _)) { return; } @@ -355,60 +353,65 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun return offset + 4; } - internal static bool ParseReturnMessage(byte[] buf, int numBytes, out string returnVal) + internal static bool VerifyReturnValueOfGetSet(ReadOnlySpan buffer, string expected) { - returnVal = string.Empty; + return TryGetReturnValueOfGetSet(buffer, out var value) + && string.Equals(Encoding.UTF8.GetString(value), expected, StringComparison.OrdinalIgnoreCase); + } - if (numBytes < 4) + internal static bool TryGetReturnValueOfGetSet(ReadOnlySpan buffer, out ReadOnlySpan value) + { + value = ReadOnlySpan.Empty; + + if (buffer.Length < 8) { return false; } - var flipEndian = BitConverter.IsLittleEndian; - int offset = 0; - byte[] msgTypeBytes = new byte[2]; - Buffer.BlockCopy(buf, offset, msgTypeBytes, 0, msgTypeBytes.Length); - - if (flipEndian) - { - Array.Reverse(msgTypeBytes); - } - - var msgType = BitConverter.ToUInt16(msgTypeBytes, 0); - offset += 2; - - if (msgType != GetSetReply) + uint crc = BinaryPrimitives.ReadUInt32LittleEndian(buffer[^4..]); + if (crc != Crc32.Compute(buffer[..^4])) { return false; } - byte[] msgLengthBytes = new byte[2]; - Buffer.BlockCopy(buf, offset, msgLengthBytes, 0, msgLengthBytes.Length); - if (flipEndian) - { - Array.Reverse(msgLengthBytes); - } - - var msgLength = BitConverter.ToUInt16(msgLengthBytes, 0); - offset += 2; - - if (numBytes < msgLength + 8) + if (BinaryPrimitives.ReadUInt16BigEndian(buffer) != GetSetReply) { return false; } - offset++; // Name Tag + var msgLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(2)); + if (buffer.Length != 2 + 2 + 4 + msgLength) + { + return false; + } - var nameLength = buf[offset++]; + var offset = 4; + if (buffer[offset++] != GetSetName) + { + return false; + } + + var nameLength = buffer[offset++]; + if (buffer.Length < 4 + 1 + offset + nameLength) + { + return false; + } - // skip the name field to get to value for return offset += nameLength; - offset++; // Value Tag + if (buffer[offset++] != GetSetValue) + { + return false; + } - var valueLength = buf[offset++]; + var valueLength = buffer[offset++]; + if (buffer.Length < 4 + offset + valueLength) + { + return false; + } - returnVal = Encoding.UTF8.GetString(buf, offset, valueLength - 1); // remove null terminator + // remove null terminator + value = buffer.Slice(offset, valueLength - 1); return true; } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index 355cfa6412..c404e6ed5c 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -1,4 +1,5 @@ using System; +using System.Text; using Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun; using Xunit; @@ -105,9 +106,9 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv } [Fact] - public void ParseReturnMessage_Valid_Success() + public void TryGetReturnValueOfGetSet_Valid_Success() { - ReadOnlySpan packet = stackalloc byte[] + ReadOnlySpan packet = new byte[] { 0, 5, 0, 20, @@ -118,8 +119,208 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv 0x7d, 0xa3, 0xa3, 0xf3 }; - Assert.True(HdHomerunManager.ParseReturnMessage(packet.ToArray(), packet.Length, out var value)); - Assert.Equal("value", value); + Assert.True(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out var value)); + Assert.Equal("value", Encoding.UTF8.GetString(value)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_InvalidPacketType_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 4, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf3 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_InvalidCrc_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf4 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_InvalidPacket_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 0x7d, 0xa3, 0xa3 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_TooSmallMessageLength_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 19, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x25, 0x25, 0x44, 0x9a + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_TooLargeMessageLength_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 21, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xe3, 0x20, 0x79, 0x6c + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_TooLargeNameLength_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 20, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xe1, 0x8e, 0x9c, 0x74 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_InvalidGetSetNameTag_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 4, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xee, 0x05, 0xe7, 0x12 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_InvalidGetSetValueTag_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 3, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x64, 0xaa, 0x66, 0xf9 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void TryGetReturnValueOfGetSet_TooLargeValueLength_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 7, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xc9, 0xa8, 0xd4, 0x55 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + + [Fact] + public void VerifyReturnValueOfGetSet_Valid_True() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf3 + }; + + Assert.True(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "value")); + } + + [Fact] + public void VerifyReturnValueOfGetSet_WrongValue_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 5, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf3 + }; + + Assert.False(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "none")); + } + + [Fact] + public void VerifyReturnValueOfGetSet_InvalidPacket_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 4, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0x7d, 0xa3, 0xa3, 0xf3 + }; + + Assert.False(HdHomerunManager.VerifyReturnValueOfGetSet(packet, "value")); } } } From d9eb7ae6dc69aa4d0b77e7a2ae1c9ccac78d0db9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 21:28:04 +0100 Subject: [PATCH 1292/1930] Fix invalid crc in TryGetReturnValueOfGetSet_InvalidPacketType test --- .../LiveTv/HdHomerunManagerTests.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs index c404e6ed5c..fd499d9cf9 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunManagerTests.cs @@ -123,23 +123,6 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.Equal("value", Encoding.UTF8.GetString(value)); } - [Fact] - public void TryGetReturnValueOfGetSet_InvalidPacketType_False() - { - ReadOnlySpan packet = new byte[] - { - 0, 4, - 0, 20, - 3, - 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, - 4, - 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, - 0x7d, 0xa3, 0xa3, 0xf3 - }; - - Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); - } - [Fact] public void TryGetReturnValueOfGetSet_InvalidCrc_False() { @@ -157,6 +140,23 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); } + [Fact] + public void TryGetReturnValueOfGetSet_InvalidPacketType_False() + { + ReadOnlySpan packet = new byte[] + { + 0, 4, + 0, 20, + 3, + 10, (byte)'/', (byte)'t', (byte)'u', (byte)'n', (byte)'e', (byte)'r', (byte)'0', (byte)'/', (byte)'N', 0, + 4, + 6, (byte)'v', (byte)'a', (byte)'l', (byte)'u', (byte)'e', 0, + 0xa9, 0x49, 0xd0, 0x68 + }; + + Assert.False(HdHomerunManager.TryGetReturnValueOfGetSet(packet, out _)); + } + [Fact] public void TryGetReturnValueOfGetSet_InvalidPacket_False() { From a8ed753f6c890f74d3a70c2653ac5548d2399737 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 05:57:38 +0100 Subject: [PATCH 1293/1930] FxCop -> Net Analyzers (part 2) --- Emby.Dlna/DlnaManager.cs | 2 +- .../ApplicationHost.cs | 5 +- .../Channels/ChannelManager.cs | 2 +- .../Data/SqliteItemRepository.cs | 2 +- .../HttpServer/WebSocketConnection.cs | 2 +- .../Library/LiveStreamHelper.cs | 2 +- .../Library/MediaSourceManager.cs | 2 +- .../LiveTv/EmbyTV/EncodedRecorder.cs | 2 +- .../LiveTv/EmbyTV/ItemDataProvider.cs | 2 +- .../LiveTv/Listings/SchedulesDirect.cs | 2 +- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- .../Localization/LocalizationManager.cs | 2 +- .../Plugins/PluginManager.cs | 4 +- .../ScheduledTasks/ScheduledTaskWorker.cs | 2 +- .../Updates/InstallationManager.cs | 2 +- .../Controllers/ConfigurationController.cs | 2 +- Jellyfin.Api/Controllers/PluginsController.cs | 2 +- Jellyfin.Data/DayOfWeekHelper.cs | 60 +++---------------- .../Entities/Libraries/Collection.cs | 1 + .../Entities/Libraries/MediaFileStream.cs | 2 + Jellyfin.Data/Entities/Permission.cs | 2 + Jellyfin.Data/Jellyfin.Data.csproj | 6 +- .../Jellyfin.Drawing.Skia.csproj | 11 ++-- Jellyfin.Drawing.Skia/SkiaEncoder.cs | 13 ++-- .../Jellyfin.Networking.csproj | 6 +- .../Security/AuthenticationSucceededLogger.cs | 8 +-- .../Consumers/System/TaskCompletedLogger.cs | 14 ++--- .../Updates/PluginUninstalledLogger.cs | 4 +- .../Consumers/Users/UserUpdatedNotifier.cs | 6 +- .../Jellyfin.Server.Implementations.csproj | 2 + .../Users/DefaultPasswordResetProvider.cs | 2 +- .../Users/DisplayPreferencesManager.cs | 3 +- .../ApiServiceCollectionExtensions.cs | 2 +- .../CamelCaseJsonProfileFormatter.cs | 2 +- .../PascalCaseJsonProfileFormatter.cs | 2 +- Jellyfin.Server/Jellyfin.Server.csproj | 8 +-- .../Migrations/MigrationOptions.cs | 3 + .../Migrations/Routines/MigrateUserDb.cs | 2 +- Jellyfin.Server/Program.cs | 4 +- MediaBrowser.Common/IApplicationHost.cs | 4 +- MediaBrowser.Common/Json/JsonDefaults.cs | 6 +- .../MediaBrowser.Common.csproj | 6 +- MediaBrowser.Common/Net/IPHost.cs | 2 +- MediaBrowser.Common/Net/IPNetAddress.cs | 6 +- MediaBrowser.Common/Plugins/BasePlugin.cs | 2 +- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 36 ++++++----- MediaBrowser.Common/Plugins/LocalPlugin.cs | 6 +- .../Progress/ActionableProgress.cs | 1 + .../Progress/SimpleProgress.cs | 1 + .../Entities/CollectionFolder.cs | 2 +- .../MediaBrowser.Controller.csproj | 6 +- .../Providers/ILocalImageProvider.cs | 2 +- .../CollectionFolderLocalImageProvider.cs | 2 +- .../Images/EpisodeLocalImageProvider.cs | 2 +- .../InternalMetadataFolderImageProvider.cs | 7 ++- .../Images/LocalImageProvider.cs | 14 ++--- .../MediaBrowser.LocalMetadata.csproj | 6 +- .../Parsers/BaseItemXmlParser.cs | 4 +- .../Parsers/BoxSetXmlParser.cs | 6 +- .../Parsers/PlaylistXmlParser.cs | 6 +- .../Savers/BaseXmlSaver.cs | 17 ++---- .../Encoder/MediaEncoder.cs | 2 +- .../Plugins/AudioDb/AlbumImageProvider.cs | 2 +- .../Plugins/AudioDb/AlbumProvider.cs | 2 +- .../Plugins/AudioDb/ArtistImageProvider.cs | 2 +- .../Plugins/AudioDb/ArtistProvider.cs | 2 +- .../Plugins/Omdb/OmdbItemProvider.cs | 2 +- .../Plugins/Omdb/OmdbProvider.cs | 2 +- .../FFprobeParserTests.cs | 2 +- .../Controllers/DashboardControllerTests.cs | 2 +- 70 files changed, 151 insertions(+), 213 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index d7b75f9796..552cd501b7 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -36,7 +36,7 @@ namespace Emby.Dlna private readonly ILogger _logger; private readonly IServerApplicationHost _appHost; private static readonly Assembly _assembly = typeof(DlnaManager).Assembly; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private readonly Dictionary> _profiles = new Dictionary>(StringComparer.Ordinal); diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 835dc33b0f..164e6d49de 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -10,8 +10,6 @@ using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; -using System.Text; -using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Emby.Dlna; @@ -51,7 +49,6 @@ using Jellyfin.Networking.Manager; using MediaBrowser.Common; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; -using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; @@ -470,7 +467,7 @@ namespace Emby.Server.Implementations } /// - public IReadOnlyCollection GetExports(CreationDelegate defaultFunc, bool manageLifetime = true) + public IReadOnlyCollection GetExports(CreationDelegateFactory defaultFunc, bool manageLifetime = true) { // Convert to list so this isn't executed for each iteration var parts = GetExportTypes() diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 8c5fa09f69..87ebe960ab 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -49,7 +49,7 @@ namespace Emby.Server.Implementations.Channels private readonly IProviderManager _providerManager; private readonly IMemoryCache _memoryCache; private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1); - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; /// /// Initializes a new instance of the class. diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index d78b93bd78..2ae8054478 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.Data _imageProcessor = imageProcessor; _typeMapper = new TypeMapper(); - _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions = JsonDefaults.Options; DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db"); } diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index 7e0c2c1da2..06acb56061 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -56,7 +56,7 @@ namespace Emby.Server.Implementations.HttpServer RemoteEndPoint = remoteEndPoint; QueryString = query; - _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions = JsonDefaults.Options; LastActivityDate = DateTime.Now; } diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index 2070df31e4..c2951dd155 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -25,7 +25,7 @@ namespace Emby.Server.Implementations.Library private readonly IMediaEncoder _mediaEncoder; private readonly ILogger _logger; private readonly IApplicationPaths _appPaths; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IApplicationPaths appPaths) { diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index c63eb70179..b2943020c5 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -46,7 +46,7 @@ namespace Emby.Server.Implementations.Library private readonly ConcurrentDictionary _openStreams = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1); - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private IMediaSourceProvider[] _providers; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 78a82118ed..44a8cdee49 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private readonly IServerApplicationPaths _appPaths; private readonly TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); private readonly IServerConfigurationManager _serverConfigurationManager; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private bool _hasExited; private Stream _logFileStream; private string _targetPath; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 57424f0435..c20b080883 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { private readonly string _dataPath; private readonly object _fileDataLock = new object(); - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private T[] _items; public ItemDataProvider( diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 6d7c5ac6ee..1926e738f2 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -35,7 +35,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings private readonly ICryptoProvider _cryptoProvider; private readonly ConcurrentDictionary _tokens = new ConcurrentDictionary(); - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private DateTime _lastErrorResponse; public SchedulesDirect( diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 0760e81274..68173a0ef7 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -61,7 +61,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun _networkManager = networkManager; _streamHelper = streamHelper; - _jsonOptions = JsonDefaults.GetOptions(); + _jsonOptions = JsonDefaults.Options; } public string Name => "HD Homerun"; diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 3f9e221066..98de848bca 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Localization private List _cultures; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; /// /// Initializes a new instance of the class. diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index c579fc8cba..700396c4cf 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -70,7 +70,7 @@ namespace Emby.Server.Implementations.Plugins _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _pluginsPath = pluginsPath; _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion)); - _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()) + _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options) { WriteIndented = true }; @@ -678,7 +678,7 @@ namespace Emby.Server.Implementations.Plugins var entry = versions[x]; if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase)) { - entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories)); + entry.DllFiles = Directory.GetFiles(entry.Path, "*.dll", SearchOption.AllDirectories); if (entry.IsEnabledAndSupported) { lastName = entry.Name; diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index b302303f88..a145a84237 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -69,7 +69,7 @@ namespace Emby.Server.Implementations.ScheduledTasks /// /// The options for the json Serializer. /// - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; /// /// Initializes a new instance of the class. diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 7af52ea652..fc34f93cdd 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.Updates _httpClientFactory = httpClientFactory; _config = config; _zipClient = zipClient; - _jsonSerializerOptions = JsonDefaults.GetOptions(); + _jsonSerializerOptions = JsonDefaults.Options; _pluginManager = pluginManager; } diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index e1c9f69f61..049a4bed7b 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -25,7 +25,7 @@ namespace Jellyfin.Api.Controllers private readonly IServerConfigurationManager _configurationManager; private readonly IMediaEncoder _mediaEncoder; - private readonly JsonSerializerOptions _serializerOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _serializerOptions = JsonDefaults.Options; /// /// Initializes a new instance of the class. diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index a5aa9bfcae..24285bfb98 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -45,7 +45,7 @@ namespace Jellyfin.Api.Controllers { _installationManager = installationManager; _pluginManager = pluginManager; - _serializerOptions = JsonDefaults.GetOptions(); + _serializerOptions = JsonDefaults.Options; _config = config; } diff --git a/Jellyfin.Data/DayOfWeekHelper.cs b/Jellyfin.Data/DayOfWeekHelper.cs index 4e75f4cfd1..8d760a1556 100644 --- a/Jellyfin.Data/DayOfWeekHelper.cs +++ b/Jellyfin.Data/DayOfWeekHelper.cs @@ -1,67 +1,21 @@ #pragma warning disable CS1591 using System; -using System.Collections.Generic; using Jellyfin.Data.Enums; namespace Jellyfin.Data { public static class DayOfWeekHelper { - public static List GetDaysOfWeek(DynamicDayOfWeek day) + public static DayOfWeek[] GetDaysOfWeek(DynamicDayOfWeek day) { - var days = new List(7); - - if (day == DynamicDayOfWeek.Sunday - || day == DynamicDayOfWeek.Weekend - || day == DynamicDayOfWeek.Everyday) + return day switch { - days.Add(DayOfWeek.Sunday); - } - - if (day == DynamicDayOfWeek.Monday - || day == DynamicDayOfWeek.Weekday - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Monday); - } - - if (day == DynamicDayOfWeek.Tuesday - || day == DynamicDayOfWeek.Weekday - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Tuesday); - } - - if (day == DynamicDayOfWeek.Wednesday - || day == DynamicDayOfWeek.Weekday - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Wednesday); - } - - if (day == DynamicDayOfWeek.Thursday - || day == DynamicDayOfWeek.Weekday - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Thursday); - } - - if (day == DynamicDayOfWeek.Friday - || day == DynamicDayOfWeek.Weekday - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Friday); - } - - if (day == DynamicDayOfWeek.Saturday - || day == DynamicDayOfWeek.Weekend - || day == DynamicDayOfWeek.Everyday) - { - days.Add(DayOfWeek.Saturday); - } - - return days; + DynamicDayOfWeek.Everyday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday }, + DynamicDayOfWeek.Weekday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, + DynamicDayOfWeek.Weekend => new[] { DayOfWeek.Saturday, DayOfWeek.Sunday }, + _ => new[] { (DayOfWeek)day } + }; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Collection.cs b/Jellyfin.Data/Entities/Libraries/Collection.cs index 39eded752d..854f17f802 100644 --- a/Jellyfin.Data/Entities/Libraries/Collection.cs +++ b/Jellyfin.Data/Entities/Libraries/Collection.cs @@ -1,3 +1,4 @@ +#pragma warning disable CA1711 // Identifiers should not have incorrect suffix #pragma warning disable CA2227 using System.Collections.Generic; diff --git a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs index 5b03e260e2..5e27156a45 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs @@ -1,3 +1,5 @@ +#pragma warning disable CA1711 // Identifiers should not have incorrect suffix + using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs index d92e5d9d25..0162e1acf8 100644 --- a/Jellyfin.Data/Entities/Permission.cs +++ b/Jellyfin.Data/Entities/Permission.cs @@ -1,3 +1,5 @@ +#pragma warning disable CA1711 // Identifiers should not have incorrect suffix + using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Enums; diff --git a/Jellyfin.Data/Jellyfin.Data.csproj b/Jellyfin.Data/Jellyfin.Data.csproj index 42731bb119..0340cda013 100644 --- a/Jellyfin.Data/Jellyfin.Data.csproj +++ b/Jellyfin.Data/Jellyfin.Data.csproj @@ -5,6 +5,8 @@ false true true + AllEnabledByDefault + ../jellyfin.ruleset true true true @@ -24,10 +26,6 @@ GPL-3.0-only - - ../jellyfin.ruleset - - diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index 1a8415ae0e..3fc44640b0 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -11,6 +11,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset @@ -30,6 +32,11 @@ + + + + + @@ -37,8 +44,4 @@ - - ../jellyfin.ruleset - - diff --git a/Jellyfin.Drawing.Skia/SkiaEncoder.cs b/Jellyfin.Drawing.Skia/SkiaEncoder.cs index eab5777d5d..fd7cb5ec58 100644 --- a/Jellyfin.Drawing.Skia/SkiaEncoder.cs +++ b/Jellyfin.Drawing.Skia/SkiaEncoder.cs @@ -274,8 +274,8 @@ namespace Jellyfin.Drawing.Skia if (requiresTransparencyHack || forceCleanBitmap) { - using var codec = SKCodec.Create(NormalizePath(path)); - if (codec == null) + using SKCodec codec = SKCodec.Create(NormalizePath(path), out SKCodecResult res); + if (res != SKCodecResult.Success) { origin = GetSKEncodedOrigin(orientation); return null; @@ -345,11 +345,6 @@ namespace Jellyfin.Drawing.Skia private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin) { - if (origin == SKEncodedOrigin.Default) - { - return bitmap; - } - var needsFlip = origin == SKEncodedOrigin.LeftBottom || origin == SKEncodedOrigin.LeftTop || origin == SKEncodedOrigin.RightBottom @@ -447,7 +442,7 @@ namespace Jellyfin.Drawing.Skia } /// - public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat) + public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat) { if (inputPath.Length == 0) { @@ -459,7 +454,7 @@ namespace Jellyfin.Drawing.Skia throw new ArgumentException("String can't be empty.", nameof(outputPath)); } - var skiaOutputFormat = GetImageFormat(selectedOutputFormat); + var skiaOutputFormat = GetImageFormat(outputFormat); var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor); var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer); diff --git a/Jellyfin.Networking/Jellyfin.Networking.csproj b/Jellyfin.Networking/Jellyfin.Networking.csproj index f89a184263..63557e91f0 100644 --- a/Jellyfin.Networking/Jellyfin.Networking.csproj +++ b/Jellyfin.Networking/Jellyfin.Networking.csproj @@ -5,6 +5,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset @@ -18,10 +20,6 @@ - - ../jellyfin.ruleset - - diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs index 2f9f44ed67..8b0bd84c66 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Security/AuthenticationSucceededLogger.cs @@ -29,20 +29,20 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Security } /// - public async Task OnEvent(GenericEventArgs e) + public async Task OnEvent(GenericEventArgs eventArgs) { await _activityManager.CreateAsync(new ActivityLog( string.Format( CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("AuthenticationSucceededWithUserName"), - e.Argument.User.Name), + eventArgs.Argument.User.Name), "AuthenticationSucceeded", - e.Argument.User.Id) + eventArgs.Argument.User.Id) { ShortOverview = string.Format( CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("LabelIpAddressValue"), - e.Argument.SessionInfo.RemoteEndPoint), + eventArgs.Argument.SessionInfo.RemoteEndPoint), }).ConfigureAwait(false); } } diff --git a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs index 05201a3469..cbc9f30173 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/System/TaskCompletedLogger.cs @@ -33,10 +33,10 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.System } /// - public async Task OnEvent(TaskCompletionEventArgs e) + public async Task OnEvent(TaskCompletionEventArgs eventArgs) { - var result = e.Result; - var task = e.Task; + var result = eventArgs.Result; + var task = eventArgs.Task; if (task.ScheduledTask is IConfigurableScheduledTask activityTask && !activityTask.IsLogged) @@ -54,14 +54,14 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.System { var vals = new List(); - if (!string.IsNullOrEmpty(e.Result.ErrorMessage)) + if (!string.IsNullOrEmpty(eventArgs.Result.ErrorMessage)) { - vals.Add(e.Result.ErrorMessage); + vals.Add(eventArgs.Result.ErrorMessage); } - if (!string.IsNullOrEmpty(e.Result.LongErrorMessage)) + if (!string.IsNullOrEmpty(eventArgs.Result.LongErrorMessage)) { - vals.Add(e.Result.LongErrorMessage); + vals.Add(eventArgs.Result.LongErrorMessage); } await _activityManager.CreateAsync(new ActivityLog( diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs index 91a30069e8..eb7572ac66 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Updates/PluginUninstalledLogger.cs @@ -30,13 +30,13 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Updates } /// - public async Task OnEvent(PluginUninstalledEventArgs e) + public async Task OnEvent(PluginUninstalledEventArgs eventArgs) { await _activityManager.CreateAsync(new ActivityLog( string.Format( CultureInfo.InvariantCulture, _localizationManager.GetLocalizedString("PluginUninstalledWithName"), - e.Argument.Name), + eventArgs.Argument.Name), NotificationType.PluginUninstalled.ToString(), Guid.Empty)) .ConfigureAwait(false); diff --git a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs index a14911b94a..9beb6f2f25 100644 --- a/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs +++ b/Jellyfin.Server.Implementations/Events/Consumers/Users/UserUpdatedNotifier.cs @@ -30,12 +30,12 @@ namespace Jellyfin.Server.Implementations.Events.Consumers.Users } /// - public async Task OnEvent(UserUpdatedEventArgs e) + public async Task OnEvent(UserUpdatedEventArgs eventArgs) { await _sessionManager.SendMessageToUserSessions( - new List { e.Argument.Id }, + new List { eventArgs.Argument.Id }, SessionMessageType.UserUpdated, - _userManager.GetUserDto(e.Argument), + _userManager.GetUserDto(eventArgs.Argument), CancellationToken.None).ConfigureAwait(false); } } diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 19c7ac5672..5a5992bd65 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -6,6 +6,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset diff --git a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs index 9cc1c3e5e5..c99c5e4efc 100644 --- a/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs +++ b/Jellyfin.Server.Implementations/Users/DefaultPasswordResetProvider.cs @@ -66,7 +66,7 @@ namespace Jellyfin.Server.Implementations.Users else if (string.Equals( spr.Pin.Replace("-", string.Empty, StringComparison.Ordinal), pin.Replace("-", string.Empty, StringComparison.Ordinal), - StringComparison.InvariantCultureIgnoreCase)) + StringComparison.OrdinalIgnoreCase)) { var resetUser = userManager.GetUserByName(spr.UserName) ?? throw new ResourceNotFoundException($"User with a username of {spr.UserName} not found"); diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs index c8a589cabc..a3e9516b9f 100644 --- a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs +++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs @@ -1,4 +1,5 @@ #pragma warning disable CA1307 +#pragma warning disable CA1309 using System; using System.Collections.Generic; @@ -35,7 +36,7 @@ namespace Jellyfin.Server.Implementations.Users if (prefs == null) { - prefs = new DisplayPreferences(userId, itemId, client); + prefs = new DisplayPreferences(userId, itemId, client); _dbContext.DisplayPreferences.Add(prefs); } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 1828f1a7eb..a3f49e6cb1 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -225,7 +225,7 @@ namespace Jellyfin.Server.Extensions .AddJsonOptions(options => { // Update all properties that are set in JsonDefaults - var jsonOptions = JsonDefaults.GetPascalCaseOptions(); + var jsonOptions = JsonDefaults.PascalCaseOptions; // From JsonDefaults options.JsonSerializerOptions.ReadCommentHandling = jsonOptions.ReadCommentHandling; diff --git a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs index 8043989b1e..c349e3dca2 100644 --- a/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs +++ b/Jellyfin.Server/Formatters/CamelCaseJsonProfileFormatter.cs @@ -12,7 +12,7 @@ namespace Jellyfin.Server.Formatters /// /// Initializes a new instance of the class. /// - public CamelCaseJsonProfileFormatter() : base(JsonDefaults.GetCamelCaseOptions()) + public CamelCaseJsonProfileFormatter() : base(JsonDefaults.CamelCaseOptions) { SupportedMediaTypes.Clear(); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(JsonDefaults.CamelCaseMediaType)); diff --git a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs index d0110b125c..0480f5e0ec 100644 --- a/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs +++ b/Jellyfin.Server/Formatters/PascalCaseJsonProfileFormatter.cs @@ -13,7 +13,7 @@ namespace Jellyfin.Server.Formatters /// /// Initializes a new instance of the class. /// - public PascalCaseJsonProfileFormatter() : base(JsonDefaults.GetPascalCaseOptions()) + public PascalCaseJsonProfileFormatter() : base(JsonDefaults.PascalCaseOptions) { SupportedMediaTypes.Clear(); // Add application/json for default formatter diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 6bfb5b8786..09799307b7 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -13,7 +13,9 @@ true true enable - true + AllEnabledByDefault + ../jellyfin.ruleset + @@ -31,10 +33,6 @@ - - ../jellyfin.ruleset - - diff --git a/Jellyfin.Server/Migrations/MigrationOptions.cs b/Jellyfin.Server/Migrations/MigrationOptions.cs index 816dd9ee74..c9710f1fd1 100644 --- a/Jellyfin.Server/Migrations/MigrationOptions.cs +++ b/Jellyfin.Server/Migrations/MigrationOptions.cs @@ -16,9 +16,12 @@ namespace Jellyfin.Server.Migrations Applied = new List<(Guid Id, string Name)>(); } +// .Net xml serializer can't handle interfaces +#pragma warning disable CA1002 // Do not expose generic lists /// /// Gets the list of applied migration routine names. /// public List<(Guid Id, string Name)> Applied { get; } +#pragma warning restore CA1002 } } diff --git a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs index 33f039c394..d61c044478 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs @@ -76,7 +76,7 @@ namespace Jellyfin.Server.Migrations.Routines foreach (var entry in queryResult) { - UserMockup? mockup = JsonSerializer.Deserialize(entry[2].ToBlob(), JsonDefaults.GetOptions()); + UserMockup? mockup = JsonSerializer.Deserialize(entry[2].ToBlob(), JsonDefaults.Options); if (mockup == null) { continue; diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 6ae0542c03..4f203b7a9d 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -222,7 +222,7 @@ namespace Jellyfin.Server } finally { - appHost?.Dispose(); + appHost.Dispose(); } if (_restartOnShutdown) @@ -623,7 +623,7 @@ namespace Jellyfin.Server string commandLineArgsString; if (options.RestartArgs != null) { - commandLineArgsString = options.RestartArgs ?? string.Empty; + commandLineArgsString = options.RestartArgs; } else { diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index ddcf2ac171..c3e4ed6db8 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -10,7 +10,7 @@ namespace MediaBrowser.Common /// /// Type to create. /// New instance of type type. - public delegate object CreationDelegate(Type type); + public delegate object CreationDelegateFactory(Type type); /// /// An interface to be implemented by the applications hosting a kernel. @@ -112,7 +112,7 @@ namespace MediaBrowser.Common /// Delegate function that gets called to create the object. /// If set to true [manage lifetime]. /// . - IReadOnlyCollection GetExports(CreationDelegate defaultFunc, bool manageLifetime = true); + IReadOnlyCollection GetExports(CreationDelegateFactory defaultFunc, bool manageLifetime = true); /// /// Gets the export types. diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs index 2ef24a884a..177ad39fa8 100644 --- a/MediaBrowser.Common/Json/JsonDefaults.cs +++ b/MediaBrowser.Common/Json/JsonDefaults.cs @@ -61,7 +61,7 @@ namespace MediaBrowser.Common.Json /// If the defaults must be modified the author must use the copy constructor. /// /// The default options. - public static JsonSerializerOptions GetOptions() + public static JsonSerializerOptions Options => _jsonSerializerOptions; /// @@ -72,7 +72,7 @@ namespace MediaBrowser.Common.Json /// If the defaults must be modified the author must use the copy constructor. /// /// The camelCase options. - public static JsonSerializerOptions GetCamelCaseOptions() + public static JsonSerializerOptions CamelCaseOptions => _camelCaseJsonSerializerOptions; /// @@ -83,7 +83,7 @@ namespace MediaBrowser.Common.Json /// If the defaults must be modified the author must use the copy constructor. /// /// The PascalCase options. - public static JsonSerializerOptions GetPascalCaseOptions() + public static JsonSerializerOptions PascalCaseOptions => _pascalCaseJsonSerializerOptions; } } diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 34e1934e25..0d9f78704e 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -33,6 +33,8 @@ false true true + AllEnabledByDefault + ../jellyfin.ruleset true true true @@ -51,10 +53,6 @@ - - ../jellyfin.ruleset - - <_Parameter1>Jellyfin.Common.Tests diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 4a7c701907..d67b6b8e15 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -406,7 +406,7 @@ namespace MediaBrowser.Common.Net } // If we haven't resolved before, or our timer has run out... - if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved?.AddMinutes(Timeout))) + if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout))) { _lastResolved = DateTime.UtcNow; ResolveHostInternal().GetAwaiter().GetResult(); diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index 5fab52eac7..59e37a5c6c 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -216,11 +216,11 @@ namespace MediaBrowser.Common.Net } /// - public override bool Equals(IPAddress address) + public override bool Equals(IPAddress ip) { - if (address != null && !address.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) + if (ip != null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) { - return address.Equals(Address); + return ip.Equals(Address); } return false; diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index 7b162c0e1c..ad5a7338dd 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Common.Plugins /// Gets a value indicating whether the plugin can be uninstalled. /// public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath) - .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture); + .Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.Ordinal); /// /// Gets the plugin info. diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index d5c7808512..99c226f509 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -39,29 +39,27 @@ namespace MediaBrowser.Common.Plugins { ApplicationPaths = applicationPaths; XmlSerializer = xmlSerializer; - if (this is IPluginAssembly assemblyPlugin) + + var assembly = GetType().Assembly; + var assemblyName = assembly.GetName(); + var assemblyFilePath = assembly.Location; + + var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); + if (!Directory.Exists(dataFolderPath) && Version != null) { - var assembly = GetType().Assembly; - var assemblyName = assembly.GetName(); - var assemblyFilePath = assembly.Location; + // Try again with the version number appended to the folder name. + dataFolderPath = dataFolderPath + "_" + Version.ToString(); + } - var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath)); - if (!Directory.Exists(dataFolderPath) && Version != null) - { - // Try again with the version number appended to the folder name. - dataFolderPath = dataFolderPath + "_" + Version.ToString(); - } + SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); - assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version); + var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); + if (idAttributes.Length > 0) + { + var attribute = (GuidAttribute)idAttributes[0]; + var assemblyId = new Guid(attribute.Value); - var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true); - if (idAttributes.Length > 0) - { - var attribute = (GuidAttribute)idAttributes[0]; - var assemblyId = new Guid(attribute.Value); - - assemblyPlugin.SetId(assemblyId); - } + SetId(assemblyId); } } diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 23b6cfa81a..12a1ad1ec8 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.Common.Plugins public LocalPlugin(string path, bool isSupported, PluginManifest manifest) { Path = path; - DllFiles = new List(); + DllFiles = Array.Empty(); _supported = isSupported; Manifest = manifest; } @@ -59,9 +59,9 @@ namespace MediaBrowser.Common.Plugins public string Path { get; } /// - /// Gets the list of dll files for this plugin. + /// Gets or sets the list of dll files for this plugin. /// - public List DllFiles { get; } + public IReadOnlyList DllFiles { get; set; } /// /// Gets or sets the instance of this plugin. diff --git a/MediaBrowser.Common/Progress/ActionableProgress.cs b/MediaBrowser.Common/Progress/ActionableProgress.cs index d5bcd5be96..fe7cb10788 100644 --- a/MediaBrowser.Common/Progress/ActionableProgress.cs +++ b/MediaBrowser.Common/Progress/ActionableProgress.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable CA1003 using System; diff --git a/MediaBrowser.Common/Progress/SimpleProgress.cs b/MediaBrowser.Common/Progress/SimpleProgress.cs index d75675bf17..988d8ad34a 100644 --- a/MediaBrowser.Common/Progress/SimpleProgress.cs +++ b/MediaBrowser.Common/Progress/SimpleProgress.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#pragma warning disable CA1003 using System; diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 65fd1654c3..76b6d39a93 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Controller.Entities /// public class CollectionFolder : Folder, ICollectionFolder { - private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public static IXmlSerializer XmlSerializer { get; set; } public static IServerApplicationHost ApplicationHost { get; set; } diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index d487a324f4..8c68b47dd7 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -34,6 +34,8 @@ false true true + AllEnabledByDefault + ../jellyfin.ruleset true true true @@ -52,8 +54,4 @@ - - ../jellyfin.ruleset - - diff --git a/MediaBrowser.Controller/Providers/ILocalImageProvider.cs b/MediaBrowser.Controller/Providers/ILocalImageProvider.cs index c129eddb3a..f78bd6ddf4 100644 --- a/MediaBrowser.Controller/Providers/ILocalImageProvider.cs +++ b/MediaBrowser.Controller/Providers/ILocalImageProvider.cs @@ -10,6 +10,6 @@ namespace MediaBrowser.Controller.Providers /// public interface ILocalImageProvider : IImageProvider { - List GetImages(BaseItem item, IDirectoryService directoryService); + IEnumerable GetImages(BaseItem item, IDirectoryService directoryService); } } diff --git a/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs index 556bb6a0e4..b6189bcdd6 100644 --- a/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/CollectionFolderLocalImageProvider.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.LocalMetadata.Images } /// - public List GetImages(BaseItem item, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, IDirectoryService directoryService) { var collectionFolder = (CollectionFolder)item; diff --git a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs index 393ad2efb5..2d3b2d889c 100644 --- a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs @@ -39,7 +39,7 @@ namespace MediaBrowser.LocalMetadata.Images } /// - public List GetImages(BaseItem item, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, IDirectoryService directoryService) { var parentPath = Path.GetDirectoryName(item.Path); diff --git a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs index 509b5d700d..10d691b3e9 100644 --- a/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/InternalMetadataFolderImageProvider.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; @@ -69,13 +70,13 @@ namespace MediaBrowser.LocalMetadata.Images } /// - public List GetImages(BaseItem item, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, IDirectoryService directoryService) { var path = item.GetInternalMetadataPath(); if (!Directory.Exists(path)) { - return new List(); + return Enumerable.Empty(); } try @@ -85,7 +86,7 @@ namespace MediaBrowser.LocalMetadata.Images catch (IOException ex) { _logger.LogError(ex, "Error while getting images for {Library}", item.Name); - return new List(); + return Enumerable.Empty(); } } } diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs index 84c3ed8b0b..7ad8c24e89 100644 --- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs @@ -108,7 +108,7 @@ namespace MediaBrowser.LocalMetadata.Images { if (!item.IsFileProtocol) { - return new List(); + return Enumerable.Empty(); } var path = item.ContainingFolderPath; @@ -116,7 +116,7 @@ namespace MediaBrowser.LocalMetadata.Images // Exit if the cache dir does not exist, alternative solution is to create it, but that's a lot of empty dirs... if (!Directory.Exists(path)) { - return Array.Empty(); + return Enumerable.Empty(); } if (includeDirectories) @@ -133,7 +133,7 @@ namespace MediaBrowser.LocalMetadata.Images } /// - public List GetImages(BaseItem item, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, IDirectoryService directoryService) { var files = GetFiles(item, true, directoryService).ToList(); @@ -151,7 +151,7 @@ namespace MediaBrowser.LocalMetadata.Images /// The images path. /// Instance of the interface. /// The local image info. - public List GetImages(BaseItem item, string path, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, string path, IDirectoryService directoryService) { return GetImages(item, new[] { path }, directoryService); } @@ -163,7 +163,7 @@ namespace MediaBrowser.LocalMetadata.Images /// The image paths. /// Instance of the interface. /// The local image info. - public List GetImages(BaseItem item, IEnumerable paths, IDirectoryService directoryService) + public IEnumerable GetImages(BaseItem item, IEnumerable paths, IDirectoryService directoryService) { IEnumerable files = paths.SelectMany(i => _fileSystem.GetFiles(i, BaseItem.SupportedImageExtensions, true, false)); @@ -181,9 +181,7 @@ namespace MediaBrowser.LocalMetadata.Images { if (supportParentSeriesFiles) { - var season = item as Season; - - if (season != null) + if (item is Season season) { PopulateSeasonImagesFromSeriesFolder(season, images, directoryService); } diff --git a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj index 1792f1d9b6..eb2077a5ff 100644 --- a/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj +++ b/MediaBrowser.LocalMetadata/MediaBrowser.LocalMetadata.csproj @@ -16,6 +16,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset @@ -29,8 +31,4 @@ - - ../jellyfin.ruleset - - diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index b0afb834b1..5f620634fb 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -1275,8 +1275,8 @@ namespace MediaBrowser.LocalMetadata.Parsers // Only split by comma if there is no pipe in the string // We have to be careful to not split names like Matthew, Jr. - var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 - && value.IndexOf(';', StringComparison.Ordinal) == -1 ? new[] { ',' } : new[] { '|', ';' }; + var separator = !value.Contains('|', StringComparison.Ordinal) + && !value.Contains(';', StringComparison.Ordinal) ? new[] { ',' } : new[] { '|', ';' }; value = value.Trim().Trim(separator); diff --git a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs index ff846830bf..7df800971a 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BoxSetXmlParser.cs @@ -23,7 +23,7 @@ namespace MediaBrowser.LocalMetadata.Parsers } /// - protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult item) + protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult itemResult) { switch (reader.Name) { @@ -33,7 +33,7 @@ namespace MediaBrowser.LocalMetadata.Parsers { using (var subReader = reader.ReadSubtree()) { - FetchFromCollectionItemsNode(subReader, item); + FetchFromCollectionItemsNode(subReader, itemResult); } } else @@ -44,7 +44,7 @@ namespace MediaBrowser.LocalMetadata.Parsers break; default: - base.FetchDataFromXmlNode(reader, item); + base.FetchDataFromXmlNode(reader, itemResult); break; } } diff --git a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs index 78c0fa8ad3..b84307cb20 100644 --- a/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/PlaylistXmlParser.cs @@ -23,9 +23,9 @@ namespace MediaBrowser.LocalMetadata.Parsers } /// - protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult result) + protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult itemResult) { - var item = result.Item; + var item = itemResult.Item; switch (reader.Name) { @@ -53,7 +53,7 @@ namespace MediaBrowser.LocalMetadata.Parsers break; default: - base.FetchDataFromXmlNode(reader, result); + base.FetchDataFromXmlNode(reader, itemResult); break; } } diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index e59fcb965b..dfbce5f49a 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Text; using System.Threading; using System.Xml; -using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -37,7 +36,7 @@ namespace MediaBrowser.LocalMetadata.Savers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - public BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger) + protected BaseXmlSaver(IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataManager, ILogger logger) { FileSystem = fileSystem; ConfigurationManager = configurationManager; @@ -421,20 +420,17 @@ namespace MediaBrowser.LocalMetadata.Savers writer.WriteEndElement(); } - var boxset = item as BoxSet; - if (boxset != null) + if (item is BoxSet boxset) { AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem"); } - var playlist = item as Playlist; - if (playlist != null && !Playlist.IsPlaylistFile(playlist.Path)) + if (item is Playlist playlist && !Playlist.IsPlaylistFile(playlist.Path)) { AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem"); } - var hasShares = item as IHasShares; - if (hasShares != null) + if (item is IHasShares hasShares) { AddShares(hasShares, writer); } @@ -542,10 +538,5 @@ namespace MediaBrowser.LocalMetadata.Savers writer.WriteEndElement(); } - - private bool IsPersonType(PersonInfo person, string type) - { - return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase); - } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 8a25a64c74..47cf020b4e 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -86,7 +86,7 @@ namespace MediaBrowser.MediaEncoding.Encoder _localization = localization; _encodingHelperFactory = encodingHelperFactory; _startupOptionFFmpegPath = config.GetValue(Controller.Extensions.ConfigurationExtensions.FfmpegPathKey) ?? string.Empty; - _jsonSerializerOptions = JsonDefaults.GetOptions(); + _jsonSerializerOptions = JsonDefaults.Options; } /// diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index cd9e477432..2adb119087 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public AudioDbAlbumImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 0a79f5bb59..00feeec1f9 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -29,7 +29,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public static AudioDbAlbumProvider Current; diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index 36700d1917..b8095ff04c 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -22,7 +22,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb { private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public AudioDbArtistImageProvider(IServerConfigurationManager config, IHttpClientFactory httpClientFactory) { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 4b1d915671..59ecbc0171 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -31,7 +31,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; private readonly IHttpClientFactory _httpClientFactory; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public AudioDbArtistProvider(IServerConfigurationManager config, IFileSystem fileSystem, IHttpClientFactory httpClientFactory) { diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs index 97fcbfb6fe..428b0ded11 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbItemProvider.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb _configurationManager = configurationManager; _appHost = appHost; - _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); + _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); } diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index e3301ff329..d35805a84b 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -39,7 +39,7 @@ namespace MediaBrowser.Providers.Plugins.Omdb _configurationManager = configurationManager; _appHost = appHost; - _jsonOptions = new JsonSerializerOptions(JsonDefaults.GetOptions()); + _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableStringConverter()); _jsonOptions.Converters.Add(new JsonOmdbNotAvailableInt32Converter()); } diff --git a/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs index c39ef0ce99..415682e855 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/FFprobeParserTests.cs @@ -16,7 +16,7 @@ namespace Jellyfin.MediaEncoding.Tests var path = Path.Join("Test Data", fileName); using (var stream = File.OpenRead(path)) { - await JsonSerializer.DeserializeAsync(stream, JsonDefaults.GetOptions()).ConfigureAwait(false); + await JsonSerializer.DeserializeAsync(stream, JsonDefaults.Options).ConfigureAwait(false); } } } diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs index 86d6326d84..f5411dcb8d 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/DashboardControllerTests.cs @@ -13,7 +13,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers public sealed class DashboardControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; - private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.GetOptions(); + private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options; public DashboardControllerTests(JellyfinApplicationFactory factory) { From 46a41ecba66f8055a9e7de4d0dd4a1e07ea371a3 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 9 Mar 2021 17:01:14 +0100 Subject: [PATCH 1294/1930] Sunday isn't a weekend --- Jellyfin.Data/DayOfWeekHelper.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Data/DayOfWeekHelper.cs b/Jellyfin.Data/DayOfWeekHelper.cs index 8d760a1556..1bfd4a0c69 100644 --- a/Jellyfin.Data/DayOfWeekHelper.cs +++ b/Jellyfin.Data/DayOfWeekHelper.cs @@ -12,8 +12,8 @@ namespace Jellyfin.Data return day switch { DynamicDayOfWeek.Everyday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday }, - DynamicDayOfWeek.Weekday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, - DynamicDayOfWeek.Weekend => new[] { DayOfWeek.Saturday, DayOfWeek.Sunday }, + DynamicDayOfWeek.Weekday => new[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, + DynamicDayOfWeek.Weekend => new[] { DayOfWeek.Sunday, DayOfWeek.Saturday }, _ => new[] { (DayOfWeek)day } }; } From 01dfa8801a74f8c6802aea33d9bce0e421601faa Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 13 Mar 2021 22:40:23 +0100 Subject: [PATCH 1295/1930] Fix GetDaysOfWeek behavior --- Jellyfin.Data/DayOfWeekHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Data/DayOfWeekHelper.cs b/Jellyfin.Data/DayOfWeekHelper.cs index 1bfd4a0c69..b7ba30180e 100644 --- a/Jellyfin.Data/DayOfWeekHelper.cs +++ b/Jellyfin.Data/DayOfWeekHelper.cs @@ -11,7 +11,7 @@ namespace Jellyfin.Data { return day switch { - DynamicDayOfWeek.Everyday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday, DayOfWeek.Sunday }, + DynamicDayOfWeek.Everyday => new[] { DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday, DayOfWeek.Saturday }, DynamicDayOfWeek.Weekday => new[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }, DynamicDayOfWeek.Weekend => new[] { DayOfWeek.Sunday, DayOfWeek.Saturday }, _ => new[] { (DayOfWeek)day } From b1f0c5eb4935904bea3a784e147d403b9d43097d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 13 Mar 2021 22:16:12 +0000 Subject: [PATCH 1296/1930] Update NetworkExtensions.cs changed description --- MediaBrowser.Common/Net/NetworkExtensions.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index cd0c2ea242..26f21b5f14 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -27,10 +27,11 @@ namespace MediaBrowser.Common.Net /// /// The . /// Item to add. - /// True if subnets that overlap should be merged (default). - public static void AddItem(this Collection source, IPObject item, bool unique = true) + /// If true the values are treated as subnets. + /// If false items are addresses. + public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true) { - if (!source.ContainsAddress(item) || !unique) + if (!source.ContainsAddress(item) || !itemsAreNetworks) { source.Add(item); } From 72d3eed15c0a24612cc8ff90475a9e19ff8c7558 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 14 Mar 2021 01:07:53 +0100 Subject: [PATCH 1297/1930] Fix integration test project --- Jellyfin.sln | 9 +++++++-- .../Jellyfin.Server.Integration.Tests.csproj | 1 - tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 7 ++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 7b81f43462..0f36e283c6 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -76,10 +76,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -214,6 +214,10 @@ Global {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.Build.0 = Release|Any CPU + {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -230,6 +234,7 @@ Global {FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 49004966b9..b0a38736ae 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -23,7 +23,6 @@ - diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 65ea28e94d..a310b0ea96 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -5,6 +5,8 @@ false true enable + AllEnabledByDefault + ../jellyfin-tests.ruleset @@ -22,7 +24,6 @@ - @@ -32,8 +33,4 @@ - - ../jellyfin-tests.ruleset - - From 6087831aa65398a6305570c4dc84f0bc2613b842 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 14 Mar 2021 17:30:25 +0000 Subject: [PATCH 1298/1930] Fixed selection of correct interface ip --- Jellyfin.Networking/Manager/NetworkManager.cs | 26 +++++++++++++------ MediaBrowser.Common/Net/NetworkExtensions.cs | 7 ++--- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index bf121737b6..9ce3b7e49a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -274,7 +274,7 @@ namespace Jellyfin.Networking.Manager if (_bindExclusions.Count > 0) { // Return all the interfaces except the ones specifically excluded. - return _interfaceAddresses.Exclude(_bindExclusions); + return _interfaceAddresses.Exclude(_bindExclusions, false); } if (individualInterfaces) @@ -299,7 +299,7 @@ namespace Jellyfin.Networking.Manager } // Remove any excluded bind interfaces. - return _bindAddresses.Exclude(_bindExclusions); + return _bindAddresses.Exclude(_bindExclusions, false); } /// @@ -388,7 +388,7 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that isn't a loopback. var interfaces = CreateCollection( _interfaceAddresses - .Exclude(_bindExclusions) + .Exclude(_bindExclusions, false) .Where(IsInLocalNetwork) .OrderBy(p => p.Tag)); @@ -396,6 +396,16 @@ namespace Jellyfin.Networking.Manager { if (haveSource) { + foreach (var intf in interfaces) + { + if (intf.Address.Equals(source.Address)) + { + result = FormatIP6String(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result); + return result; + } + } + // Does the request originate in one of the interface subnets? // (For systems with multiple internal network cards, and multiple subnets) foreach (var intf in interfaces) @@ -522,10 +532,10 @@ namespace Jellyfin.Networking.Manager { if (filter == null) { - return _lanSubnets.Exclude(_excludedSubnets).AsNetworks(); + return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks(); } - return _lanSubnets.Exclude(filter); + return _lanSubnets.Exclude(filter, true); } /// @@ -1018,7 +1028,7 @@ namespace Jellyfin.Networking.Manager _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString()); - _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets).AsNetworks().AsString()); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString()); } } @@ -1207,7 +1217,7 @@ namespace Jellyfin.Networking.Manager private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) { result = string.Empty; - var addresses = _bindAddresses.Exclude(_bindExclusions); + var addresses = _bindAddresses.Exclude(_bindExclusions, false); int count = addresses.Count; if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) @@ -1292,7 +1302,7 @@ namespace Jellyfin.Networking.Manager result = string.Empty; // Get the first WAN interface address that isn't a loopback. var extResult = _interfaceAddresses - .Exclude(_bindExclusions) + .Exclude(_bindExclusions, false) .Where(p => !IsInLocalNetwork(p)) .OrderBy(p => p.Tag); diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 26f21b5f14..93cfb4817b 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -27,7 +27,7 @@ namespace MediaBrowser.Common.Net /// /// The . /// Item to add. - /// If true the values are treated as subnets. + /// If true the values are treated as subnets. /// If false items are addresses. public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true) { @@ -192,8 +192,9 @@ namespace MediaBrowser.Common.Net /// /// The . /// Items to exclude. + /// Collection is a network collection. /// A new collection, with the items excluded. - public static Collection Exclude(this Collection source, Collection excludeList) + public static Collection Exclude(this Collection source, Collection excludeList, bool isNetwork) { if (source.Count == 0 || excludeList == null) { @@ -218,7 +219,7 @@ namespace MediaBrowser.Common.Net if (!found) { - results.AddItem(outer); + results.AddItem(outer, isNetwork); } } From ab0cff8556403e123642dc9717ba778329554634 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 14 Mar 2021 19:56:45 +0100 Subject: [PATCH 1299/1930] do not resolve episode-like files if they are in extras folders --- .../Library/Resolvers/BaseVideoResolver.cs | 2 +- .../Library/Resolvers/Books/BookResolver.cs | 2 +- .../Library/Resolvers/Movies/MovieResolver.cs | 208 +++++++++--------- .../Library/Resolvers/TV/EpisodeResolver.cs | 12 +- .../Resolvers/BaseItemResolver.cs | 2 +- 5 files changed, 114 insertions(+), 112 deletions(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 2f5e46038d..dd92e252fa 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -30,7 +30,7 @@ namespace Emby.Server.Implementations.Library.Resolvers /// /// The args. /// `0. - protected override T Resolve(ItemResolveArgs args) + public override T Resolve(ItemResolveArgs args) { return ResolveVideo(args, false); } diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs index 86242d1379..0525c7e307 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs @@ -13,7 +13,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books { private readonly string[] _validExtensions = { ".azw", ".azw3", ".cb7", ".cbr", ".cbt", ".cbz", ".epub", ".mobi", ".pdf" }; - protected override Book Resolve(ItemResolveArgs args) + public override Book Resolve(ItemResolveArgs args) { var collectionType = args.GetCollectionType(); diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 8ef7172de1..714bc3a84d 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -69,6 +69,110 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return result; } + /// + /// Resolves the specified args. + /// + /// The args. + /// Video. + public override Video Resolve(ItemResolveArgs args) + { + var collectionType = args.GetCollectionType(); + + // Find movies with their own folders + if (args.IsDirectory) + { + if (IsInvalid(args.Parent, collectionType)) + { + return null; + } + + var files = args.FileSystemChildren + .Where(i => !LibraryManager.IgnoreFile(i, args.Parent)) + .ToList(); + + if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase)) + { + return FindMovie(args, args.Path, args.Parent, files, args.DirectoryService, collectionType, false); + } + + if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)) + { + return FindMovie /// The args. /// Episode. - protected override Episode Resolve(ItemResolveArgs args) + public override Episode Resolve(ItemResolveArgs args) { var parent = args.Parent; @@ -34,11 +35,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV season = parent.GetParents().OfType().FirstOrDefault(); } - // If the parent is a Season or Series, then this is an Episode if the VideoResolver returns something + // If the parent is a Season or Series and the parent is not an extras folder, then this is an Episode if the VideoResolver returns something // Also handle flat tv folders - if (season != null || - string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || - args.HasParent()) + if ((season != null || + string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || + args.HasParent()) + && !BaseItem.AllExtrasTypesFolderNames.Contains(parent.Name, StringComparer.OrdinalIgnoreCase)) { var episode = ResolveVideo(args, false); diff --git a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs index 67acdd9a3c..25128a5cd0 100644 --- a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs +++ b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.Resolvers /// /// The args. /// `0. - protected virtual T Resolve(ItemResolveArgs args) + public virtual T Resolve(ItemResolveArgs args) { return null; } From 025e351f619137426a0a64074ca2ada863ccc493 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 15 Mar 2021 08:25:20 +0100 Subject: [PATCH 1300/1930] add unit tests --- .../Library/Resolvers/BaseVideoResolver.cs | 2 +- .../Library/Resolvers/TV/EpisodeResolver.cs | 20 +++--- .../Library/EpisodeResolverTest.cs | 65 +++++++++++++++++++ 3 files changed, 76 insertions(+), 11 deletions(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index dd92e252fa..6e688693be 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -42,7 +42,7 @@ namespace Emby.Server.Implementations.Library.Resolvers /// The args. /// if set to true [parse name]. /// ``0. - protected TVideoType ResolveVideo(ItemResolveArgs args, bool parseName) + protected virtual TVideoType ResolveVideo(ItemResolveArgs args, bool parseName) where TVideoType : Video, new() { var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index da65c746d9..9b4cd7a3df 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -12,6 +12,15 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// public class EpisodeResolver : BaseVideoResolver { + /// + /// Initializes a new instance of the class. + /// + /// The library manager. + public EpisodeResolver(ILibraryManager libraryManager) + : base(libraryManager) + { + } + /// /// Resolves the specified args. /// @@ -40,7 +49,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV if ((season != null || string.Equals(args.GetCollectionType(), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || args.HasParent()) - && !BaseItem.AllExtrasTypesFolderNames.Contains(parent.Name, StringComparer.OrdinalIgnoreCase)) + && (parent is Series || !BaseItem.AllExtrasTypesFolderNames.Contains(parent.Name, StringComparer.OrdinalIgnoreCase))) { var episode = ResolveVideo(args, false); @@ -76,14 +85,5 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - - /// - /// Initializes a new instance of the class. - /// - /// The library manager. - public EpisodeResolver(ILibraryManager libraryManager) - : base(libraryManager) - { - } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs new file mode 100644 index 0000000000..8765192150 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs @@ -0,0 +1,65 @@ +using System; +using Emby.Server.Implementations.Library.Resolvers.TV; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Entities; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Library +{ + public class EpisodeResolverTest + { + [Fact] + public void Resolve_GivenVideoInExtrasFolder_DoesNotResolveToEpisode() + { + var season = new Season { Name = "Season 1" }; + var parent = new Folder { Name = "extras" }; + var libraryManagerMock = new Mock(); + libraryManagerMock.Setup(x => x.GetItemById(It.IsAny())).Returns(season); + + var episodeResolver = new EpisodeResolver(libraryManagerMock.Object); + var itemResolveArgs = new ItemResolveArgs( + Mock.Of(), + Mock.Of()) + { + Parent = parent, + CollectionType = CollectionType.TvShows, + Path = "All My Children/Season 01/Extras/All My Children S01E01 - Behind The Scenes.mkv" + }; + + Assert.Null(episodeResolver.Resolve(itemResolveArgs)); + } + + [Fact] + public void Resolve_GivenVideoInExtrasSeriesFolder_ResolvesToEpisode() + { + var series = new Series { Name = "Extras" }; + + // Have to create a mock because of moq proxies not being castable to a concrete implementation + // https://github.com/jellyfin/jellyfin/blob/ab0cff8556403e123642dc9717ba778329554634/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs#L48 + var episodeResolver = new EpisodeResolverMock(Mock.Of()); + var itemResolveArgs = new ItemResolveArgs( + Mock.Of(), + Mock.Of()) + { + Parent = series, + CollectionType = CollectionType.TvShows, + Path = "Extras/Extras S01E01.mkv" + }; + Assert.NotNull(episodeResolver.Resolve(itemResolveArgs)); + } + + private class EpisodeResolverMock : EpisodeResolver + { + public EpisodeResolverMock(ILibraryManager libraryManager) : base(libraryManager) + { + } + + protected override TVideoType ResolveVideo(ItemResolveArgs args, bool parseName) => new (); + } + } +} From 23c3188501447db9def5cd5345112a76cfe04b83 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 15 Mar 2021 23:24:59 +0100 Subject: [PATCH 1301/1930] revert underscore as a multiversion separator --- Emby.Naming/Video/VideoListResolver.cs | 1 - tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs | 7 ++----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index d71d609540..7b6a1705ba 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -235,7 +235,6 @@ namespace Emby.Naming.Video // The CleanStringParser should have removed common keywords etc. return string.IsNullOrEmpty(testFilename) || testFilename[0] == '-' - || testFilename[0] == '_' || Regex.IsMatch(testFilename, @"^\[([^]]*)\]"); } diff --git a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs index 2af6667595..6e803593e8 100644 --- a/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/MultiVersionTests.cs @@ -295,12 +295,9 @@ namespace Jellyfin.Naming.Tests.Video FullName = i }).ToList()).ToList(); - Assert.Single(result); + Assert.Equal(7, result.Count); Assert.Empty(result[0].Extras); - Assert.Equal(6, result[0].AlternateVersions.Count); - Assert.False(result[0].AlternateVersions[2].Is3D); - Assert.True(result[0].AlternateVersions[3].Is3D); - Assert.True(result[0].AlternateVersions[4].Is3D); + Assert.Empty(result[0].AlternateVersions); } [Fact] From e14311ca8b86fa14033d2c02f9b003f235fa7e6a Mon Sep 17 00:00:00 2001 From: Alyssa Ross Date: Tue, 16 Mar 2021 17:40:56 +0000 Subject: [PATCH 1302/1930] Translated using Weblate (Esperanto) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/eo/ --- .../Localization/Core/eo.json | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/eo.json b/Emby.Server.Implementations/Localization/Core/eo.json index 3ff7eddae3..ca615cc8cf 100644 --- a/Emby.Server.Implementations/Localization/Core/eo.json +++ b/Emby.Server.Implementations/Localization/Core/eo.json @@ -22,5 +22,26 @@ "Artists": "Artistoj", "Application": "Aplikaĵo", "AppDeviceValues": "Aplikaĵo: {0}, Aparato: {1}", - "Albums": "Albumoj" + "Albums": "Albumoj", + "TasksLibraryCategory": "Libraro", + "VersionNumber": "Versio {0}", + "UserDownloadingItemWithValues": "{0} elŝutas {1}", + "UserCreatedWithName": "Uzanto {0} kreiĝis", + "User": "Uzanto", + "System": "Sistemo", + "Songs": "Kantoj", + "ScheduledTaskStartedWithName": "{0} komencis", + "ScheduledTaskFailedWithName": "{0} malsukcesis", + "PluginUninstalledWithName": "{0} malinstaliĝis", + "PluginInstalledWithName": "{0} instaliĝis", + "Plugin": "Kromprogramo", + "Playlists": "Ludlistoj", + "Photos": "Fotoj", + "NotificationOptionPluginUninstalled": "Kromprogramo malinstaliĝis", + "NotificationOptionNewLibraryContent": "Nova enhavo aldoniĝis", + "NotificationOptionPluginInstalled": "Kromprogramo instaliĝis", + "MusicVideos": "Muzikvideoj", + "LabelIpAddressValue": "IP-adreso: {0}", + "Genres": "Ĝenroj", + "DeviceOfflineWithName": "{0} malkonektis" } From 14cbd22fbe0a1989f70895edbd0a0f52d850d55e Mon Sep 17 00:00:00 2001 From: David Date: Tue, 16 Mar 2021 21:11:34 +0100 Subject: [PATCH 1303/1930] Use Helper Methods for provider url parsing --- .../Library/PathExtensions.cs | 5 +- .../Providers/ProviderIdParsers.cs | 119 ++++++++++++++++++ .../Parsers/BaseNfoParser.cs | 35 +++--- .../Parsers/SeriesNfoParser.cs | 3 - .../Providers/ProviderIdParserTests.cs | 63 ++++++++++ 5 files changed, 201 insertions(+), 24 deletions(-) create mode 100644 MediaBrowser.Common/Providers/ProviderIdParsers.cs create mode 100644 tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 7dcc925c2f..72fe5a854a 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text.RegularExpressions; +using MediaBrowser.Common.Providers; namespace Emby.Server.Implementations.Library { @@ -43,8 +44,8 @@ namespace Emby.Server.Implementations.Library // for imdbid we also accept pattern matching if (string.Equals(attribute, "imdbid", StringComparison.OrdinalIgnoreCase)) { - var m = Regex.Match(str, "tt([0-9]{7,8})", RegexOptions.IgnoreCase); - return m.Success ? m.Value : null; + var match = ProviderIdParsers.TryParseImdbId(str, out var imdbId); + return match ? imdbId : null; } return null; diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs new file mode 100644 index 0000000000..56e0112ddc --- /dev/null +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -0,0 +1,119 @@ +#nullable enable + +using System; +using System.Diagnostics.CodeAnalysis; + +namespace MediaBrowser.Common.Providers +{ + /// + /// Parsers for provider ids. + /// + public static class ProviderIdParsers + { + /// + /// Parses an IMDb id from a string. + /// + /// The text to parse. + /// The parsed IMDb id. + /// True if parsing was successful, false otherwise. + public static bool TryParseImdbId(string text, [NotNullWhen(true)] out string? imdbId) + { + var span = text.AsSpan(); + var tt = "tt".AsSpan(); + + while (true) + { + var ttPos = span.IndexOf(tt); + if (ttPos == -1) + { + imdbId = default; + return false; + } + + span = span.Slice(ttPos + tt.Length); + + int i = 0; + // IMDb id has a maximum of 8 digits + int max = span.Length > 8 ? 8 : span.Length; + for (; i < max; i++) + { + var c = span[i]; + + if (c < '0' || c > '9') + { + break; + } + } + + // IMDb id has a minimum of 7 digits + if (i >= 7) + { + imdbId = string.Concat(tt, span.Slice(0, i)); + return true; + } + } + } + + /// + /// Parses an TMDb id from a movie url. + /// + /// The text with the url to parse. + /// The parsed TMDb id. + /// True if parsing was successful, false otherwise. + public static bool TryParseTmdbMovieId(string text, [NotNullWhen(true)] out string? tmdbId) + => TryParseProviderId(text, "themoviedb.org/movie/", out tmdbId); + + /// + /// Parses an TMDb id from a series url. + /// + /// The text with the url to parse. + /// The parsed TMDb id. + /// True if parsing was successful, false otherwise. + public static bool TryParseTmdbSeriesId(string text, [NotNullWhen(true)] out string? tmdbId) + => TryParseProviderId(text, "themoviedb.org/tv/", out tmdbId); + + /// + /// Parses an TVDb id from a url. + /// + /// The text with the url to parse. + /// The parsed TVDb id. + /// True if parsing was successful, false otherwise. + public static bool TryParseTvdbId(string text, [NotNullWhen(true)] out string? tvdbId) + => TryParseProviderId(text, "thetvdb.com/?tab=series&id=", out tvdbId); + + private static bool TryParseProviderId(string text, string searchString, [NotNullWhen(true)] out string? providerId) + { + var span = text.AsSpan(); + var searchSpan = searchString.AsSpan(); + + while (true) + { + var searchPos = span.IndexOf(searchSpan); + if (searchPos == -1) + { + providerId = default; + return false; + } + + span = span.Slice(searchPos + searchSpan.Length); + + int i = 0; + for (; i < span.Length; i++) + { + var c = span[i]; + + if (c < '0' || c > '9') + { + break; + } + } + + if (i >= 1) + { + providerId = span.Slice(0, i).ToString(); + return true; + } + } + } + } +} diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 3129c131d0..d2fa120e8c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -6,11 +6,12 @@ using System.Globalization; using System.IO; using System.Linq; using System.Text; -using System.Text.RegularExpressions; using System.Threading; using System.Xml; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Providers; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -63,8 +64,6 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected virtual bool SupportsUrlAfterClosingXmlTag => false; - protected virtual string TmdbRegex => "themoviedb\\.org\\/movie\\/([0-9]+)"; - /// /// Fetches metadata for an item from one xml file. /// @@ -220,31 +219,29 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected void ParseProviderLinks(T item, string xml) { - // IMDB: - // https://www.imdb.com/title/tt4154796 - var imdbRegex = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.Compiled); - if (imdbRegex.Success) + if (ProviderIdParsers.TryParseImdbId(xml, out var imdbId)) { - item.SetProviderId(MetadataProvider.Imdb, imdbRegex.Value); + item.SetProviderId(MetadataProvider.Imdb, imdbId); } - // TMDB: - // https://www.themoviedb.org/movie/30287-fallo (movie) - // https://www.themoviedb.org/tv/1668-friends (tv) - var tmdbRegex = Regex.Match(xml, TmdbRegex, RegexOptions.Compiled); - if (tmdbRegex.Success) + if (item is Movie) { - item.SetProviderId(MetadataProvider.Tmdb, tmdbRegex.Groups[1].Value); + if (ProviderIdParsers.TryParseTmdbMovieId(xml, out var tmdbId)) + { + item.SetProviderId(MetadataProvider.Tmdb, tmdbId); + } } - // TVDB: - // https://www.thetvdb.com/?tab=series&id=121361 if (item is Series) { - var tvdbRegex = Regex.Match(xml, "thetvdb\\.com\\/\\?tab=series\\&id=([0-9]+)", RegexOptions.Compiled); - if (tvdbRegex.Success) + if (ProviderIdParsers.TryParseTmdbSeriesId(xml, out var tmdbId)) { - item.SetProviderId(MetadataProvider.Tvdb, tvdbRegex.Groups[1].Value); + item.SetProviderId(MetadataProvider.Tmdb, tmdbId); + } + + if (ProviderIdParsers.TryParseTvdbId(xml, out var tvdbId)) + { + item.SetProviderId(MetadataProvider.Tvdb, tvdbId); } } } diff --git a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs index c09781b1ae..1dce378dca 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/SeriesNfoParser.cs @@ -35,9 +35,6 @@ namespace MediaBrowser.XbmcMetadata.Parsers /// protected override bool SupportsUrlAfterClosingXmlTag => true; - /// - protected override string TmdbRegex => "themoviedb\\.org\\/tv\\/([0-9]+)"; - /// protected override void FetchDataFromXmlNode(XmlReader reader, MetadataResult itemResult) { diff --git a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs new file mode 100644 index 0000000000..a493dda64f --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs @@ -0,0 +1,63 @@ +using MediaBrowser.Common.Providers; +using Xunit; + +namespace Jellyfin.Common.Tests.Providers +{ + public class ProviderIdParserTests + { + [Theory] + [InlineData("tt123456", false, null)] + [InlineData("tt1234567", true, "tt1234567")] + [InlineData("tt12345678", true, "tt12345678")] + [InlineData("https://www.imdb.com/title/tt123456", false, null)] + [InlineData("https://www.imdb.com/title/tt1234567", true, "tt1234567")] + [InlineData("https://www.imdb.com/title/tt12345678", true, "tt12345678")] + [InlineData(@"multiline\nhttps://www.imdb.com/title/tt1234567", true, "tt1234567")] + [InlineData(@"multiline\nhttps://www.imdb.com/title/tt12345678", true, "tt12345678")] + [InlineData("Jellyfin", false, null)] + [InlineData("tt1234567tt7654321", true, "tt1234567")] + [InlineData("tt12345678tt7654321", true, "tt12345678")] + public void Parse_Imdb(string text, bool shouldSucceed, string? imdbId) + { + var succeeded = ProviderIdParsers.TryParseImdbId(text, out string? parsedId); + Assert.Equal(shouldSucceed, succeeded); + Assert.Equal(imdbId, parsedId); + } + + [Theory] + [InlineData("https://www.themoviedb.org/movie/30287-fallo", true, "30287")] + [InlineData("themoviedb.org/movie/30287", true, "30287")] + [InlineData("https://www.themoviedb.org/movie/fallo-30287", false, null)] + [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] + public void Parse_TmdbMovie(string text, bool shouldSucceed, string? tmdbId) + { + var succeeded = ProviderIdParsers.TryParseTmdbMovieId(text, out string? parsedId); + Assert.Equal(shouldSucceed, succeeded); + Assert.Equal(tmdbId, parsedId); + } + + [Theory] + [InlineData("https://www.themoviedb.org/tv/1668-friends", true, "1668")] + [InlineData("themoviedb.org/tv/1668", true, "1668")] + [InlineData("https://www.themoviedb.org/tv/friends-1668", false, null)] + [InlineData("https://www.themoviedb.org/movie/30287-fallo", false, null)] + public void Parse_TmdbSeries(string text, bool shouldSucceed, string? tmdbId) + { + var succeeded = ProviderIdParsers.TryParseTmdbSeriesId(text, out string? parsedId); + Assert.Equal(shouldSucceed, succeeded); + Assert.Equal(tmdbId, parsedId); + } + + [Theory] + [InlineData("https://www.thetvdb.com/?tab=series&id=121361", true, "121361")] + [InlineData("thetvdb.com/?tab=series&id=121361", true, "121361")] + [InlineData("thetvdb.com/?tab=series&id=Jellyfin121361", false, null)] + [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] + public void Parse_Tvdb(string text, bool shouldSucceed, string? tvdbId) + { + var succeeded = ProviderIdParsers.TryParseTvdbId(text, out string? parsedId); + Assert.Equal(shouldSucceed, succeeded); + Assert.Equal(tvdbId, parsedId); + } + } +} From 37aa3e8735bf0089333cd19d6a0d03ed496e9f17 Mon Sep 17 00:00:00 2001 From: Vitorvlv Date: Wed, 17 Mar 2021 01:13:53 +0000 Subject: [PATCH 1304/1930] Translated using Weblate (Portuguese (Brazil)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pt_BR/ --- Emby.Server.Implementations/Localization/Core/pt-BR.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pt-BR.json b/Emby.Server.Implementations/Localization/Core/pt-BR.json index 5ec8f1e88a..323dcced07 100644 --- a/Emby.Server.Implementations/Localization/Core/pt-BR.json +++ b/Emby.Server.Implementations/Localization/Core/pt-BR.json @@ -16,7 +16,7 @@ "Folders": "Pastas", "Genres": "Gêneros", "HeaderAlbumArtists": "Artistas do Álbum", - "HeaderContinueWatching": "Continuar Assistindo", + "HeaderContinueWatching": "Continuar assistindo", "HeaderFavoriteAlbums": "Álbuns Favoritos", "HeaderFavoriteArtists": "Artistas favoritos", "HeaderFavoriteEpisodes": "Episódios favoritos", From 151156f2271104277a575054aea9e5b0f92d6591 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 17 Mar 2021 10:29:45 +0100 Subject: [PATCH 1305/1930] Clean the entity name for non-words before searching --- .../Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs | 11 +++++++++-- .../Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 3 ++- .../Plugins/Tmdb/TV/TmdbSeriesProvider.cs | 3 ++- MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs | 14 ++++++++++++++ 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs index fcd8e614c1..ca1af6c499 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/BoxSets/TmdbBoxSetProvider.cs @@ -9,6 +9,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; @@ -19,11 +20,13 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets { private readonly IHttpClientFactory _httpClientFactory; private readonly TmdbClientManager _tmdbClientManager; + private readonly ILibraryManager _libraryManager; - public TmdbBoxSetProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager) + public TmdbBoxSetProvider(IHttpClientFactory httpClientFactory, TmdbClientManager tmdbClientManager, ILibraryManager libraryManager) { _httpClientFactory = httpClientFactory; _tmdbClientManager = tmdbClientManager; + _libraryManager = libraryManager; } public string Name => TmdbUtils.ProviderName; @@ -83,7 +86,11 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets // We don't already have an Id, need to fetch it if (tmdbId <= 0) { - var searchResults = await _tmdbClientManager.SearchCollectionAsync(id.Name, language, cancellationToken).ConfigureAwait(false); + // ParseName is required here. + // Caller provides the filename with extension stripped and NOT the parsed filename + var parsedName = _libraryManager.ParseName(id.Name); + var cleanedName = TmdbUtils.CleanName(parsedName.Name); + var searchResults = await _tmdbClientManager.SearchCollectionAsync(cleanedName, language, cancellationToken).ConfigureAwait(false); if (searchResults != null && searchResults.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 2cd1ee717a..4963777bc4 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -140,7 +140,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies // ParseName is required here. // Caller provides the filename with extension stripped and NOT the parsed filename var parsedName = _libraryManager.ParseName(info.Name); - var searchResults = await _tmdbClientManager.SearchMovieAsync(parsedName.Name, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); + var cleanedName = TmdbUtils.CleanName(parsedName.Name); + var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false); if (searchResults.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index 74c2acf473..496e1ae256 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -189,7 +189,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV // ParseName is required here. // Caller provides the filename with extension stripped and NOT the parsed filename var parsedName = _libraryManager.ParseName(info.Name); - var searchResults = await _tmdbClientManager.SearchSeriesAsync(parsedName.Name, info.MetadataLanguage, info.Year ?? parsedName.Year ?? 0, cancellationToken).ConfigureAwait(false); + var cleanedName = TmdbUtils.CleanName(parsedName.Name); + var searchResults = await _tmdbClientManager.SearchSeriesAsync(cleanedName, info.MetadataLanguage, info.Year ?? parsedName.Year ?? 0, cancellationToken).ConfigureAwait(false); if (searchResults.Count > 0) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 0e8a5baab6..15a44c7ed3 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Text.RegularExpressions; using MediaBrowser.Model.Entities; using TMDbLib.Objects.General; @@ -12,6 +13,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// public static class TmdbUtils { + private static readonly Regex _nonWords = new (@"[\W_]+", RegexOptions.Compiled); + /// /// URL of the TMDB instance to use. /// @@ -42,6 +45,17 @@ namespace MediaBrowser.Providers.Plugins.Tmdb PersonType.Producer }; + /// + /// Cleans the name according to TMDb requirements. + /// + /// The name of the entity. + /// The cleaned name. + public static string CleanName(string name) + { + // TMDb expects a space separated list of words make sure that is the case + return _nonWords.Replace(name, " "); + } + /// /// Maps the TMDB provided roles for crew members to Jellyfin roles. /// From 12b8e29aefad3ad202769cdab9c6afc17c5687d9 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Wed, 17 Mar 2021 17:42:45 -0400 Subject: [PATCH 1306/1930] Fix duplicate permissions --- Jellyfin.Data/Entities/User.cs | 33 ++++++++++--------- .../Users/UserManager.cs | 3 ++ 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 9aa8091640..74331726cc 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -73,9 +73,6 @@ namespace Jellyfin.Data.Entities PlayDefaultAudioTrack = true; SubtitleMode = SubtitlePlaybackMode.Default; SyncPlayAccess = SyncPlayUserAccessType.CreateAndJoinGroups; - - AddDefaultPermissions(); - AddDefaultPreferences(); } /// @@ -483,18 +480,11 @@ namespace Jellyfin.Data.Entities return Array.IndexOf(GetPreferenceValues(PreferenceKind.GroupedFolders), id) != -1; } - private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date) - { - var localTime = date.ToLocalTime(); - var hour = localTime.TimeOfDay.TotalHours; - - return DayOfWeekHelper.GetDaysOfWeek(schedule.DayOfWeek).Contains(localTime.DayOfWeek) - && hour >= schedule.StartHour - && hour <= schedule.EndHour; - } - + /// + /// Initializes the default permissions for a user. Should only be called on user creation. + /// // TODO: make these user configurable? - private void AddDefaultPermissions() + public void AddDefaultPermissions() { Permissions.Add(new Permission(PermissionKind.IsAdministrator, false)); Permissions.Add(new Permission(PermissionKind.IsDisabled, false)); @@ -519,12 +509,25 @@ namespace Jellyfin.Data.Entities Permissions.Add(new Permission(PermissionKind.EnableRemoteControlOfOtherUsers, false)); } - private void AddDefaultPreferences() + /// + /// Initializes the default preferences. Should only be called on user creation. + /// + public void AddDefaultPreferences() { foreach (var val in Enum.GetValues(typeof(PreferenceKind)).Cast()) { Preferences.Add(new Preference(val, string.Empty)); } } + + private static bool IsParentalScheduleAllowed(AccessSchedule schedule, DateTime date) + { + var localTime = date.ToLocalTime(); + var hour = localTime.TimeOfDay.TotalHours; + + return DayOfWeekHelper.GetDaysOfWeek(schedule.DayOfWeek).Contains(localTime.DayOfWeek) + && hour >= schedule.StartHour + && hour <= schedule.EndHour; + } } } diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index b400a0dd1b..50d7612f27 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -190,6 +190,9 @@ namespace Jellyfin.Server.Implementations.Users InternalId = max + 1 }; + user.AddDefaultPermissions(); + user.AddDefaultPreferences(); + _users.Add(user.Id, user); return user; From 85da0b50e2e9686a0d660e2c2138709937c2fee2 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Wed, 17 Mar 2021 21:24:14 -0400 Subject: [PATCH 1307/1930] Fix user mocking --- .../Auth/CustomAuthenticationHandlerTests.cs | 2 ++ tests/Jellyfin.Api.Tests/TestHelpers.cs | 3 +++ 2 files changed, 5 insertions(+) diff --git a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs index ee20cc5738..de03aa5f5b 100644 --- a/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/CustomAuthenticationHandlerTests.cs @@ -128,6 +128,8 @@ namespace Jellyfin.Api.Tests.Auth { var authorizationInfo = _fixture.Create(); authorizationInfo.User = _fixture.Create(); + authorizationInfo.User.AddDefaultPermissions(); + authorizationInfo.User.AddDefaultPreferences(); authorizationInfo.User.SetPermission(PermissionKind.IsAdministrator, isAdmin); authorizationInfo.IsApiKey = false; diff --git a/tests/Jellyfin.Api.Tests/TestHelpers.cs b/tests/Jellyfin.Api.Tests/TestHelpers.cs index c1549561db..f9bca41465 100644 --- a/tests/Jellyfin.Api.Tests/TestHelpers.cs +++ b/tests/Jellyfin.Api.Tests/TestHelpers.cs @@ -29,6 +29,9 @@ namespace Jellyfin.Api.Tests typeof(DefaultAuthenticationProvider).FullName!, typeof(DefaultPasswordResetProvider).FullName!); + user.AddDefaultPermissions(); + user.AddDefaultPreferences(); + // Set administrator flag. user.SetPermission(PermissionKind.IsAdministrator, role.Equals(UserRoles.Administrator, StringComparison.OrdinalIgnoreCase)); From 840eeff2afb0faca7e65057276a1a3c7787102bf Mon Sep 17 00:00:00 2001 From: David Date: Thu, 18 Mar 2021 11:25:58 +0100 Subject: [PATCH 1308/1930] Apply suggestions from code review --- .../Providers/ProviderIdParsers.cs | 78 +++++++++++-------- .../Providers/ProviderIdParserTests.cs | 1 + 2 files changed, 45 insertions(+), 34 deletions(-) diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index 56e0112ddc..bfe61a3f8f 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -10,6 +10,9 @@ namespace MediaBrowser.Common.Providers /// public static class ProviderIdParsers { + private const int ImdbMinNumbers = 7; + private const int ImdbMaxNumbers = 8; + /// /// Parses an IMDb id from a string. /// @@ -21,7 +24,8 @@ namespace MediaBrowser.Common.Providers var span = text.AsSpan(); var tt = "tt".AsSpan(); - while (true) + // imdb id is at least 9 chars (tt + 7 numbers) + while (span.Length >= 2 + ImdbMinNumbers) { var ttPos = span.IndexOf(tt); if (ttPos == -1) @@ -31,27 +35,28 @@ namespace MediaBrowser.Common.Providers } span = span.Slice(ttPos + tt.Length); - - int i = 0; - // IMDb id has a maximum of 8 digits - int max = span.Length > 8 ? 8 : span.Length; - for (; i < max; i++) + var i = 0; + for (; i < Math.Min(span.Length, ImdbMaxNumbers); i++) { var c = span[i]; - - if (c < '0' || c > '9') + if (!IsDigit(c)) { break; } } - // IMDb id has a minimum of 7 digits - if (i >= 7) + // skip if more than 8 digits + if (i <= ImdbMaxNumbers && i >= ImdbMinNumbers) { imdbId = string.Concat(tt, span.Slice(0, i)); return true; } + + span = span.Slice(i); } + + imdbId = default; + return false; } /// @@ -86,34 +91,39 @@ namespace MediaBrowser.Common.Providers var span = text.AsSpan(); var searchSpan = searchString.AsSpan(); - while (true) + var searchPos = span.IndexOf(searchSpan); + if (searchPos == -1) { - var searchPos = span.IndexOf(searchSpan); - if (searchPos == -1) + providerId = default; + return false; + } + + span = span.Slice(searchPos + searchSpan.Length); + + int i = 0; + for (; i < span.Length; i++) + { + var c = span[i]; + + if (!IsDigit(c)) { - providerId = default; - return false; - } - - span = span.Slice(searchPos + searchSpan.Length); - - int i = 0; - for (; i < span.Length; i++) - { - var c = span[i]; - - if (c < '0' || c > '9') - { - break; - } - } - - if (i >= 1) - { - providerId = span.Slice(0, i).ToString(); - return true; + break; } } + + if (i >= 1) + { + providerId = span.Slice(0, i).ToString(); + return true; + } + + providerId = default; + return false; + } + + private static bool IsDigit(char c) + { + return c >= '0' && c <= '9'; } } } diff --git a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs index a493dda64f..cfe1ea86bf 100644 --- a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs +++ b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs @@ -17,6 +17,7 @@ namespace Jellyfin.Common.Tests.Providers [InlineData("Jellyfin", false, null)] [InlineData("tt1234567tt7654321", true, "tt1234567")] [InlineData("tt12345678tt7654321", true, "tt12345678")] + [InlineData("tt123456789", true, "tt12345678")] public void Parse_Imdb(string text, bool shouldSucceed, string? imdbId) { var succeeded = ProviderIdParsers.TryParseImdbId(text, out string? parsedId); From 59641e5c766d8d4fc756ef327642ac04be24968a Mon Sep 17 00:00:00 2001 From: David Date: Thu, 18 Mar 2021 20:52:56 +0100 Subject: [PATCH 1309/1930] Use ReadOnlySpan and char.IsDigit --- .../Providers/ProviderIdParsers.cs | 47 ++++++++----------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index bfe61a3f8f..7986675054 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -19,27 +19,26 @@ namespace MediaBrowser.Common.Providers /// The text to parse. /// The parsed IMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseImdbId(string text, [NotNullWhen(true)] out string? imdbId) + public static bool TryParseImdbId(ReadOnlySpan text, [NotNullWhen(true)] out string? imdbId) { - var span = text.AsSpan(); var tt = "tt".AsSpan(); // imdb id is at least 9 chars (tt + 7 numbers) - while (span.Length >= 2 + ImdbMinNumbers) + while (text.Length >= 2 + ImdbMinNumbers) { - var ttPos = span.IndexOf(tt); + var ttPos = text.IndexOf(tt); if (ttPos == -1) { imdbId = default; return false; } - span = span.Slice(ttPos + tt.Length); + text = text.Slice(ttPos + tt.Length); var i = 0; - for (; i < Math.Min(span.Length, ImdbMaxNumbers); i++) + for (; i < Math.Min(text.Length, ImdbMaxNumbers); i++) { - var c = span[i]; - if (!IsDigit(c)) + var c = text[i]; + if (!char.IsDigit(c)) { break; } @@ -48,11 +47,11 @@ namespace MediaBrowser.Common.Providers // skip if more than 8 digits if (i <= ImdbMaxNumbers && i >= ImdbMinNumbers) { - imdbId = string.Concat(tt, span.Slice(0, i)); + imdbId = string.Concat(tt, text.Slice(0, i)); return true; } - span = span.Slice(i); + text = text.Slice(i); } imdbId = default; @@ -65,7 +64,7 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTmdbMovieId(string text, [NotNullWhen(true)] out string? tmdbId) + public static bool TryParseTmdbMovieId(ReadOnlySpan text, [NotNullWhen(true)] out string? tmdbId) => TryParseProviderId(text, "themoviedb.org/movie/", out tmdbId); /// @@ -74,7 +73,7 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTmdbSeriesId(string text, [NotNullWhen(true)] out string? tmdbId) + public static bool TryParseTmdbSeriesId(ReadOnlySpan text, [NotNullWhen(true)] out string? tmdbId) => TryParseProviderId(text, "themoviedb.org/tv/", out tmdbId); /// @@ -83,29 +82,26 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TVDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTvdbId(string text, [NotNullWhen(true)] out string? tvdbId) + public static bool TryParseTvdbId(ReadOnlySpan text, [NotNullWhen(true)] out string? tvdbId) => TryParseProviderId(text, "thetvdb.com/?tab=series&id=", out tvdbId); - private static bool TryParseProviderId(string text, string searchString, [NotNullWhen(true)] out string? providerId) + private static bool TryParseProviderId(ReadOnlySpan text, ReadOnlySpan searchString, [NotNullWhen(true)] out string? providerId) { - var span = text.AsSpan(); - var searchSpan = searchString.AsSpan(); - - var searchPos = span.IndexOf(searchSpan); + var searchPos = text.IndexOf(searchString); if (searchPos == -1) { providerId = default; return false; } - span = span.Slice(searchPos + searchSpan.Length); + text = text.Slice(searchPos + searchString.Length); int i = 0; - for (; i < span.Length; i++) + for (; i < text.Length; i++) { - var c = span[i]; + var c = text[i]; - if (!IsDigit(c)) + if (!char.IsDigit(c)) { break; } @@ -113,17 +109,12 @@ namespace MediaBrowser.Common.Providers if (i >= 1) { - providerId = span.Slice(0, i).ToString(); + providerId = text.Slice(0, i).ToString(); return true; } providerId = default; return false; } - - private static bool IsDigit(char c) - { - return c >= '0' && c <= '9'; - } } } From 9857c21717380261e11ec948c3520a673ffd83ae Mon Sep 17 00:00:00 2001 From: andrewthemeow Date: Fri, 19 Mar 2021 06:29:39 +0000 Subject: [PATCH 1310/1930] Translated using Weblate (Lithuanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/lt/ --- Emby.Server.Implementations/Localization/Core/lt-LT.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/lt-LT.json b/Emby.Server.Implementations/Localization/Core/lt-LT.json index d4cb592efc..9920ef4d51 100644 --- a/Emby.Server.Implementations/Localization/Core/lt-LT.json +++ b/Emby.Server.Implementations/Localization/Core/lt-LT.json @@ -113,5 +113,9 @@ "TasksChannelsCategory": "Internetiniai Kanalai", "TasksApplicationCategory": "Programa", "TasksLibraryCategory": "Mediateka", - "TasksMaintenanceCategory": "Priežiūra" + "TasksMaintenanceCategory": "Priežiūra", + "TaskCleanActivityLog": "Švarus veiklos žurnalas", + "Undefined": "Neapibrėžtas", + "Forced": "Priverstas", + "Default": "Numatytas" } From 7685569480409f2703fc6ead32d093a08d783312 Mon Sep 17 00:00:00 2001 From: David Date: Fri, 19 Mar 2021 12:34:21 +0100 Subject: [PATCH 1311/1930] Rollback char.IsDigit --- MediaBrowser.Common/Providers/ProviderIdParsers.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index 7986675054..7744124eaa 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Common.Providers for (; i < Math.Min(text.Length, ImdbMaxNumbers); i++) { var c = text[i]; - if (!char.IsDigit(c)) + if (!IsDigit(c)) { break; } @@ -101,7 +101,7 @@ namespace MediaBrowser.Common.Providers { var c = text[i]; - if (!char.IsDigit(c)) + if (!IsDigit(c)) { break; } @@ -116,5 +116,10 @@ namespace MediaBrowser.Common.Providers providerId = default; return false; } + + private static bool IsDigit(char c) + { + return c >= '0' && c <= '9'; + } } } From f61d18612b2e6c6e9a5dd4510331ac8d89a337d5 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Sat, 20 Mar 2021 00:38:58 +0100 Subject: [PATCH 1312/1930] Fix directory traversal in the HlsSegmentController in a fairly rudimentary but working way. GHSL-2021-050: Issue 1,2,3 Arbitrary file read and directory traversal. The segment id's can probably just be verified to be an actual ID or to not contain any forward or backward slashes --- .../Controllers/HlsSegmentController.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index d0ed45acb4..5a8542048a 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -62,6 +62,13 @@ namespace Jellyfin.Api.Controllers // TODO: Deprecate with new iOS app var file = segmentId + Path.GetExtension(Request.Path); file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file); + var transcodePath = _serverConfigurationManager.GetTranscodePath(); + file = Path.GetFullPath(Path.Combine(transcodePath, file)); + var fileDir = Path.GetDirectoryName(file); + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath)) + { + return BadRequest("Invalid segment."); + } return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file)!, false, HttpContext); } @@ -82,6 +89,13 @@ namespace Jellyfin.Api.Controllers { var file = playlistId + Path.GetExtension(Request.Path); file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file); + var transcodePath = _serverConfigurationManager.GetTranscodePath(); + file = Path.GetFullPath(Path.Combine(transcodePath, file)); + var fileDir = Path.GetDirectoryName(file); + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath) || Path.GetExtension(file) != ".m3u8") + { + return BadRequest("Invalid segment."); + } return GetFileResult(file, file); } @@ -131,6 +145,12 @@ namespace Jellyfin.Api.Controllers var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath(); file = Path.Combine(transcodeFolderPath, file); + file = Path.GetFullPath(Path.Combine(transcodeFolderPath, file)); + var fileDir = Path.GetDirectoryName(file); + if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath)) + { + return BadRequest("Invalid segment."); + } var normalizedPlaylistId = playlistId; From 239a7156cc9c2c383aca1e7265ae4679666d5c85 Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Sat, 20 Mar 2021 00:46:59 +0100 Subject: [PATCH 1313/1930] Fix arbitrary image file reads in ImageByNameController GHSL-2021-050: Issue 4 Arbitrary image file read and directory traversal. --- .../Controllers/ImageByNameController.cs | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageByNameController.cs b/Jellyfin.Api/Controllers/ImageByNameController.cs index 198dbc51fc..e1b8080984 100644 --- a/Jellyfin.Api/Controllers/ImageByNameController.cs +++ b/Jellyfin.Api/Controllers/ImageByNameController.cs @@ -74,7 +74,7 @@ namespace Jellyfin.Api.Controllers : type; var path = BaseItem.SupportedImageExtensions - .Select(i => Path.Combine(_applicationPaths.GeneralPath, name, filename + i)) + .Select(i => Path.GetFullPath(Path.Combine(_applicationPaths.GeneralPath, name, filename + i))) .FirstOrDefault(System.IO.File.Exists); if (path == null) @@ -82,6 +82,11 @@ namespace Jellyfin.Api.Controllers return NotFound(); } + if (!path.StartsWith(_applicationPaths.GeneralPath)) + { + return BadRequest("Invalid image path."); + } + var contentType = MimeTypes.GetMimeType(path); return File(System.IO.File.OpenRead(path), contentType); } @@ -163,7 +168,8 @@ namespace Jellyfin.Api.Controllers /// A containing the image contents on success, or a if the image could not be found. private ActionResult GetImageFile(string basePath, string theme, string? name) { - var themeFolder = Path.Combine(basePath, theme); + var themeFolder = Path.GetFullPath(Path.Combine(basePath, theme)); + if (Directory.Exists(themeFolder)) { var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(themeFolder, name + i)) @@ -171,12 +177,18 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path)) { + if (!path.StartsWith(basePath)) + { + return BadRequest("Invalid image path."); + } + var contentType = MimeTypes.GetMimeType(path); + return PhysicalFile(path, contentType); } } - var allFolder = Path.Combine(basePath, "all"); + var allFolder = Path.GetFullPath(Path.Combine(basePath, "all")); if (Directory.Exists(allFolder)) { var path = BaseItem.SupportedImageExtensions.Select(i => Path.Combine(allFolder, name + i)) @@ -184,6 +196,11 @@ namespace Jellyfin.Api.Controllers if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path)) { + if (!path.StartsWith(basePath)) + { + return BadRequest("Invalid image path."); + } + var contentType = MimeTypes.GetMimeType(path); return PhysicalFile(path, contentType); } From 470305f75edc037653b68dd0614f73009219bdbd Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Sat, 20 Mar 2021 01:07:09 +0100 Subject: [PATCH 1314/1930] Authenticated arbitrary file overwrite in SubtitleController -> SubtitleManager GHSL-2021-050: Issue 5 Arbitrary file overwrite. --- .../Subtitles/SubtitleManager.cs | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index d4d79d27b5..1f3d9acff2 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -205,12 +205,30 @@ namespace MediaBrowser.Providers.Subtitles if (saveInMediaFolder) { - savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName)); + var mediaFolderPath = Path.GetFullPath(Path.Combine(video.ContainingFolderPath, saveFileName)); + // TODO: Add some error handling to the API user: return BadRequest("Could not save subtitle, bad path."); + if (mediaFolderPath.StartsWith(video.ContainingFolderPath)) + { + savePaths.Add(mediaFolderPath); + } } - savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); + var internalPath = Path.GetFullPath(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); - await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); + // TODO: Add some error to the user: return BadRequest("Could not save subtitle, bad path."); + if (internalPath.StartsWith(video.GetInternalMetadataPath())) + { + savePaths.Add(internalPath); + } + + if (savePaths.Count > 0) + { + await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false); + } + else + { + _logger.LogError("An uploaded subtitle could not be saved because the resulting paths were invalid."); + } } } From 1f3aa3fe6f72f9b745dac7de5b6f8b877590017c Mon Sep 17 00:00:00 2001 From: Erwin de Haan Date: Sat, 20 Mar 2021 01:28:14 +0100 Subject: [PATCH 1315/1930] Apply review suggestions --- Jellyfin.Api/Controllers/HlsSegmentController.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/HlsSegmentController.cs b/Jellyfin.Api/Controllers/HlsSegmentController.cs index 5a8542048a..473bdc523c 100644 --- a/Jellyfin.Api/Controllers/HlsSegmentController.cs +++ b/Jellyfin.Api/Controllers/HlsSegmentController.cs @@ -61,7 +61,6 @@ namespace Jellyfin.Api.Controllers { // TODO: Deprecate with new iOS app var file = segmentId + Path.GetExtension(Request.Path); - file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file); var transcodePath = _serverConfigurationManager.GetTranscodePath(); file = Path.GetFullPath(Path.Combine(transcodePath, file)); var fileDir = Path.GetDirectoryName(file); @@ -88,7 +87,6 @@ namespace Jellyfin.Api.Controllers public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId) { var file = playlistId + Path.GetExtension(Request.Path); - file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file); var transcodePath = _serverConfigurationManager.GetTranscodePath(); file = Path.GetFullPath(Path.Combine(transcodePath, file)); var fileDir = Path.GetDirectoryName(file); @@ -144,7 +142,6 @@ namespace Jellyfin.Api.Controllers var file = segmentId + Path.GetExtension(Request.Path); var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath(); - file = Path.Combine(transcodeFolderPath, file); file = Path.GetFullPath(Path.Combine(transcodeFolderPath, file)); var fileDir = Path.GetDirectoryName(file); if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath)) From 32853ca2441d4b730258e6911faa56eba608dc1d Mon Sep 17 00:00:00 2001 From: LIAUD Date: Sat, 20 Mar 2021 20:15:19 +0100 Subject: [PATCH 1316/1930] Add 'group-title' channel parsing --- Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs | 5 +++++ MediaBrowser.Controller/LiveTv/ChannelInfo.cs | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index c4f173c7ac..2af635492e 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -133,6 +133,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts channel.ImageUrl = value; } + if (attributes.TryGetValue("group-title", out string groupTitle)) + { + channel.ChannelGroup = groupTitle; + } + channel.Name = GetChannelName(extInf, attributes); channel.Number = GetChannelNumber(extInf, attributes, mediaUrl); diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs index 44bd38b54f..0f3f878475 100644 --- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs @@ -45,6 +45,12 @@ namespace MediaBrowser.Controller.LiveTv /// The type of the channel. public ChannelType ChannelType { get; set; } + /// + /// Gets or sets the group of the channel + /// + /// The group of the channel + public string ChannelGroup { get; set; } + /// /// Supply the image path if it can be accessed directly from the file system. /// From 72db3df605b7061fef28c99e42b7c11a06e8d995 Mon Sep 17 00:00:00 2001 From: LIAUD Date: Sat, 20 Mar 2021 20:31:38 +0100 Subject: [PATCH 1317/1930] Changed CONTRIBUTORS.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 954315f0eb..9b1ac0673a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -17,6 +17,7 @@ - [bugfixin](https://github.com/bugfixin) - [chaosinnovator](https://github.com/chaosinnovator) - [ckcr4lyf](https://github.com/ckcr4lyf) + - [cocool97](https://github.com/cocool97) - [ConfusedPolarBear](https://github.com/ConfusedPolarBear) - [crankdoofus](https://github.com/crankdoofus) - [crobibero](https://github.com/crobibero) From 849ced470adf3ae122713e870e476b835c57d5ad Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 21 Mar 2021 03:26:51 +0100 Subject: [PATCH 1318/1930] Add StartupControllerTests --- .../Controllers/StartupControllerTests.cs | 61 +++++++++++++++++++ .../Jellyfin.Server.Integration.Tests.csproj | 1 + 2 files changed, 62 insertions(+) create mode 100644 tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs new file mode 100644 index 0000000000..cf4b9dd712 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs @@ -0,0 +1,61 @@ +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Mime; +using System.Text.Json; +using System.Threading.Tasks; +using Jellyfin.Api.Models.StartupDtos; +using MediaBrowser.Common.Json; +using Xunit; +using Xunit.Priority; + +namespace Jellyfin.Server.Integration.Tests.Controllers +{ + public sealed class StartupControllerTests : IClassFixture + { + private readonly JellyfinApplicationFactory _factory; + private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options; + + public StartupControllerTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + [Priority(0)] + public async Task GetStartupConfiguration_EditConfig_Success() + { + var client = _factory.CreateClient(); + + using var res0 = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, res0.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, res0.Content.Headers.ContentType?.MediaType); + + var content0 = await res0.Content.ReadAsStreamAsync().ConfigureAwait(false); + _ = await JsonSerializer.DeserializeAsync(content0, _jsonOpions).ConfigureAwait(false); + + var newConfig = new StartupConfigurationDto() + { + UICulture = "NewCulture", + MetadataCountryCode = "be", + PreferredMetadataLanguage = "nl" + }; + + var req1 = JsonSerializer.SerializeToUtf8Bytes(newConfig, _jsonOpions); + using var reqContent1 = new ByteArrayContent(req1); + reqContent1.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + var res1 = await client.PostAsync("/Startup/Configuration", reqContent1).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, res1.StatusCode); + + var res2 = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, res2.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, res2.Content.Headers.ContentType?.MediaType); + + var content2 = await res2.Content.ReadAsStreamAsync().ConfigureAwait(false); + var config2 = await JsonSerializer.DeserializeAsync(content2, _jsonOpions).ConfigureAwait(false); + Assert.Equal(newConfig.UICulture, config2!.UICulture); + Assert.Equal(newConfig.MetadataCountryCode, config2.MetadataCountryCode); + Assert.Equal(newConfig.PreferredMetadataLanguage, config2.PreferredMetadataLanguage); + } + } +} diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index b0a38736ae..34cef90050 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -17,6 +17,7 @@ + From c5079ebed5187c40e19284772c710c41c4252cc9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 21 Mar 2021 03:59:31 +0100 Subject: [PATCH 1319/1930] Add tests for GetFirstUser, UpdateStartupUser and CompleteWizard --- .../Controllers/StartupControllerTests.cs | 57 ++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs index cf4b9dd712..bb38db1be4 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs @@ -1,3 +1,4 @@ +using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; @@ -11,6 +12,7 @@ using Xunit.Priority; namespace Jellyfin.Server.Integration.Tests.Controllers { + [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] public sealed class StartupControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; @@ -23,7 +25,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers [Fact] [Priority(0)] - public async Task GetStartupConfiguration_EditConfig_Success() + public async Task Configuration_EditConfig_Success() { var client = _factory.CreateClient(); @@ -57,5 +59,58 @@ namespace Jellyfin.Server.Integration.Tests.Controllers Assert.Equal(newConfig.MetadataCountryCode, config2.MetadataCountryCode); Assert.Equal(newConfig.PreferredMetadataLanguage, config2.PreferredMetadataLanguage); } + + [Fact] + [Priority(0)] + public async Task User_EditUser_Success() + { + var client = _factory.CreateClient(); + + using var res0 = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, res0.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, res0.Content.Headers.ContentType?.MediaType); + + var content0 = await res0.Content.ReadAsStreamAsync().ConfigureAwait(false); + var user = await JsonSerializer.DeserializeAsync(content0, _jsonOpions).ConfigureAwait(false); + + user!.Name = "NewName"; + user.Password = "NewPassword"; + + var req1 = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOpions); + using var reqContent1 = new ByteArrayContent(req1); + reqContent1.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + var res1 = await client.PostAsync("/Startup/User", reqContent1).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, res1.StatusCode); + + var res2 = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, res2.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, res2.Content.Headers.ContentType?.MediaType); + + var content2 = await res2.Content.ReadAsStreamAsync().ConfigureAwait(false); + var user2 = await JsonSerializer.DeserializeAsync(content2, _jsonOpions).ConfigureAwait(false); + Assert.Equal(user.Name, user2!.Name); + Assert.NotEmpty(user2.Password); + Assert.NotEqual(user.Password, user2.Password); + } + + [Fact] + [Priority(1)] + public async Task CompleteWizard_Success() + { + var client = _factory.CreateClient(); + + var res = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty())).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, res.StatusCode); + } + + [Fact] + [Priority(2)] + public async Task GetFirstUser_CompleteWizard_Unauthorized() + { + var client = _factory.CreateClient(); + + using var res0 = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.Unauthorized, res0.StatusCode); + } } } From fcb070abf702c587fc98183253d56ec7f501eaa6 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Mon, 22 Mar 2021 18:36:04 +0800 Subject: [PATCH 1320/1930] disable auto rotation for some HWA methods --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index e5877a484a..b0cf47c7a3 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -541,6 +541,8 @@ namespace MediaBrowser.Controller.MediaEncoding .Append(encodingOptions.VaapiDevice) .Append(' '); } + + arg.Append("-autorotate 0"); } if (state.IsVideoRequest @@ -585,6 +587,8 @@ namespace MediaBrowser.Controller.MediaEncoding .Append("-init_hw_device qsv@va ") .Append("-hwaccel_output_format vaapi "); } + + arg.Append("-autorotate 0 "); } } @@ -592,7 +596,8 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecDecoder) { - arg.Append("-hwaccel_output_format cuda "); + arg.Append("-hwaccel_output_format cuda ") + .Append("-autorotate 0 "); } if (state.IsVideoRequest From a6bc191607675cd5676c6d1dceaf0ad37ac7e508 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Mon, 22 Mar 2021 19:25:41 +0800 Subject: [PATCH 1321/1930] Apply suggestions from code review Co-authored-by: Claus Vium --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index b0cf47c7a3..1df040a266 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -596,8 +596,7 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecDecoder) { - arg.Append("-hwaccel_output_format cuda ") - .Append("-autorotate 0 "); + arg.Append("-hwaccel_output_format cuda -autorotate 0 "); } if (state.IsVideoRequest From fab4bf184e27eba59566702d20ed352f75f0418b Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Mon, 22 Mar 2021 19:47:05 +0800 Subject: [PATCH 1322/1930] Apply suggestions from code review Co-authored-by: Claus Vium --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1df040a266..09080e7b2c 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -542,7 +542,7 @@ namespace MediaBrowser.Controller.MediaEncoding .Append(' '); } - arg.Append("-autorotate 0"); + arg.Append("-autorotate 0 "); } if (state.IsVideoRequest From 5253483ce4213a5f32fc15210ef61b2df9915185 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 22 Mar 2021 13:49:00 +0100 Subject: [PATCH 1323/1930] Improve naming --- .../Controllers/StartupControllerTests.cs | 107 +++++++++--------- 1 file changed, 55 insertions(+), 52 deletions(-) diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs index bb38db1be4..169a5a6c52 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/StartupControllerTests.cs @@ -16,7 +16,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers public sealed class StartupControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; - private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; public StartupControllerTests(JellyfinApplicationFactory factory) { @@ -24,93 +24,96 @@ namespace Jellyfin.Server.Integration.Tests.Controllers } [Fact] - [Priority(0)] + [Priority(-2)] public async Task Configuration_EditConfig_Success() { var client = _factory.CreateClient(); - using var res0 = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.OK, res0.StatusCode); - Assert.Equal(MediaTypeNames.Application.Json, res0.Content.Headers.ContentType?.MediaType); - - var content0 = await res0.Content.ReadAsStreamAsync().ConfigureAwait(false); - _ = await JsonSerializer.DeserializeAsync(content0, _jsonOpions).ConfigureAwait(false); - - var newConfig = new StartupConfigurationDto() + var config = new StartupConfigurationDto() { UICulture = "NewCulture", MetadataCountryCode = "be", PreferredMetadataLanguage = "nl" }; - var req1 = JsonSerializer.SerializeToUtf8Bytes(newConfig, _jsonOpions); - using var reqContent1 = new ByteArrayContent(req1); - reqContent1.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); - var res1 = await client.PostAsync("/Startup/Configuration", reqContent1).ConfigureAwait(false); - Assert.Equal(HttpStatusCode.NoContent, res1.StatusCode); + using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(config, _jsonOptions)); + postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + using var postResponse = await client.PostAsync("/Startup/Configuration", postContent).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, postResponse.StatusCode); - var res2 = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.OK, res2.StatusCode); - Assert.Equal(MediaTypeNames.Application.Json, res2.Content.Headers.ContentType?.MediaType); + using var getResponse = await client.GetAsync("/Startup/Configuration").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, getResponse.Content.Headers.ContentType?.MediaType); - var content2 = await res2.Content.ReadAsStreamAsync().ConfigureAwait(false); - var config2 = await JsonSerializer.DeserializeAsync(content2, _jsonOpions).ConfigureAwait(false); - Assert.Equal(newConfig.UICulture, config2!.UICulture); - Assert.Equal(newConfig.MetadataCountryCode, config2.MetadataCountryCode); - Assert.Equal(newConfig.PreferredMetadataLanguage, config2.PreferredMetadataLanguage); + using var responseStream = await getResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + var newConfig = await JsonSerializer.DeserializeAsync(responseStream, _jsonOptions).ConfigureAwait(false); + Assert.Equal(config.UICulture, newConfig!.UICulture); + Assert.Equal(config.MetadataCountryCode, newConfig.MetadataCountryCode); + Assert.Equal(config.PreferredMetadataLanguage, newConfig.PreferredMetadataLanguage); } [Fact] - [Priority(0)] + [Priority(-2)] + public async Task User_DefaultUser_NameWithoutPassword() + { + var client = _factory.CreateClient(); + + using var response = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); + + using var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var user = await JsonSerializer.DeserializeAsync(contentStream, _jsonOptions).ConfigureAwait(false); + Assert.NotEmpty(user!.Name); + Assert.Null(user.Password); + } + + [Fact] + [Priority(-1)] public async Task User_EditUser_Success() { var client = _factory.CreateClient(); - using var res0 = await client.GetAsync("/Startup/User").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.OK, res0.StatusCode); - Assert.Equal(MediaTypeNames.Application.Json, res0.Content.Headers.ContentType?.MediaType); + var user = new StartupUserDto() + { + Name = "NewName", + Password = "NewPassword" + }; - var content0 = await res0.Content.ReadAsStreamAsync().ConfigureAwait(false); - var user = await JsonSerializer.DeserializeAsync(content0, _jsonOpions).ConfigureAwait(false); + using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(user, _jsonOptions)); + postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + var postResponse = await client.PostAsync("/Startup/User", postContent).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, postResponse.StatusCode); - user!.Name = "NewName"; - user.Password = "NewPassword"; + var getResponse = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, getResponse.Content.Headers.ContentType?.MediaType); - var req1 = JsonSerializer.SerializeToUtf8Bytes(user, _jsonOpions); - using var reqContent1 = new ByteArrayContent(req1); - reqContent1.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); - var res1 = await client.PostAsync("/Startup/User", reqContent1).ConfigureAwait(false); - Assert.Equal(HttpStatusCode.NoContent, res1.StatusCode); - - var res2 = await client.GetAsync("/Startup/User").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.OK, res2.StatusCode); - Assert.Equal(MediaTypeNames.Application.Json, res2.Content.Headers.ContentType?.MediaType); - - var content2 = await res2.Content.ReadAsStreamAsync().ConfigureAwait(false); - var user2 = await JsonSerializer.DeserializeAsync(content2, _jsonOpions).ConfigureAwait(false); - Assert.Equal(user.Name, user2!.Name); - Assert.NotEmpty(user2.Password); - Assert.NotEqual(user.Password, user2.Password); + var contentStream = await getResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); + var newUser = await JsonSerializer.DeserializeAsync(contentStream, _jsonOptions).ConfigureAwait(false); + Assert.Equal(user.Name, newUser!.Name); + Assert.NotEmpty(newUser.Password); + Assert.NotEqual(user.Password, newUser.Password); } [Fact] - [Priority(1)] + [Priority(0)] public async Task CompleteWizard_Success() { var client = _factory.CreateClient(); - var res = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty())).ConfigureAwait(false); - Assert.Equal(HttpStatusCode.NoContent, res.StatusCode); + var response = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty())).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } [Fact] - [Priority(2)] + [Priority(1)] public async Task GetFirstUser_CompleteWizard_Unauthorized() { var client = _factory.CreateClient(); - using var res0 = await client.GetAsync("/Startup/User").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.Unauthorized, res0.StatusCode); + using var response = await client.GetAsync("/Startup/User").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } From 0853d1265c99a2e8614aa0c7a584dff541484e19 Mon Sep 17 00:00:00 2001 From: Nyanmisaka Date: Tue, 23 Mar 2021 00:59:57 +0800 Subject: [PATCH 1324/1930] Disable auto rotation for some HWA methods (#5586) Co-authored-by: Claus Vium --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index e5877a484a..09080e7b2c 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -541,6 +541,8 @@ namespace MediaBrowser.Controller.MediaEncoding .Append(encodingOptions.VaapiDevice) .Append(' '); } + + arg.Append("-autorotate 0 "); } if (state.IsVideoRequest @@ -585,6 +587,8 @@ namespace MediaBrowser.Controller.MediaEncoding .Append("-init_hw_device qsv@va ") .Append("-hwaccel_output_format vaapi "); } + + arg.Append("-autorotate 0 "); } } @@ -592,7 +596,7 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecDecoder) { - arg.Append("-hwaccel_output_format cuda "); + arg.Append("-hwaccel_output_format cuda -autorotate 0 "); } if (state.IsVideoRequest From 7fa525c83b7573e61124fa1c64a3b27569e66b6d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 22 Mar 2021 17:04:09 +0000 Subject: [PATCH 1325/1930] Added more tests --- Jellyfin.sln | 17 +++++++++++------ .../NetworkParseTests.cs | 11 +++++++---- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index 7b81f43462..9d5cd98e26 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -1,4 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30503.244 MinimumVisualStudioVersion = 10.0.40219.1 @@ -70,15 +71,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking", "Jell EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Dlna.Tests", "tests\Jellyfin.Dlna.Tests\Jellyfin.Dlna.Tests.csproj", "{B8AE4B9D-E8D3-4B03-A95E-7FD8CECECC50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.XbmcMetadata.Tests", "tests\Jellyfin.XbmcMetadata.Tests\Jellyfin.XbmcMetadata.Tests.csproj", "{30922383-D513-4F4D-B890-A940B57FA353}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Model.Tests", "tests\Jellyfin.Model.Tests\Jellyfin.Model.Tests.csproj", "{FC1BC0CE-E8D2-4AE9-A6AB-8A02143B335D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Networking.Tests", "tests\Jellyfin.Networking.Tests\Jellyfin.Networking.Tests.csproj", "{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{25E40B0B-7C89-4230-8911-CBBBCE83FC5B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Jellyfin.Server.Tests", "tests\Jellyfin.Server.Tests\Jellyfin.Server.Tests.csproj", "{3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -210,6 +211,10 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Debug|Any CPU.Build.0 = Debug|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.ActiveCfg = Release|Any CPU {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}.Release|Any CPU.Build.0 = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {25E40B0B-7C89-4230-8911-CBBBCE83FC5B}.Release|Any CPU.Build.0 = Release|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Debug|Any CPU.Build.0 = Debug|Any CPU {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 19f0faa8fe..de81ad0a6d 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -518,7 +518,9 @@ namespace Jellyfin.Networking.Tests [Theory] [InlineData("185.10.10.10,200.200.200.200", "79.2.3.4", true)] [InlineData("185.10.10.10", "185.10.10.10", false)] - public void HasRemoteAccess_GivenNonEmptyWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied) + [InlineData("", "100.100.100.100", false)] + + public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. @@ -534,9 +536,10 @@ namespace Jellyfin.Networking.Tests } [Theory] - [InlineData("185.10.10.10", "79.2.3.4", false)] // blacklist - [InlineData("185.10.10.10", "185.10.10.10", true)] // blacklist - public void HasRemoteAccess_GivenNonEmptyBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) + [InlineData("185.10.10.10", "79.2.3.4", false)] + [InlineData("185.10.10.10", "185.10.10.10", true)] + [InlineData("", "100.100.100.100", false)] + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. // If left blank, all remote addresses will be allowed. From 4bd345fbabd7832bcb91a920ec81dc14a7420218 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 22 Mar 2021 17:21:12 +0000 Subject: [PATCH 1326/1930] DLNA Exception catching --- Emby.Dlna/PlayTo/Device.cs | 41 +++++++++++++++---- Emby.Dlna/PlayTo/PlayToManager.cs | 5 +++ Emby.Dlna/PlayTo/SsdpHttpClient.cs | 15 +++++-- .../NetworkParseTests.cs | 4 +- 4 files changed, 51 insertions(+), 14 deletions(-) diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 7bf7047fbb..abd99bbc3c 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -219,7 +219,7 @@ namespace Emby.Dlna.PlayTo { var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetMute"); + var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetMute"); if (command == null) { return false; @@ -259,7 +259,7 @@ namespace Emby.Dlna.PlayTo { var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume"); + var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume"); if (command == null) { return; @@ -290,7 +290,7 @@ namespace Emby.Dlna.PlayTo { var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Seek"); + var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Seek"); if (command == null) { return; @@ -323,7 +323,7 @@ namespace Emby.Dlna.PlayTo _logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); - var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI"); + var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI"); if (command == null) { return; @@ -403,6 +403,10 @@ namespace Emby.Dlna.PlayTo public async Task SetPlay(CancellationToken cancellationToken) { var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false); + if (avCommands == null) + { + return; + } await SetPlay(avCommands, cancellationToken).ConfigureAwait(false); @@ -413,7 +417,7 @@ namespace Emby.Dlna.PlayTo { var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Stop"); + var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Stop"); if (command == null) { return; @@ -437,7 +441,7 @@ namespace Emby.Dlna.PlayTo { var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Pause"); + var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Pause"); if (command == null) { return; @@ -565,7 +569,7 @@ namespace Emby.Dlna.PlayTo var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume"); + var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume"); if (command == null) { return; @@ -615,7 +619,7 @@ namespace Emby.Dlna.PlayTo var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); - var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMute"); + var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetMute"); if (command == null) { return; @@ -702,6 +706,10 @@ namespace Emby.Dlna.PlayTo } var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); + if (rendererCommands == null) + { + return null; + } var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync( Properties.BaseUrl, @@ -770,6 +778,11 @@ namespace Emby.Dlna.PlayTo var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false); + if (rendererCommands == null) + { + return (false, null); + } + var result = await new SsdpHttpClient(_httpClientFactory).SendCommandAsync( Properties.BaseUrl, service, @@ -951,6 +964,10 @@ namespace Emby.Dlna.PlayTo var httpClient = new SsdpHttpClient(_httpClientFactory); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); + if (document == null) + { + return null; + } AvCommands = TransportCommands.Create(document); return AvCommands; @@ -979,6 +996,10 @@ namespace Emby.Dlna.PlayTo var httpClient = new SsdpHttpClient(_httpClientFactory); _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync"); var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false); + if (document == null) + { + return null; + } RendererCommands = TransportCommands.Create(document); return RendererCommands; @@ -1010,6 +1031,10 @@ namespace Emby.Dlna.PlayTo var ssdpHttpClient = new SsdpHttpClient(httpClientFactory); var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false); + if (document == null) + { + return null; + } var friendlyNames = new List(); diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index a6793a7081..8272e505a0 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -178,6 +178,11 @@ namespace Emby.Dlna.PlayTo if (controller == null) { var device = await Device.CreateuPnpDeviceAsync(uri, _httpClientFactory, _logger, cancellationToken).ConfigureAwait(false); + if (device == null) + { + _logger.LogError("Ignoring device as xml response is invalid."); + return; + } string deviceName = device.Properties.Name; diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index b7643fb279..e750f5bbc3 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -94,10 +94,17 @@ namespace Emby.Dlna.PlayTo options.Headers.TryAddWithoutValidation("FriendlyName.DLNA.ORG", FriendlyName); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - return await XDocument.LoadAsync( - stream, - LoadOptions.PreserveWhitespace, - cancellationToken).ConfigureAwait(false); + try + { + return await XDocument.LoadAsync( + stream, + LoadOptions.PreserveWhitespace, + cancellationToken).ConfigureAwait(false); + } + catch + { + return null; + } } private async Task PostSoapDataAsync( diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index c3469035eb..28b5a4691b 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -83,7 +83,7 @@ namespace Jellyfin.Networking.Tests /// /// Checks IP address formats. /// - /// + /// IP Address. [Theory] [InlineData("127.0.0.1")] [InlineData("127.0.0.1:123")] @@ -107,7 +107,7 @@ namespace Jellyfin.Networking.Tests /// /// Checks IP address formats. /// - /// + /// IP Address. [Theory] [InlineData("127.0.0.1")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] From 4637bbc723b2462ca01cb6cc5bd7e5e8b70b10c2 Mon Sep 17 00:00:00 2001 From: Kenneth SB Date: Mon, 22 Mar 2021 15:24:00 +0000 Subject: [PATCH 1327/1930] Translated using Weblate (Danish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/da/ --- Emby.Server.Implementations/Localization/Core/da.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/da.json b/Emby.Server.Implementations/Localization/Core/da.json index 4ee4eb989f..051d6d009f 100644 --- a/Emby.Server.Implementations/Localization/Core/da.json +++ b/Emby.Server.Implementations/Localization/Core/da.json @@ -1,5 +1,5 @@ { - "Albums": "Albums", + "Albums": "Albummer", "AppDeviceValues": "App: {0}, Enhed: {1}", "Application": "Applikation", "Artists": "Kunstnere", From 7dedeb6c795cb7764ec1cd1d2cd943f5c5506847 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 22 Mar 2021 20:53:55 +0100 Subject: [PATCH 1328/1930] change HLS endpoint defaults to false --- Emby.Dlna/PlayTo/PlayToController.cs | 2 +- Jellyfin.Api/Controllers/AudioController.cs | 24 +++---- .../Controllers/DynamicHlsController.cs | 72 +++++++++---------- .../Controllers/UniversalAudioController.cs | 8 +-- .../Controllers/VideoHlsController.cs | 12 ++-- Jellyfin.Api/Controllers/VideosController.cs | 12 ++-- MediaBrowser.Model/Dlna/StreamInfo.cs | 2 +- 7 files changed, 66 insertions(+), 66 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 5abc1bc134..6021da51db 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -945,7 +945,7 @@ namespace Emby.Dlna.PlayTo request.LiveStreamId = values.GetValueOrDefault("LiveStreamId"); // Be careful, IsDirectStream==true by default (Static != false or not in query). - // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. + // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? false. request.IsDirectStream = !string.Equals("false", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase); request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex"); diff --git a/Jellyfin.Api/Controllers/AudioController.cs b/Jellyfin.Api/Controllers/AudioController.cs index 8b1813b200..a6e70e72d3 100644 --- a/Jellyfin.Api/Controllers/AudioController.cs +++ b/Jellyfin.Api/Controllers/AudioController.cs @@ -144,7 +144,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -168,7 +168,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -177,13 +177,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -309,7 +309,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -333,7 +333,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -342,13 +342,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index f6c23c5aad..c4e75fe859 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -225,7 +225,7 @@ namespace Jellyfin.Api.Controllers var streamingRequest = new HlsVideoRequestDto { Id = itemId, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -249,7 +249,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -258,13 +258,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -392,7 +392,7 @@ namespace Jellyfin.Api.Controllers var streamingRequest = new HlsAudioRequestDto { Id = itemId, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -416,7 +416,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -425,13 +425,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -555,7 +555,7 @@ namespace Jellyfin.Api.Controllers var streamingRequest = new VideoRequestDto { Id = itemId, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -579,7 +579,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -588,13 +588,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -720,7 +720,7 @@ namespace Jellyfin.Api.Controllers var streamingRequest = new StreamingRequestDto { Id = itemId, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -744,7 +744,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -753,13 +753,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -890,7 +890,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -914,7 +914,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -923,13 +923,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, @@ -1062,7 +1062,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -1086,7 +1086,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -1095,13 +1095,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 0c2e6f19f1..dcdd8b3677 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -219,10 +219,10 @@ namespace Jellyfin.Api.Controllers AudioBitRate = audioBitRate ?? maxStreamingBitrate, StartTimeTicks = startTimeTicks, SubtitleMethod = SubtitleDeliveryMethod.Hls, - RequireAvc = true, - DeInterlace = true, - RequireNonAnamorphic = true, - EnableMpegtsM2TsMode = true, + RequireAvc = false, + DeInterlace = false, + RequireNonAnamorphic = false, + EnableMpegtsM2TsMode = false, TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(',', mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray()), Context = EncodingContext.Static, StreamOptions = new Dictionary(), diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index 620eef5680..e95410d024 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -223,7 +223,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -247,7 +247,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -256,13 +256,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 99654e7b0d..699ca53278 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -386,7 +386,7 @@ namespace Jellyfin.Api.Controllers { Id = itemId, Container = container, - Static = @static ?? true, + Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, @@ -410,7 +410,7 @@ namespace Jellyfin.Api.Controllers Level = level, Framerate = framerate, MaxFramerate = maxFramerate, - CopyTimestamps = copyTimestamps ?? true, + CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, @@ -419,13 +419,13 @@ namespace Jellyfin.Api.Controllers SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, - RequireAvc = requireAvc ?? true, - DeInterlace = deInterlace ?? true, - RequireNonAnamorphic = requireNonAnamorphic ?? true, + RequireAvc = requireAvc ?? false, + DeInterlace = deInterlace ?? false, + RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, - EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? true, + EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 29da5d9e7f..475bea4cdb 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -631,7 +631,7 @@ namespace MediaBrowser.Model.Dlna } // Be careful, IsDirectStream==true by default (Static != false or not in query). - // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? true. + // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? false. if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) { From 74e14b4ca591b9043435ee1065827101379b1318 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 22 Mar 2021 22:34:47 +0100 Subject: [PATCH 1329/1930] fix isdirectstream default --- Emby.Dlna/PlayTo/PlayToController.cs | 6 +----- MediaBrowser.Model/Dlna/StreamInfo.cs | 4 +--- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 6021da51db..25ba18add8 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -943,11 +943,7 @@ namespace Emby.Dlna.PlayTo request.DeviceId = values.GetValueOrDefault("DeviceId"); request.MediaSourceId = values.GetValueOrDefault("MediaSourceId"); request.LiveStreamId = values.GetValueOrDefault("LiveStreamId"); - - // Be careful, IsDirectStream==true by default (Static != false or not in query). - // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? false. - request.IsDirectStream = !string.Equals("false", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase); - + request.IsDirectStream = string.Equals("true", values.GetValueOrDefault("Static"), StringComparison.OrdinalIgnoreCase); request.AudioStreamIndex = GetIntValue(values, "AudioStreamIndex"); request.SubtitleStreamIndex = GetIntValue(values, "SubtitleStreamIndex"); request.StartPositionTicks = GetLongValue(values, "StartPositionTicks"); diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 475bea4cdb..252872847a 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -630,10 +630,8 @@ namespace MediaBrowser.Model.Dlna continue; } - // Be careful, IsDirectStream==true by default (Static != false or not in query). - // See initialization of StreamingRequestDto in AudioController.GetAudioStream() method : Static = @static ?? false. if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase) && - string.Equals(pair.Value, "true", StringComparison.OrdinalIgnoreCase)) + string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase)) { continue; } From 6765f6ab172bcb5a6a98ba84087c5b51288f05d7 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 23 Mar 2021 00:12:14 +0000 Subject: [PATCH 1330/1930] fix compilation --- .../Middleware/IpBasedAccessValidationMiddleware.cs | 3 +-- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 96e6fd8340..7d92bd7d31 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -29,9 +29,8 @@ namespace Jellyfin.Server.Middleware /// /// The current HTTP context. /// The network manager. - /// The server configuration manager. /// The async task. - public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager) + public async Task Invoke(HttpContext httpContext, INetworkManager networkManager) { if (httpContext.IsLocal()) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index de81ad0a6d..5d22b4d334 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -83,7 +83,7 @@ namespace Jellyfin.Networking.Tests /// /// Checks IP address formats. /// - /// + /// IP Address. [Theory] [InlineData("127.0.0.1")] [InlineData("127.0.0.1:123")] @@ -107,7 +107,7 @@ namespace Jellyfin.Networking.Tests /// /// Checks IP address formats. /// - /// + /// IP Address. [Theory] [InlineData("127.0.0.1")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] From 572600b38ec560ee57e9954e2967014a042a1c06 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 23 Mar 2021 15:47:55 +0100 Subject: [PATCH 1331/1930] Use conditional operator instead of if/else block --- .../Parsers/MovieNfoParserTests.cs | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index 76e10b4515..4c556b4d6b 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -56,26 +56,15 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers .Returns(new UserItemData()); var directoryService = new Mock(); - if (MediaBrowser.Common.System.OperatingSystem.Id != OperatingSystemId.Windows) + _localImageFileMetadata = new FileSystemMetadata() { - _localImageFileMetadata = new FileSystemMetadata() - { - Exists = true, - FullName = "/media/movies/Justice League (2017).jpg" - }; - directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName)) - .Returns(_localImageFileMetadata); - } - else - { - _localImageFileMetadata = new FileSystemMetadata() - { - Exists = true, - FullName = "C:\\media\\movies\\Justice League (2017).jpg" - }; - directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName)) - .Returns(_localImageFileMetadata); - } + Exists = true, + FullName = MediaBrowser.Common.System.OperatingSystem.Id == OperatingSystemId.Windows ? + "C:\\media\\movies\\Justice League (2017).jpg" + : "/media/movies/Justice League (2017).jpg" + }; + directoryService.Setup(x => x.GetFile(_localImageFileMetadata.FullName)) + .Returns(_localImageFileMetadata); _userDataManager = userData.Object; _parser = new MovieNfoParser( From 19e4ef82dda1cbba9d533047950afb42c425749a Mon Sep 17 00:00:00 2001 From: David Date: Tue, 23 Mar 2021 17:16:10 +0100 Subject: [PATCH 1332/1930] Remove conversion from IPAddress to string to IPAddress --- .../HttpServer/Security/SessionContext.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 25 +++++++++++++------ Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 5 ++-- Jellyfin.Api/Helpers/RequestHelpers.cs | 2 +- .../Extensions/HttpContextExtensions.cs | 4 +-- .../LocalAccessHandlerTests.cs | 3 ++- 7 files changed, 28 insertions(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index 040b6b9e4e..dd77b45d89 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.HttpServer.Security var authorization = _authContext.GetAuthorizationInfo(requestContext); var user = authorization.User; - return _sessionManager.LogSessionActivity(authorization.Client, authorization.Version, authorization.DeviceId, authorization.Device, requestContext.GetNormalizedRemoteIp(), user); + return _sessionManager.LogSessionActivity(authorization.Client, authorization.Version, authorization.DeviceId, authorization.Device, requestContext.GetNormalizedRemoteIp().ToString(), user); } public SessionInfo GetSession(object requestContext) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 43ee309b76..3c0d2aca16 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -21,6 +21,7 @@ using MediaBrowser.Model.Users; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; namespace Jellyfin.Api.Controllers { @@ -36,6 +37,7 @@ namespace Jellyfin.Api.Controllers private readonly IDeviceManager _deviceManager; private readonly IAuthorizationContext _authContext; private readonly IServerConfigurationManager _config; + private readonly ILogger _logger; /// /// Initializes a new instance of the class. @@ -46,13 +48,15 @@ namespace Jellyfin.Api.Controllers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of the interface. public UserController( IUserManager userManager, ISessionManager sessionManager, INetworkManager networkManager, IDeviceManager deviceManager, IAuthorizationContext authContext, - IServerConfigurationManager config) + IServerConfigurationManager config, + ILogger logger) { _userManager = userManager; _sessionManager = sessionManager; @@ -60,6 +64,7 @@ namespace Jellyfin.Api.Controllers _deviceManager = deviceManager; _authContext = authContext; _config = config; + _logger = logger; } /// @@ -118,7 +123,7 @@ namespace Jellyfin.Api.Controllers return NotFound("User not found"); } - var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp()); + var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString()); return result; } @@ -204,7 +209,7 @@ namespace Jellyfin.Api.Controllers DeviceName = auth.Device, Password = request.Pw, PasswordSha1 = request.Password, - RemoteEndPoint = HttpContext.GetNormalizedRemoteIp(), + RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(), Username = request.Username }).ConfigureAwait(false); @@ -291,7 +296,7 @@ namespace Jellyfin.Api.Controllers user.Username, request.CurrentPw, request.CurrentPw, - HttpContext.GetNormalizedRemoteIp(), + HttpContext.GetNormalizedRemoteIp().ToString(), false).ConfigureAwait(false); if (success == null) @@ -483,7 +488,7 @@ namespace Jellyfin.Api.Controllers await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false); } - var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp()); + var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString()); return result; } @@ -498,8 +503,14 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status200OK)] public async Task> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest) { + var ip = HttpContext.GetNormalizedRemoteIp(); var isLocal = HttpContext.IsLocal() - || _networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()); + || _networkManager.IsInLocalNetwork(ip); + + if (isLocal) + { + _logger.LogWarning("Password reset proccess initiated from outside the local network with IP: {IP}", ip); + } var result = await _userManager.StartForgotPasswordProcess(forgotPasswordRequest.EnteredUsername, isLocal).ConfigureAwait(false); @@ -581,7 +592,7 @@ namespace Jellyfin.Api.Controllers var result = users .OrderBy(u => u.Username) - .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp())); + .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString())); return result; } diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 16380f0bba..751b48682d 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -434,7 +434,7 @@ namespace Jellyfin.Api.Helpers } } - private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, string ipAddress) + private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress) { // Within the local network this will likely do more harm than good. if (_networkManager.IsInLocalNetwork(ipAddress)) diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index ce6740fc99..a2d0e7030a 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -1,6 +1,7 @@ using System; using System.Globalization; using System.Linq; +using System.Net; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -179,7 +180,7 @@ namespace Jellyfin.Api.Helpers bool enableTranscoding, bool allowVideoStreamCopy, bool allowAudioStreamCopy, - string ipAddress) + IPAddress ipAddress) { var streamBuilder = new StreamBuilder(_mediaEncoder, _logger); @@ -551,7 +552,7 @@ namespace Jellyfin.Api.Helpers } } - private int? GetMaxBitrate(int? clientMaxBitrate, User user, string ipAddress) + private int? GetMaxBitrate(int? clientMaxBitrate, User user, IPAddress ipAddress) { var maxBitrate = clientMaxBitrate; var remoteClientMaxBitrate = user.RemoteClientBitrateLimit ?? 0; diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 94856e03ed..56585aeab5 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -84,7 +84,7 @@ namespace Jellyfin.Api.Helpers authorization.Version, authorization.DeviceId, authorization.Device, - request.HttpContext.GetNormalizedRemoteIp(), + request.HttpContext.GetNormalizedRemoteIp().ToString(), user); if (session == null) diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs index 19fa95480d..e51ad42d12 100644 --- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs +++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions /// /// The HTTP context. /// The remote caller IP address. - public static string GetNormalizedRemoteIp(this HttpContext context) + public static IPAddress GetNormalizedRemoteIp(this HttpContext context) { // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests) var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback; @@ -35,7 +35,7 @@ namespace MediaBrowser.Common.Extensions ip = ip.MapToIPv4(); } - return ip.ToString(); + return ip; } } } diff --git a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs index 09ffa84689..5b3d784ffa 100644 --- a/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs +++ b/tests/Jellyfin.Api.Tests/Auth/LocalAccessPolicy/LocalAccessHandlerTests.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Net; using System.Threading.Tasks; using AutoFixture; using AutoFixture.AutoMoq; @@ -41,7 +42,7 @@ namespace Jellyfin.Api.Tests.Auth.LocalAccessPolicy public async Task LocalAccessOnly(bool isInLocalNetwork, bool shouldSucceed) { _networkManagerMock - .Setup(n => n.IsInLocalNetwork(It.IsAny())) + .Setup(n => n.IsInLocalNetwork(It.IsAny())) .Returns(isInLocalNetwork); TestHelpers.SetupConfigurationManager(_configurationManagerMock, true); From c2af50c51dd4d49ce44604ba5b34d77fad01a130 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 23 Mar 2021 17:39:55 +0100 Subject: [PATCH 1333/1930] Add tests for IsInNetwork --- .../NetworkManagerTests.cs | 63 +++++++++++++++++++ .../NetworkParseTests.cs | 28 +-------- 2 files changed, 64 insertions(+), 27 deletions(-) create mode 100644 tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs new file mode 100644 index 0000000000..1cad625b73 --- /dev/null +++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs @@ -0,0 +1,63 @@ +using System.Net; +using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Manager; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Jellyfin.Networking.Tests +{ + public class NetworkManagerTests + { + /// + /// Checks that the given IP address is in the specified network(s). + /// + /// Network address(es). + /// The IP to check. + [Theory] + [InlineData("192.168.2.1/24", "192.168.2.123")] + [InlineData("192.168.2.1/24, !192.168.2.122/32", "192.168.2.123")] + [InlineData("fd23:184f:2029:0::/56", "fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0::/56, !fd23:184f:2029:0:3139:7386:67d7:d518/128", "fd23:184f:2029:0:3139:7386:67d7:d517")] + public void InNetwork_True_Success(string network, string value) + { + var ip = IPAddress.Parse(value); + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + LocalNetworkSubnets = network.Split(',') + }; + + using var networkManager = new NetworkManager(NetworkParseTests.GetMockConfig(conf), new NullLogger()); + + Assert.True(networkManager.IsInLocalNetwork(ip)); + } + + /// + /// Checks that thge given IP address is not in the network provided. + /// + /// Network address(es). + /// The IP to check. + [Theory] + [InlineData("192.168.10.0/24", "192.168.11.1")] + [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")] + [InlineData("192.168.10.0/24", "fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0::/56", "fd24:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0::/56, !fd23:184f:2029:0:3139:7386:67d7:d500/120", "fd23:184f:2029:0:3139:7386:67d7:d517")] + [InlineData("fd23:184f:2029:0::/56", "192.168.10.60")] + public void InNetwork_False_Success(string network, string value) + { + var ip = IPAddress.Parse(value); + var conf = new NetworkConfiguration() + { + EnableIPV6 = true, + EnableIPV4 = true, + LocalNetworkSubnets = network.Split(',') + }; + + using var nm = new NetworkManager(NetworkParseTests.GetMockConfig(conf), new NullLogger()); + + Assert.False(nm.IsInLocalNetwork(ip)); + } + } +} diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index c3469035eb..d8541d76bb 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -13,7 +13,7 @@ namespace Jellyfin.Networking.Tests { public class NetworkParseTests { - private static IConfigurationManager GetMockConfig(NetworkConfiguration conf) + internal static IConfigurationManager GetMockConfig(NetworkConfiguration conf) { var configManager = new Mock { @@ -54,32 +54,6 @@ namespace Jellyfin.Networking.Tests Assert.Equal(nm.GetInternalBindAddresses().AsString(), value); } - /// - /// Check that the value given is in the network provided. - /// - /// Network address. - /// Value to check. - [Theory] - [InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")] - public void IsInNetwork(string network, string value) - { - if (network == null) - { - throw new ArgumentNullException(nameof(network)); - } - - var conf = new NetworkConfiguration() - { - EnableIPV6 = true, - EnableIPV4 = true, - LocalNetworkSubnets = network.Split(',') - }; - - using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - - Assert.False(nm.IsInLocalNetwork(value)); - } - /// /// Checks IP address formats. /// From a4cac09d5b90dda5b7d7978e083676394022ffc1 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 23 Mar 2021 19:25:32 +0100 Subject: [PATCH 1334/1930] Use |= --- .../Manager/MetadataService.cs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 494e479a57..437b43ecaf 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -473,7 +473,7 @@ namespace MediaBrowser.Providers.Manager if ((originalPremiereDate ?? DateTime.MinValue) != (item.PremiereDate ?? DateTime.MinValue) || (originalProductionYear ?? -1) != (item.ProductionYear ?? -1)) { - updateType = updateType | ItemUpdateType.MetadataEdit; + updateType |= ItemUpdateType.MetadataEdit; } return updateType; @@ -493,7 +493,7 @@ namespace MediaBrowser.Providers.Manager if (currentList.Length != item.Genres.Length || !currentList.OrderBy(i => i).SequenceEqual(item.Genres.OrderBy(i => i), StringComparer.OrdinalIgnoreCase)) { - updateType = updateType | ItemUpdateType.MetadataEdit; + updateType |= ItemUpdateType.MetadataEdit; } } @@ -514,7 +514,7 @@ namespace MediaBrowser.Providers.Manager if (currentList.Length != item.Studios.Length || !currentList.OrderBy(i => i).SequenceEqual(item.Studios.OrderBy(i => i), StringComparer.OrdinalIgnoreCase)) { - updateType = updateType | ItemUpdateType.MetadataEdit; + updateType |= ItemUpdateType.MetadataEdit; } } @@ -529,7 +529,7 @@ namespace MediaBrowser.Providers.Manager { if (item.UpdateRatingToItems(children)) { - updateType = updateType | ItemUpdateType.MetadataEdit; + updateType |= ItemUpdateType.MetadataEdit; } } @@ -686,7 +686,7 @@ namespace MediaBrowser.Providers.Manager var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType>(), cancellationToken) .ConfigureAwait(false); - refreshResult.UpdateType = refreshResult.UpdateType | remoteResult.UpdateType; + refreshResult.UpdateType |= remoteResult.UpdateType; refreshResult.ErrorMessage = remoteResult.ErrorMessage; refreshResult.Failures += remoteResult.Failures; } @@ -709,12 +709,12 @@ namespace MediaBrowser.Providers.Manager foreach (var remoteImage in localItem.RemoteImages) { await ProviderManager.SaveImage(item, remoteImage.url, remoteImage.type, null, cancellationToken).ConfigureAwait(false); - refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.ImageUpdate; + refreshResult.UpdateType |= ItemUpdateType.ImageUpdate; } if (imageService.MergeImages(item, localItem.Images)) { - refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.ImageUpdate; + refreshResult.UpdateType |= ItemUpdateType.ImageUpdate; } if (localItem.UserDataList != null) @@ -723,7 +723,7 @@ namespace MediaBrowser.Providers.Manager } MergeData(localItem, temp, Array.Empty(), !options.ReplaceAllMetadata, true); - refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataImport; + refreshResult.UpdateType |= ItemUpdateType.MetadataImport; // Only one local provider allowed per item if (item.IsLocked || localItem.Item.IsLocked || IsFullLocalMetadata(localItem.Item)) @@ -755,7 +755,7 @@ namespace MediaBrowser.Providers.Manager var remoteResult = await ExecuteRemoteProviders(temp, logName, id, providers.OfType>(), cancellationToken) .ConfigureAwait(false); - refreshResult.UpdateType = refreshResult.UpdateType | remoteResult.UpdateType; + refreshResult.UpdateType |= remoteResult.UpdateType; refreshResult.ErrorMessage = remoteResult.ErrorMessage; refreshResult.Failures += remoteResult.Failures; } @@ -851,7 +851,7 @@ namespace MediaBrowser.Providers.Manager MergeData(result, temp, Array.Empty(), false, false); MergeNewData(temp.Item, id); - refreshResult.UpdateType = refreshResult.UpdateType | ItemUpdateType.MetadataDownload; + refreshResult.UpdateType |= ItemUpdateType.MetadataDownload; } else { From 415b03d719e054a3cc6998d89c3f4a13806e0a9e Mon Sep 17 00:00:00 2001 From: Mason Tran Date: Wed, 24 Mar 2021 02:35:44 -0400 Subject: [PATCH 1335/1930] Delay starting services until after network is online --- debian/jellyfin.service | 2 +- fedora/jellyfin.service | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/debian/jellyfin.service b/debian/jellyfin.service index f1a8f4652c..c9d1a4d130 100644 --- a/debian/jellyfin.service +++ b/debian/jellyfin.service @@ -1,6 +1,6 @@ [Unit] Description = Jellyfin Media Server -After = network.target +After = network-online.target [Service] Type = simple diff --git a/fedora/jellyfin.service b/fedora/jellyfin.service index b092ebf2f0..f706b0ad3f 100644 --- a/fedora/jellyfin.service +++ b/fedora/jellyfin.service @@ -1,5 +1,5 @@ [Unit] -After=network.target +After=network-online.target Description=Jellyfin is a free software media system that puts you in control of managing and streaming your media. [Service] From d77507ba09a010dc653814ea620aafa42348a373 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Mar 2021 18:09:40 +0100 Subject: [PATCH 1336/1930] Rewrite PasswordHash.Parse to work with ReadOnlySpans --- .../Cryptography/PasswordHash.cs | 121 +++++++++++---- .../Cryptography/PasswordHashTests.cs | 139 ++++++++++++++++++ .../PasswordHashTests.cs | 31 ---- 3 files changed, 233 insertions(+), 58 deletions(-) create mode 100644 tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs delete mode 100644 tests/Jellyfin.Common.Tests/PasswordHashTests.cs diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index 3e2eae1c8e..81e980bf2f 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#nullable enable using System; using System.Collections.Generic; @@ -30,6 +31,16 @@ namespace MediaBrowser.Common.Cryptography public PasswordHash(string id, byte[] hash, byte[] salt, Dictionary parameters) { + if (id == null) + { + throw new ArgumentNullException(nameof(id)); + } + + if (id.Length == 0) + { + throw new ArgumentException("String can't be empty", nameof(id)); + } + Id = id; _hash = hash; _salt = salt; @@ -59,58 +70,109 @@ namespace MediaBrowser.Common.Cryptography /// Return the hashed password. public ReadOnlySpan Hash => _hash; - public static PasswordHash Parse(string hashString) + public static PasswordHash Parse(ReadOnlySpan hashString) { - // The string should at least contain the hash function and the hash itself - string[] splitted = hashString.Split('$'); - if (splitted.Length < 3) + if (hashString.IsEmpty) { - throw new ArgumentException("String doesn't contain enough segments", nameof(hashString)); + throw new ArgumentException("String can't be empty", nameof(hashString)); } - // Start at 1, the first index shouldn't contain any data - int index = 1; + if (hashString[0] != '$') + { + throw new FormatException("Hash string must start with a $"); + } - // Name of the hash function - string id = splitted[index++]; + // Ignore first $ + hashString = hashString[1..]; + + int nextSegment = hashString.IndexOf('$'); + if (hashString.IsEmpty || nextSegment == 0) + { + throw new FormatException("Hash string must contain a valid id"); + } + else if (nextSegment == -1) + { + return new PasswordHash(hashString.ToString(), Array.Empty()); + } + + ReadOnlySpan id = hashString[..nextSegment]; + hashString = hashString[(nextSegment + 1)..]; + Dictionary? parameters = null; + + nextSegment = hashString.IndexOf('$'); // Optional parameters - Dictionary parameters = new Dictionary(); - if (splitted[index].IndexOf('=', StringComparison.Ordinal) != -1) + ReadOnlySpan parametersSpan = nextSegment == -1 ? hashString : hashString[..nextSegment]; + if (parametersSpan.Contains('=')) { - foreach (string paramset in splitted[index++].Split(',')) + while (!parametersSpan.IsEmpty) { - if (string.IsNullOrEmpty(paramset)) + ReadOnlySpan parameter; + int index = parametersSpan.IndexOf(','); + if (index == -1) { - continue; + parameter = parametersSpan; + parametersSpan = ReadOnlySpan.Empty; + } + else + { + parameter = parametersSpan[..index]; + parametersSpan = parametersSpan[(index + 1)..]; } - string[] fields = paramset.Split('='); - if (fields.Length != 2) + int splitIndex = parameter.IndexOf('='); + if (splitIndex == -1 || splitIndex == 0 || splitIndex == parameter.Length - 1) { - throw new InvalidDataException($"Malformed parameter in password hash string {paramset}"); + throw new FormatException($"Malformed parameter in password hash string"); } - parameters.Add(fields[0], fields[1]); + (parameters ??= new Dictionary()).Add( + parameter[..splitIndex].ToString(), + parameter[(splitIndex + 1)..].ToString()); } + + if (nextSegment == -1) + { + // parameters can't be null here + return new PasswordHash(id.ToString(), Array.Empty(), Array.Empty(), parameters!); + } + + hashString = hashString[(nextSegment + 1)..]; + nextSegment = hashString.IndexOf('$'); + } + + if (nextSegment == 0) + { + throw new FormatException($"Hash string contains an empty segment"); } byte[] hash; byte[] salt; - // Check if the string also contains a salt - if (splitted.Length - index == 2) + if (nextSegment == -1) { - salt = Convert.FromHexString(splitted[index++]); - hash = Convert.FromHexString(splitted[index++]); + salt = Array.Empty(); + hash = Convert.FromHexString(hashString); } else { - salt = Array.Empty(); - hash = Convert.FromHexString(splitted[index++]); + salt = Convert.FromHexString(hashString[..nextSegment]); + hashString = hashString[(nextSegment + 1)..]; + nextSegment = hashString.IndexOf('$'); + if (nextSegment != -1) + { + throw new FormatException("Hash string contains too many segments"); + } + + if (hashString.IsEmpty) + { + throw new FormatException("Hash segment is empty"); + } + + hash = Convert.FromHexString(hashString); } - return new PasswordHash(id, hash, salt, parameters); + return new PasswordHash(id.ToString(), hash, salt, parameters ?? new Dictionary()); } private void SerializeParameters(StringBuilder stringBuilder) @@ -147,8 +209,13 @@ namespace MediaBrowser.Common.Cryptography .Append(Convert.ToHexString(_salt)); } - return str.Append('$') - .Append(Convert.ToHexString(_hash)).ToString(); + if (_hash.Length != 0) + { + str.Append('$') + .Append(Convert.ToHexString(_hash)); + } + + return str.ToString(); } } } diff --git a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs new file mode 100644 index 0000000000..6da0a3037e --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using MediaBrowser.Common.Cryptography; +using Xunit; + +namespace Jellyfin.Common.Tests.Cryptography +{ + public static class PasswordHashTests + { + [Fact] + public static void Ctor_Null_ThrowsArgumentNullException() + { + Assert.Throws(() => new PasswordHash(null!, Array.Empty())); + } + + [Fact] + public static void Ctor_Empty_ThrowsArgumentException() + { + Assert.Throws(() => new PasswordHash(string.Empty, Array.Empty())); + } + + public static IEnumerable Parse_Valid_TestData() + { + yield return new object[] + { + "$PBKDF2", + new PasswordHash("PBKDF2", Array.Empty()) + }; + + yield return new object[] + { + "$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", + new PasswordHash( + "PBKDF2", + Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"), + Array.Empty(), + new Dictionary() + { + { "iterations", "1000" } + }) + }; + + yield return new object[] + { + "$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", + new PasswordHash( + "PBKDF2", + Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"), + Array.Empty(), + new Dictionary() + { + { "iterations", "1000" }, + { "m", "120" } + }) + }; + + yield return new object[] + { + "$PBKDF2$iterations=1000,m=120$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", + new PasswordHash( + "PBKDF2", + Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"), + Convert.FromHexString("69F420"), + new Dictionary() + { + { "iterations", "1000" }, + { "m", "120" } + }) + }; + + yield return new object[] + { + "$PBKDF2$iterations=1000,m=120", + new PasswordHash( + "PBKDF2", + Array.Empty(), + Array.Empty(), + new Dictionary() + { + { "iterations", "1000" }, + { "m", "120" } + }) + }; + } + + [Theory] + [MemberData(nameof(Parse_Valid_TestData))] + public static void Parse_Valid_Success(string passwordHashString, PasswordHash expected) + { + var passwordHash = PasswordHash.Parse(passwordHashString); + Assert.Equal(expected.Id, passwordHash.Id); + Assert.Equal(expected.Parameters, passwordHash.Parameters); + Assert.Equal(expected.Salt.ToArray(), passwordHash.Salt.ToArray()); + Assert.Equal(expected.Hash.ToArray(), passwordHash.Hash.ToArray()); + Assert.Equal(expected.ToString(), passwordHash.ToString()); + } + + [Theory] + [InlineData("$PBKDF2")] + [InlineData("$PBKDF2$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] + [InlineData("$PBKDF2$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] + [InlineData("$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] + [InlineData("$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] + [InlineData("$PBKDF2$iterations=1000,m=120")] + public static void ToString_Roundtrip_Success(string passwordHash) + { + Assert.Equal(passwordHash, PasswordHash.Parse(passwordHash).ToString()); + } + + [Fact] + public static void Parse_Null_ThrowsArgumentException() + { + Assert.Throws(() => PasswordHash.Parse(null)); + } + + [Fact] + public static void Parse_Empty_ThrowsArgumentException() + { + Assert.Throws(() => PasswordHash.Parse(string.Empty)); + } + + [Theory] + [InlineData("$")] // No id + [InlineData("$$")] // Empty segments + [InlineData("PBKDF2$")] // Doesn't start with $ + [InlineData("$PBKDF2$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty segment + [InlineData("$PBKDF2$iterations=1000$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty salt segment + [InlineData("$PBKDF2$=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter + [InlineData("$PBKDF2$=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter + [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter + [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$")] // Ends on $ + [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$anotherone")] // Extra segment + [InlineData("$PBKDF2$69F420$")] // Empty hash + public static void Parse_InvalidFormat_ThrowsFormatException(string passwordHash) + { + Assert.Throws(() => PasswordHash.Parse(passwordHash)); + } + } +} diff --git a/tests/Jellyfin.Common.Tests/PasswordHashTests.cs b/tests/Jellyfin.Common.Tests/PasswordHashTests.cs deleted file mode 100644 index c4422bd105..0000000000 --- a/tests/Jellyfin.Common.Tests/PasswordHashTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using MediaBrowser.Common; -using MediaBrowser.Common.Cryptography; -using Xunit; - -namespace Jellyfin.Common.Tests -{ - public class PasswordHashTests - { - [Theory] - [InlineData( - "$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", - "PBKDF2", - "", - "62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] - public void ParseTest(string passwordHash, string id, string salt, string hash) - { - var pass = PasswordHash.Parse(passwordHash); - Assert.Equal(id, pass.Id); - Assert.Equal(salt, Convert.ToHexString(pass.Salt)); - Assert.Equal(hash, Convert.ToHexString(pass.Hash)); - } - - [Theory] - [InlineData("$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] - public void ToStringTest(string passwordHash) - { - Assert.Equal(passwordHash, PasswordHash.Parse(passwordHash).ToString()); - } - } -} From c2cd7fa0b2441212ac0de16ffcef18883ee8c665 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 24 Mar 2021 18:39:33 +0100 Subject: [PATCH 1337/1930] Add more PasswordHash tests --- .../Cryptography/PasswordHashTests.cs | 76 +++++++++++++++---- 1 file changed, 61 insertions(+), 15 deletions(-) diff --git a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs index 6da0a3037e..e6c325bac0 100644 --- a/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs +++ b/tests/Jellyfin.Common.Tests/Cryptography/PasswordHashTests.cs @@ -21,12 +21,65 @@ namespace Jellyfin.Common.Tests.Cryptography public static IEnumerable Parse_Valid_TestData() { + // Id yield return new object[] { "$PBKDF2", new PasswordHash("PBKDF2", Array.Empty()) }; + // Id + parameter + yield return new object[] + { + "$PBKDF2$iterations=1000", + new PasswordHash( + "PBKDF2", + Array.Empty(), + Array.Empty(), + new Dictionary() + { + { "iterations", "1000" }, + }) + }; + + // Id + parameters + yield return new object[] + { + "$PBKDF2$iterations=1000,m=120", + new PasswordHash( + "PBKDF2", + Array.Empty(), + Array.Empty(), + new Dictionary() + { + { "iterations", "1000" }, + { "m", "120" } + }) + }; + + // Id + hash + yield return new object[] + { + "$PBKDF2$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", + new PasswordHash( + "PBKDF2", + Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"), + Array.Empty(), + new Dictionary()) + }; + + // Id + salt + hash + yield return new object[] + { + "$PBKDF2$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", + new PasswordHash( + "PBKDF2", + Convert.FromHexString("62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D"), + Convert.FromHexString("69F420"), + new Dictionary()) + }; + + // Id + parameter + hash yield return new object[] { "$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", @@ -40,6 +93,7 @@ namespace Jellyfin.Common.Tests.Cryptography }) }; + // Id + parameters + hash yield return new object[] { "$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", @@ -54,6 +108,7 @@ namespace Jellyfin.Common.Tests.Cryptography }) }; + // Id + parameters + salt + hash yield return new object[] { "$PBKDF2$iterations=1000,m=120$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D", @@ -67,20 +122,6 @@ namespace Jellyfin.Common.Tests.Cryptography { "m", "120" } }) }; - - yield return new object[] - { - "$PBKDF2$iterations=1000,m=120", - new PasswordHash( - "PBKDF2", - Array.Empty(), - Array.Empty(), - new Dictionary() - { - { "iterations", "1000" }, - { "m", "120" } - }) - }; } [Theory] @@ -101,6 +142,7 @@ namespace Jellyfin.Common.Tests.Cryptography [InlineData("$PBKDF2$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] [InlineData("$PBKDF2$iterations=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] [InlineData("$PBKDF2$iterations=1000,m=120$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] + [InlineData("$PBKDF2$iterations=1000,m=120$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] [InlineData("$PBKDF2$iterations=1000,m=120")] public static void ToString_Roundtrip_Success(string passwordHash) { @@ -125,11 +167,15 @@ namespace Jellyfin.Common.Tests.Cryptography [InlineData("PBKDF2$")] // Doesn't start with $ [InlineData("$PBKDF2$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty segment [InlineData("$PBKDF2$iterations=1000$$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Empty salt segment + [InlineData("$PBKDF2$iterations=1000$69F420$")] // Empty hash segment [InlineData("$PBKDF2$=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter [InlineData("$PBKDF2$=1000$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid parmeter [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$")] // Ends on $ - [InlineData("$PBKDF2$iterations=$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$anotherone")] // Extra segment + [InlineData("$PBKDF2$iterations=$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$")] // Extra segment + [InlineData("$PBKDF2$iterations=$69F420$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D$anotherone")] // Extra segment + [InlineData("$PBKDF2$iterations=$invalidstalt$62FBA410AFCA5B4475F35137AB2E8596B127E4D927BA23F6CC05C067E897042D")] // Invalid salt + [InlineData("$PBKDF2$iterations=$69F420$invalid hash")] // Invalid hash [InlineData("$PBKDF2$69F420$")] // Empty hash public static void Parse_InvalidFormat_ThrowsFormatException(string passwordHash) { From 136136dea95321a1b691d3d5cafeac4f946aaf50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szymon=20Aceda=C5=84ski?= Date: Wed, 24 Mar 2021 20:26:01 +0100 Subject: [PATCH 1338/1930] Fix incorrect responses for HEAD /audio//stream Without this fix my Samsung Soundbar (HW-Q80R) fails to play using DLNA and returns "Error: Resource not found (716)" instead. I had a look on tcpdump network logs between Jellyfin and the soundbar and noticed that the device performs a HEAD request for the media before responding to the DLNA UPNP control request from Jellyfin (or BubbleUPNP Android App). Jellyfin retuns 204 No Content response, which is unusual. Common web servers generally return 200 OK if the GET would return content, and this is not-very-clearly suggested [in HTTP spec](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1) The other patch is to ensure, that invalid Content-Length: 0 is not returned with the HEAD response in the streaming case. I think in both cases we still don't return the same headers with HEAD as with GET (e.g. Content-Length or Accept-Ranges), but at least we don't return anything misleading. --- Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index f828b1d9d6..a567fce1e4 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -46,7 +46,8 @@ namespace Jellyfin.Api.Helpers if (isHeadRequest) { - return new FileContentResult(Array.Empty(), contentType); + httpContext.Response.Headers[HeaderNames.ContentType] = contentType; + return new OkResult(); } return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), contentType); @@ -71,7 +72,7 @@ namespace Jellyfin.Api.Helpers // if the request is a head request, return a NoContent result with the same headers as it would with a GET request if (isHeadRequest) { - return new NoContentResult(); + return new OkResult(); } return new PhysicalFileResult(path, contentType) { EnableRangeProcessing = true }; From 066c19a26b1dbc36c20439426110738b2ce1c2d6 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 24 Mar 2021 21:06:03 +0100 Subject: [PATCH 1339/1930] Fix possible null ref exception --- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 46a7feb7ff..c18838caf7 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -208,7 +208,7 @@ namespace Emby.Server.Implementations.Library /// Gets or sets the list of entity resolution ignore rules. /// /// The entity resolution ignore rules. - private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; } + private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; } = Array.Empty(); /// /// Gets or sets the list of currently registered entity resolvers. From 86852178c21f19944360ab0728042faa127d0128 Mon Sep 17 00:00:00 2001 From: cocool97 <34218602+cocool97@users.noreply.github.com> Date: Wed, 24 Mar 2021 21:23:59 +0100 Subject: [PATCH 1340/1930] Update MediaBrowser.Controller/LiveTv/ChannelInfo.cs Co-authored-by: Cody Robibero --- MediaBrowser.Controller/LiveTv/ChannelInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs index 0f3f878475..166c4d77c0 100644 --- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs @@ -46,9 +46,9 @@ namespace MediaBrowser.Controller.LiveTv public ChannelType ChannelType { get; set; } /// - /// Gets or sets the group of the channel + /// Gets or sets the group of the channel. /// - /// The group of the channel + /// The group of the channel. public string ChannelGroup { get; set; } /// From b1e8a8565f316e9b3d65b3a681384dfc8d743b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szymon=20Aceda=C5=84ski?= Date: Wed, 24 Mar 2021 22:46:08 +0100 Subject: [PATCH 1341/1930] Update Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs Co-authored-by: Claus Vium --- Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs index a567fce1e4..b0fd59e5e3 100644 --- a/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs +++ b/Jellyfin.Api/Helpers/FileStreamResponseHelpers.cs @@ -69,7 +69,7 @@ namespace Jellyfin.Api.Helpers { httpContext.Response.ContentType = contentType; - // if the request is a head request, return a NoContent result with the same headers as it would with a GET request + // if the request is a head request, return an OkResult (200) with the same headers as it would with a GET request if (isHeadRequest) { return new OkResult(); From ef9eba8bc9f697ed6d8bf973d7f5c8d7865ecd18 Mon Sep 17 00:00:00 2001 From: MrTimscampi Date: Thu, 25 Mar 2021 11:45:27 +0100 Subject: [PATCH 1342/1930] Ignore format for ISO files --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 6 ++++++ MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 09080e7b2c..92b9a8c7eb 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -313,6 +313,12 @@ namespace MediaBrowser.Controller.MediaEncoding return null; } + // ISO files don't have an ffmpeg format + if (string.Equals(container, "iso", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + return container; } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 47cf020b4e..205933ae20 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -370,7 +370,7 @@ namespace MediaBrowser.MediaEncoding.Encoder public string GetInputArgument(string inputFile, MediaSourceInfo mediaSource) { var prefix = "file"; - if (mediaSource.VideoType == VideoType.BluRay || mediaSource.VideoType == VideoType.Iso) + if (mediaSource.VideoType == VideoType.BluRay) { prefix = "bluray"; } From 5bb7d99b48feb66a393da73f4a056b6dd5f38739 Mon Sep 17 00:00:00 2001 From: MrTimscampi Date: Thu, 25 Mar 2021 13:16:09 +0100 Subject: [PATCH 1343/1930] Remove DVDs from files exempt from chapter image extraction --- Emby.Server.Implementations/MediaEncoder/EncodingManager.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index c6e931448d..a9dab91383 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -82,11 +82,6 @@ namespace Emby.Server.Implementations.MediaEncoder return false; } - if (video.VideoType == VideoType.Dvd) - { - return false; - } - if (video.IsShortcut) { return false; From b3d084044e2d98590d9c939090ba522aa66dff82 Mon Sep 17 00:00:00 2001 From: cvium Date: Thu, 25 Mar 2021 15:09:37 +0100 Subject: [PATCH 1344/1930] enable range processing for download endpoints --- Jellyfin.Api/Controllers/LibraryController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index f8e8825ef0..1d4bbe61e8 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -114,7 +114,7 @@ namespace Jellyfin.Api.Controllers return NotFound(); } - return PhysicalFile(item.Path, MimeTypes.GetMimeType(item.Path)); + return PhysicalFile(item.Path, MimeTypes.GetMimeType(item.Path), true); } /// @@ -666,7 +666,7 @@ namespace Jellyfin.Api.Controllers } // TODO determine non-ASCII validity. - return PhysicalFile(path, MimeTypes.GetMimeType(path), filename); + return PhysicalFile(path, MimeTypes.GetMimeType(path), filename, true); } /// From 4cea6d9ccfa5bddaef27800aac1c125ae22747d7 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 25 Mar 2021 18:53:36 +0100 Subject: [PATCH 1345/1930] Apply suggestions from code review Co-authored-by: Cody Robibero --- MediaBrowser.Common/Cryptography/PasswordHash.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index 81e980bf2f..f2ecc4741b 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -123,7 +123,7 @@ namespace MediaBrowser.Common.Cryptography int splitIndex = parameter.IndexOf('='); if (splitIndex == -1 || splitIndex == 0 || splitIndex == parameter.Length - 1) { - throw new FormatException($"Malformed parameter in password hash string"); + throw new FormatException("Malformed parameter in password hash string"); } (parameters ??= new Dictionary()).Add( @@ -143,7 +143,7 @@ namespace MediaBrowser.Common.Cryptography if (nextSegment == 0) { - throw new FormatException($"Hash string contains an empty segment"); + throw new FormatException("Hash string contains an empty segment"); } byte[] hash; From 36669ff45146dd8d4dc063b6a6b1d057f2d33464 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Wed, 17 Mar 2021 19:08:11 -0400 Subject: [PATCH 1346/1930] Use correct setter access modifiers --- Jellyfin.Data/Entities/AccessSchedule.cs | 8 ++-- Jellyfin.Data/Entities/ActivityLog.cs | 7 ++- .../Entities/CustomItemDisplayPreferences.cs | 4 +- Jellyfin.Data/Entities/DisplayPreferences.cs | 12 +++-- Jellyfin.Data/Entities/Group.cs | 16 +++---- Jellyfin.Data/Entities/HomeSection.cs | 7 ++- Jellyfin.Data/Entities/ImageInfo.cs | 8 ++-- .../Entities/ItemDisplayPreferences.cs | 4 +- Jellyfin.Data/Entities/Libraries/Artwork.cs | 8 ++-- Jellyfin.Data/Entities/Libraries/Book.cs | 8 ++-- .../Entities/Libraries/BookMetadata.cs | 6 +-- Jellyfin.Data/Entities/Libraries/Chapter.cs | 8 ++-- .../Entities/Libraries/Collection.cs | 11 +++-- .../Entities/Libraries/CollectionItem.cs | 2 +- Jellyfin.Data/Entities/Libraries/Company.cs | 16 +++---- .../Entities/Libraries/CustomItem.cs | 8 ++-- Jellyfin.Data/Entities/Libraries/Episode.cs | 8 ++-- Jellyfin.Data/Entities/Libraries/Genre.cs | 6 +-- .../Entities/Libraries/ItemMetadata.cs | 37 +++++++--------- Jellyfin.Data/Entities/Libraries/Library.cs | 6 +-- .../Entities/Libraries/LibraryItem.cs | 10 ++--- Jellyfin.Data/Entities/Libraries/MediaFile.cs | 12 +++-- .../Entities/Libraries/MediaFileStream.cs | 6 +-- .../Entities/Libraries/MetadataProvider.cs | 6 +-- .../Entities/Libraries/MetadataProviderId.cs | 6 +-- Jellyfin.Data/Entities/Libraries/Movie.cs | 8 ++-- .../Entities/Libraries/MovieMetadata.cs | 6 +-- .../Entities/Libraries/MusicAlbum.cs | 10 ++--- .../Entities/Libraries/MusicAlbumMetadata.cs | 6 +-- Jellyfin.Data/Entities/Libraries/Person.cs | 16 +++---- .../Entities/Libraries/PersonRole.cs | 14 +++--- Jellyfin.Data/Entities/Libraries/Photo.cs | 8 ++-- Jellyfin.Data/Entities/Libraries/Rating.cs | 6 +-- .../Entities/Libraries/RatingSource.cs | 6 +-- Jellyfin.Data/Entities/Libraries/Release.cs | 16 +++---- Jellyfin.Data/Entities/Libraries/Season.cs | 10 ++--- Jellyfin.Data/Entities/Libraries/Series.cs | 11 ++--- .../Entities/Libraries/SeriesMetadata.cs | 6 +-- Jellyfin.Data/Entities/Libraries/Track.cs | 8 ++-- Jellyfin.Data/Entities/Permission.cs | 10 ++--- Jellyfin.Data/Entities/Preference.cs | 10 ++--- Jellyfin.Data/Entities/User.cs | 44 +++++++------------ 42 files changed, 179 insertions(+), 246 deletions(-) diff --git a/Jellyfin.Data/Entities/AccessSchedule.cs b/Jellyfin.Data/Entities/AccessSchedule.cs index 7974d3addb..befc4ca02c 100644 --- a/Jellyfin.Data/Entities/AccessSchedule.cs +++ b/Jellyfin.Data/Entities/AccessSchedule.cs @@ -26,20 +26,20 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the id of this instance. + /// Gets the id of this instance. /// /// /// Identity, Indexed, Required. /// [XmlIgnore] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// - /// Gets or sets the id of the associated user. + /// Gets the id of the associated user. /// [XmlIgnore] - public Guid UserId { get; protected set; } + public Guid UserId { get; private set; } /// /// Gets or sets the day of week. diff --git a/Jellyfin.Data/Entities/ActivityLog.cs b/Jellyfin.Data/Entities/ActivityLog.cs index e4534e8b5e..1d1b86552f 100644 --- a/Jellyfin.Data/Entities/ActivityLog.cs +++ b/Jellyfin.Data/Entities/ActivityLog.cs @@ -38,11 +38,10 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the identity of this instance. - /// This is the key in the backing database. + /// Gets the identity of this instance. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -120,7 +119,7 @@ namespace Jellyfin.Data.Entities /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs index cc46248c75..f12737f657 100644 --- a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -27,13 +27,13 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the Id. + /// Gets the Id. /// /// /// Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the user Id. diff --git a/Jellyfin.Data/Entities/DisplayPreferences.cs b/Jellyfin.Data/Entities/DisplayPreferences.cs index 64cd6812a4..646961238b 100644 --- a/Jellyfin.Data/Entities/DisplayPreferences.cs +++ b/Jellyfin.Data/Entities/DisplayPreferences.cs @@ -1,6 +1,4 @@ -#pragma warning disable CA2227 - -using System; +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -35,13 +33,13 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the Id. + /// Gets the Id. /// /// /// Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the user Id. @@ -145,8 +143,8 @@ namespace Jellyfin.Data.Entities public string? TvHome { get; set; } /// - /// Gets or sets the home sections. + /// Gets the home sections. /// - public virtual ICollection HomeSections { get; protected set; } + public virtual ICollection HomeSections { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Group.cs b/Jellyfin.Data/Entities/Group.cs index b14e22b7b3..14da0bb155 100644 --- a/Jellyfin.Data/Entities/Group.cs +++ b/Jellyfin.Data/Entities/Group.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -33,12 +31,12 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the id of this group. + /// Gets the id of this group. /// /// /// Identity, Indexed, Required. /// - public Guid Id { get; protected set; } + public Guid Id { get; private set; } /// /// Gets or sets the group's name. @@ -52,17 +50,17 @@ namespace Jellyfin.Data.Entities /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing the group's permissions. + /// Gets a collection containing the group's permissions. /// - public virtual ICollection Permissions { get; protected set; } + public virtual ICollection Permissions { get; private set; } /// - /// Gets or sets a collection containing the group's preferences. + /// Gets a collection containing the group's preferences. /// - public virtual ICollection Preferences { get; protected set; } + public virtual ICollection Preferences { get; private set; } /// public bool HasPermission(PermissionKind kind) diff --git a/Jellyfin.Data/Entities/HomeSection.cs b/Jellyfin.Data/Entities/HomeSection.cs index 5adc52491c..e194aa537c 100644 --- a/Jellyfin.Data/Entities/HomeSection.cs +++ b/Jellyfin.Data/Entities/HomeSection.cs @@ -1,5 +1,4 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Enums; namespace Jellyfin.Data.Entities @@ -10,13 +9,13 @@ namespace Jellyfin.Data.Entities public class HomeSection { /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity. Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the Id of the associated display preferences. diff --git a/Jellyfin.Data/Entities/ImageInfo.cs b/Jellyfin.Data/Entities/ImageInfo.cs index e0c37047d8..b5c7a1c120 100644 --- a/Jellyfin.Data/Entities/ImageInfo.cs +++ b/Jellyfin.Data/Entities/ImageInfo.cs @@ -20,18 +20,18 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// - /// Gets or sets the user id. + /// Gets the user id. /// - public Guid? UserId { get; protected set; } + public Guid? UserId { get; private set; } /// /// Gets or sets the path of the image. diff --git a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs index 4bfeb2fa30..948126d0a3 100644 --- a/Jellyfin.Data/Entities/ItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/ItemDisplayPreferences.cs @@ -29,13 +29,13 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the Id. + /// Gets the id. /// /// /// Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the user Id. diff --git a/Jellyfin.Data/Entities/Libraries/Artwork.cs b/Jellyfin.Data/Entities/Libraries/Artwork.cs index 84a524de2c..923525fc52 100644 --- a/Jellyfin.Data/Entities/Libraries/Artwork.cs +++ b/Jellyfin.Data/Entities/Libraries/Artwork.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -30,13 +28,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the path. @@ -58,7 +56,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Book.cs b/Jellyfin.Data/Entities/Libraries/Book.cs index aea3d58d58..a838686d05 100644 --- a/Jellyfin.Data/Entities/Libraries/Book.cs +++ b/Jellyfin.Data/Entities/Libraries/Book.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -21,11 +19,11 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets a collection containing the metadata for this book. + /// Gets a collection containing the metadata for this book. /// - public virtual ICollection BookMetadata { get; protected set; } + public virtual ICollection BookMetadata { get; private set; } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs index 1ff4327b01..4a350d200e 100644 --- a/Jellyfin.Data/Entities/Libraries/BookMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/BookMetadata.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -26,9 +24,9 @@ namespace Jellyfin.Data.Entities.Libraries public long? Isbn { get; set; } /// - /// Gets or sets a collection of the publishers for this book. + /// Gets a collection of the publishers for this book. /// - public virtual ICollection Publishers { get; protected set; } + public virtual ICollection Publishers { get; private set; } /// public ICollection Companies => Publishers; diff --git a/Jellyfin.Data/Entities/Libraries/Chapter.cs b/Jellyfin.Data/Entities/Libraries/Chapter.cs index 11f53ae20a..3d81f713d6 100644 --- a/Jellyfin.Data/Entities/Libraries/Chapter.cs +++ b/Jellyfin.Data/Entities/Libraries/Chapter.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -29,13 +27,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -74,7 +72,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; protected set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Collection.cs b/Jellyfin.Data/Entities/Libraries/Collection.cs index 4253b7eccf..7de6019692 100644 --- a/Jellyfin.Data/Entities/Libraries/Collection.cs +++ b/Jellyfin.Data/Entities/Libraries/Collection.cs @@ -1,5 +1,4 @@ #pragma warning disable CA1711 // Identifiers should not have incorrect suffix -#pragma warning disable CA2227 using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -22,13 +21,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -42,12 +41,12 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing this collection's items. + /// Gets a collection containing this collection's items. /// - public virtual ICollection Items { get; protected set; } + public virtual ICollection Items { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs index e19362bdf1..0cb4716dbe 100644 --- a/Jellyfin.Data/Entities/Libraries/CollectionItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CollectionItem.cs @@ -29,7 +29,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the library item. diff --git a/Jellyfin.Data/Entities/Libraries/Company.cs b/Jellyfin.Data/Entities/Libraries/Company.cs index 09050bb522..1abbee4458 100644 --- a/Jellyfin.Data/Entities/Libraries/Company.cs +++ b/Jellyfin.Data/Entities/Libraries/Company.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -22,27 +20,27 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing the metadata. + /// Gets a collection containing the metadata. /// - public virtual ICollection CompanyMetadata { get; protected set; } + public virtual ICollection CompanyMetadata { get; private set; } /// - /// Gets or sets a collection containing this company's child companies. + /// Gets a collection containing this company's child companies. /// - public virtual ICollection ChildCompanies { get; protected set; } + public virtual ICollection ChildCompanies { get; private set; } /// public ICollection Companies => ChildCompanies; diff --git a/Jellyfin.Data/Entities/Libraries/CustomItem.cs b/Jellyfin.Data/Entities/Libraries/CustomItem.cs index 88d1a0c258..e27d01d860 100644 --- a/Jellyfin.Data/Entities/Libraries/CustomItem.cs +++ b/Jellyfin.Data/Entities/Libraries/CustomItem.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -21,11 +19,11 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets a collection containing the metadata for this item. + /// Gets a collection containing the metadata for this item. /// - public virtual ICollection CustomItemMetadata { get; protected set; } + public virtual ICollection CustomItemMetadata { get; private set; } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Episode.cs b/Jellyfin.Data/Entities/Libraries/Episode.cs index 458c7d9f5a..ce2f0c6178 100644 --- a/Jellyfin.Data/Entities/Libraries/Episode.cs +++ b/Jellyfin.Data/Entities/Libraries/Episode.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -26,11 +24,11 @@ namespace Jellyfin.Data.Entities.Libraries public int? EpisodeNumber { get; set; } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } /// - /// Gets or sets a collection containing the metadata for this episode. + /// Gets a collection containing the metadata for this episode. /// - public virtual ICollection EpisodeMetadata { get; protected set; } + public virtual ICollection EpisodeMetadata { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Genre.cs b/Jellyfin.Data/Entities/Libraries/Genre.cs index 9f3d650283..3b822ee828 100644 --- a/Jellyfin.Data/Entities/Libraries/Genre.cs +++ b/Jellyfin.Data/Entities/Libraries/Genre.cs @@ -19,13 +19,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -39,7 +39,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; protected set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs index d12e011a8b..d429a90c61 100644 --- a/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/ItemMetadata.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -43,13 +41,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the title. @@ -99,12 +97,12 @@ namespace Jellyfin.Data.Entities.Libraries public DateTimeOffset? ReleaseDate { get; set; } /// - /// Gets or sets the date added. + /// Gets the date added. /// /// /// Required. /// - public DateTime DateAdded { get; protected set; } + public DateTime DateAdded { get; private set; } /// /// Gets or sets the date modified. @@ -114,37 +112,32 @@ namespace Jellyfin.Data.Entities.Libraries /// public DateTime DateModified { get; set; } - /// - /// Gets or sets the row version. - /// - /// - /// Required, ConcurrencyToken. - /// + /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing the person roles for this item. + /// Gets a collection containing the person roles for this item. /// - public virtual ICollection PersonRoles { get; protected set; } + public virtual ICollection PersonRoles { get; private set; } /// - /// Gets or sets a collection containing the genres for this item. + /// Gets a collection containing the genres for this item. /// - public virtual ICollection Genres { get; protected set; } + public virtual ICollection Genres { get; private set; } /// - public virtual ICollection Artwork { get; protected set; } + public virtual ICollection Artwork { get; private set; } /// - /// Gets or sets a collection containing the ratings for this item. + /// Gets a collection containing the ratings for this item. /// - public virtual ICollection Ratings { get; protected set; } + public virtual ICollection Ratings { get; private set; } /// - /// Gets or sets a collection containing the metadata sources for this item. + /// Gets a collection containing the metadata sources for this item. /// - public virtual ICollection Sources { get; protected set; } + public virtual ICollection Sources { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Library.cs b/Jellyfin.Data/Entities/Libraries/Library.cs index e453849020..0db42a1c7b 100644 --- a/Jellyfin.Data/Entities/Libraries/Library.cs +++ b/Jellyfin.Data/Entities/Libraries/Library.cs @@ -21,13 +21,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -49,7 +49,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs index 67ffad944b..d889b871ed 100644 --- a/Jellyfin.Data/Entities/Libraries/LibraryItem.cs +++ b/Jellyfin.Data/Entities/Libraries/LibraryItem.cs @@ -21,22 +21,22 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// - /// Gets or sets the date this library item was added. + /// Gets the date this library item was added. /// - public DateTime DateAdded { get; protected set; } + public DateTime DateAdded { get; private set; } /// [ConcurrencyCheck] - public uint RowVersion { get; protected set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the library of this item. diff --git a/Jellyfin.Data/Entities/Libraries/MediaFile.cs b/Jellyfin.Data/Entities/Libraries/MediaFile.cs index f3e2fe6539..36e1e47776 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFile.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFile.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -33,13 +31,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the path relative to the library root. @@ -61,12 +59,12 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing the streams in this file. + /// Gets a collection containing the streams in this file. /// - public virtual ICollection MediaFileStreams { get; protected set; } + public virtual ICollection MediaFileStreams { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs index ba21294fc9..e24e73ecb7 100644 --- a/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs +++ b/Jellyfin.Data/Entities/Libraries/MediaFileStream.cs @@ -21,13 +21,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the stream number. @@ -39,7 +39,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs index fb2587882d..b271960787 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProvider.cs @@ -25,13 +25,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -45,7 +45,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs index 2a9c904c88..44c1985181 100644 --- a/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs +++ b/Jellyfin.Data/Entities/Libraries/MetadataProviderId.cs @@ -27,13 +27,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the provider id. @@ -47,7 +47,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the metadata provider. diff --git a/Jellyfin.Data/Entities/Libraries/Movie.cs b/Jellyfin.Data/Entities/Libraries/Movie.cs index f89cacff44..499fafd0e1 100644 --- a/Jellyfin.Data/Entities/Libraries/Movie.cs +++ b/Jellyfin.Data/Entities/Libraries/Movie.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -21,11 +19,11 @@ namespace Jellyfin.Data.Entities.Libraries } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } /// - /// Gets or sets a collection containing the metadata for this movie. + /// Gets a collection containing the metadata for this movie. /// - public virtual ICollection MovieMetadata { get; protected set; } + public virtual ICollection MovieMetadata { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs index fb181dea60..44b5f34d7f 100644 --- a/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MovieMetadata.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Jellyfin.Data.Interfaces; @@ -62,9 +60,9 @@ namespace Jellyfin.Data.Entities.Libraries public string? Country { get; set; } /// - /// Gets or sets the studios that produced this movie. + /// Gets the studios that produced this movie. /// - public virtual ICollection Studios { get; protected set; } + public virtual ICollection Studios { get; private set; } /// public ICollection Companies => Studios; diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs index 4049cdac8e..d6231bbf02 100644 --- a/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs +++ b/Jellyfin.Data/Entities/Libraries/MusicAlbum.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; namespace Jellyfin.Data.Entities.Libraries @@ -20,13 +18,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets a collection containing the album metadata. + /// Gets a collection containing the album metadata. /// - public virtual ICollection MusicAlbumMetadata { get; protected set; } + public virtual ICollection MusicAlbumMetadata { get; private set; } /// - /// Gets or sets a collection containing the tracks. + /// Gets a collection containing the tracks. /// - public virtual ICollection Tracks { get; protected set; } + public virtual ICollection Tracks { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs index 3080bd692d..691f3504fa 100644 --- a/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/MusicAlbumMetadata.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -51,8 +49,8 @@ namespace Jellyfin.Data.Entities.Libraries public string? Country { get; set; } /// - /// Gets or sets a collection containing the labels. + /// Gets a collection containing the labels. /// - public virtual ICollection Labels { get; protected set; } + public virtual ICollection Labels { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Person.cs b/Jellyfin.Data/Entities/Libraries/Person.cs index 159bd47be7..8b67d920d2 100644 --- a/Jellyfin.Data/Entities/Libraries/Person.cs +++ b/Jellyfin.Data/Entities/Libraries/Person.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -32,13 +30,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -61,12 +59,12 @@ namespace Jellyfin.Data.Entities.Libraries public string? SourceId { get; set; } /// - /// Gets or sets the date added. + /// Gets the date added. /// /// /// Required. /// - public DateTime DateAdded { get; protected set; } + public DateTime DateAdded { get; private set; } /// /// Gets or sets the date modified. @@ -78,12 +76,12 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a list of metadata sources for this person. + /// Gets a list of metadata sources for this person. /// - public virtual ICollection Sources { get; protected set; } + public virtual ICollection Sources { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/PersonRole.cs b/Jellyfin.Data/Entities/Libraries/PersonRole.cs index 988aa84bae..7d40bdf448 100644 --- a/Jellyfin.Data/Entities/Libraries/PersonRole.cs +++ b/Jellyfin.Data/Entities/Libraries/PersonRole.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -27,13 +25,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name of the person's role. @@ -55,7 +53,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; protected set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the person. @@ -66,12 +64,12 @@ namespace Jellyfin.Data.Entities.Libraries public virtual Person Person { get; set; } /// - public virtual ICollection Artwork { get; protected set; } + public virtual ICollection Artwork { get; private set; } /// - /// Gets or sets a collection containing the metadata sources for this person role. + /// Gets a collection containing the metadata sources for this person role. /// - public virtual ICollection Sources { get; protected set; } + public virtual ICollection Sources { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Photo.cs b/Jellyfin.Data/Entities/Libraries/Photo.cs index eb5c962675..4b459432bc 100644 --- a/Jellyfin.Data/Entities/Libraries/Photo.cs +++ b/Jellyfin.Data/Entities/Libraries/Photo.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -21,11 +19,11 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets a collection containing the photo metadata. + /// Gets a collection containing the photo metadata. /// - public virtual ICollection PhotoMetadata { get; protected set; } + public virtual ICollection PhotoMetadata { get; private set; } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Rating.cs b/Jellyfin.Data/Entities/Libraries/Rating.cs index 6862012a80..58c8fa49ef 100644 --- a/Jellyfin.Data/Entities/Libraries/Rating.cs +++ b/Jellyfin.Data/Entities/Libraries/Rating.cs @@ -19,13 +19,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the value. @@ -42,7 +42,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the rating type. diff --git a/Jellyfin.Data/Entities/Libraries/RatingSource.cs b/Jellyfin.Data/Entities/Libraries/RatingSource.cs index ae0d806ff0..0f3a073244 100644 --- a/Jellyfin.Data/Entities/Libraries/RatingSource.cs +++ b/Jellyfin.Data/Entities/Libraries/RatingSource.cs @@ -21,13 +21,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -57,7 +57,7 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// /// Gets or sets the metadata source. diff --git a/Jellyfin.Data/Entities/Libraries/Release.cs b/Jellyfin.Data/Entities/Libraries/Release.cs index 21d4039793..d3d52bf5cd 100644 --- a/Jellyfin.Data/Entities/Libraries/Release.cs +++ b/Jellyfin.Data/Entities/Libraries/Release.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -31,13 +29,13 @@ namespace Jellyfin.Data.Entities.Libraries } /// - /// Gets or sets the id. + /// Gets the id. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// /// Gets or sets the name. @@ -51,17 +49,17 @@ namespace Jellyfin.Data.Entities.Libraries /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets a collection containing the media files for this release. + /// Gets a collection containing the media files for this release. /// - public virtual ICollection MediaFiles { get; protected set; } + public virtual ICollection MediaFiles { get; private set; } /// - /// Gets or sets a collection containing the chapters for this release. + /// Gets a collection containing the chapters for this release. /// - public virtual ICollection Chapters { get; protected set; } + public virtual ICollection Chapters { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Libraries/Season.cs b/Jellyfin.Data/Entities/Libraries/Season.cs index 04f723a1d1..fc110b49da 100644 --- a/Jellyfin.Data/Entities/Libraries/Season.cs +++ b/Jellyfin.Data/Entities/Libraries/Season.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; namespace Jellyfin.Data.Entities.Libraries @@ -25,13 +23,13 @@ namespace Jellyfin.Data.Entities.Libraries public int? SeasonNumber { get; set; } /// - /// Gets or sets the season metadata. + /// Gets the season metadata. /// - public virtual ICollection SeasonMetadata { get; protected set; } + public virtual ICollection SeasonMetadata { get; private set; } /// - /// Gets or sets a collection containing the number of episodes. + /// Gets a collection containing the number of episodes. /// - public virtual ICollection Episodes { get; protected set; } + public virtual ICollection Episodes { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/Series.cs b/Jellyfin.Data/Entities/Libraries/Series.cs index 59508831e4..0354433e08 100644 --- a/Jellyfin.Data/Entities/Libraries/Series.cs +++ b/Jellyfin.Data/Entities/Libraries/Series.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; @@ -16,7 +14,6 @@ namespace Jellyfin.Data.Entities.Libraries /// The library. public Series(Library library) : base(library) { - DateAdded = DateTime.UtcNow; Seasons = new HashSet(); SeriesMetadata = new HashSet(); } @@ -37,13 +34,13 @@ namespace Jellyfin.Data.Entities.Libraries public DateTime? FirstAired { get; set; } /// - /// Gets or sets a collection containing the series metadata. + /// Gets a collection containing the series metadata. /// - public virtual ICollection SeriesMetadata { get; protected set; } + public virtual ICollection SeriesMetadata { get; private set; } /// - /// Gets or sets a collection containing the seasons. + /// Gets a collection containing the seasons. /// - public virtual ICollection Seasons { get; protected set; } + public virtual ICollection Seasons { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs index 730deccaed..b75b0a25be 100644 --- a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; @@ -63,9 +61,9 @@ namespace Jellyfin.Data.Entities.Libraries public string? Country { get; set; } /// - /// Gets or sets a collection containing the networks. + /// Gets a collection containing the networks. /// - public virtual ICollection Networks { get; protected set; } + public virtual ICollection Networks { get; private set; } /// public ICollection Companies => Networks; diff --git a/Jellyfin.Data/Entities/Libraries/Track.cs b/Jellyfin.Data/Entities/Libraries/Track.cs index 86a3edff83..d354000337 100644 --- a/Jellyfin.Data/Entities/Libraries/Track.cs +++ b/Jellyfin.Data/Entities/Libraries/Track.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System.Collections.Generic; using Jellyfin.Data.Interfaces; @@ -26,11 +24,11 @@ namespace Jellyfin.Data.Entities.Libraries public int? TrackNumber { get; set; } /// - public virtual ICollection Releases { get; protected set; } + public virtual ICollection Releases { get; private set; } /// - /// Gets or sets a collection containing the track metadata. + /// Gets a collection containing the track metadata. /// - public virtual ICollection TrackMetadata { get; protected set; } + public virtual ICollection TrackMetadata { get; private set; } } } diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs index f059dedfa2..005d1a10f2 100644 --- a/Jellyfin.Data/Entities/Permission.cs +++ b/Jellyfin.Data/Entities/Permission.cs @@ -25,21 +25,21 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the id of this permission. + /// Gets the id of this permission. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// - /// Gets or sets the type of this permission. + /// Gets the type of this permission. /// /// /// Required. /// - public PermissionKind Kind { get; protected set; } + public PermissionKind Kind { get; private set; } /// /// Gets or sets a value indicating whether the associated user has this permission. @@ -51,7 +51,7 @@ namespace Jellyfin.Data.Entities /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs index a8813ab88d..048caeceef 100644 --- a/Jellyfin.Data/Entities/Preference.cs +++ b/Jellyfin.Data/Entities/Preference.cs @@ -24,21 +24,21 @@ namespace Jellyfin.Data.Entities } /// - /// Gets or sets the id of this preference. + /// Gets the id of this preference. /// /// /// Identity, Indexed, Required. /// [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; protected set; } + public int Id { get; private set; } /// - /// Gets or sets the type of this preference. + /// Gets the type of this preference. /// /// /// Required. /// - public PreferenceKind Kind { get; protected set; } + public PreferenceKind Kind { get; private set; } /// /// Gets or sets the value of this preference. @@ -52,7 +52,7 @@ namespace Jellyfin.Data.Entities /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// public void OnSavingChanges() diff --git a/Jellyfin.Data/Entities/User.cs b/Jellyfin.Data/Entities/User.cs index 74331726cc..e309e54de9 100644 --- a/Jellyfin.Data/Entities/User.cs +++ b/Jellyfin.Data/Entities/User.cs @@ -1,5 +1,3 @@ -#pragma warning disable CA2227 - using System; using System.Collections.Generic; using System.ComponentModel; @@ -302,64 +300,54 @@ namespace Jellyfin.Data.Entities public virtual ImageInfo? ProfileImage { get; set; } /// - /// Gets or sets the user's display preferences. + /// Gets the user's display preferences. /// - /// - /// Required. - /// - public virtual ICollection DisplayPreferences { get; set; } + public virtual ICollection DisplayPreferences { get; private set; } /// /// Gets or sets the level of sync play permissions this user has. /// public SyncPlayUserAccessType SyncPlayAccess { get; set; } - /// - /// Gets or sets the row version. - /// - /// - /// Required, Concurrency Token. - /// + /// [ConcurrencyCheck] - public uint RowVersion { get; set; } + public uint RowVersion { get; private set; } /// - /// Gets or sets the list of access schedules this user has. + /// Gets the list of access schedules this user has. /// - public virtual ICollection AccessSchedules { get; protected set; } + public virtual ICollection AccessSchedules { get; private set; } /// - /// Gets or sets the list of item display preferences. + /// Gets the list of item display preferences. /// - public virtual ICollection ItemDisplayPreferences { get; protected set; } + public virtual ICollection ItemDisplayPreferences { get; private set; } /* /// - /// Gets or sets the list of groups this user is a member of. + /// Gets the list of groups this user is a member of. /// - [ForeignKey("Group_Groups_Guid")] - public virtual ICollection Groups { get; protected set; } + public virtual ICollection Groups { get; private set; } */ /// - /// Gets or sets the list of permissions this user has. + /// Gets the list of permissions this user has. /// [ForeignKey("Permission_Permissions_Guid")] - public virtual ICollection Permissions { get; protected set; } + public virtual ICollection Permissions { get; private set; } /* /// - /// Gets or sets the list of provider mappings this user has. + /// Gets the list of provider mappings this user has. /// - [ForeignKey("ProviderMapping_ProviderMappings_Id")] - public virtual ICollection ProviderMappings { get; protected set; } + public virtual ICollection ProviderMappings { get; private set; } */ /// - /// Gets or sets the list of preferences this user has. + /// Gets the list of preferences this user has. /// [ForeignKey("Preference_Preferences_Guid")] - public virtual ICollection Preferences { get; protected set; } + public virtual ICollection Preferences { get; private set; } /// public void OnSavingChanges() From 3ffef5794ea6ddda565d89a58667980f1c3bddc3 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Wed, 17 Mar 2021 19:21:03 -0400 Subject: [PATCH 1347/1930] Delete unnecessary indexes Multicolumn indexes can be queried on the first column without needing a separate index --- Jellyfin.Server.Implementations/JellyfinDb.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 39f842354f..eda2fa65c3 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -149,18 +149,10 @@ namespace Jellyfin.Server.Implementations modelBuilder.HasDefaultSchema("jellyfin"); - modelBuilder.Entity() - .HasIndex(entity => entity.UserId) - .IsUnique(false); - modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client }) .IsUnique(); - modelBuilder.Entity() - .HasIndex(entity => entity.UserId) - .IsUnique(false); - modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client, entity.Key }) .IsUnique(); From 0a579e5bbd3c36e15d322ee5d30c8ef3331863bf Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Wed, 17 Mar 2021 21:41:52 -0400 Subject: [PATCH 1348/1930] Configure user deletion behavior --- Jellyfin.Server.Implementations/JellyfinDb.cs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index eda2fa65c3..88ed22086e 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -149,6 +149,31 @@ namespace Jellyfin.Server.Implementations modelBuilder.HasDefaultSchema("jellyfin"); + modelBuilder.Entity() + .HasOne(u => u.ProfileImage) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasMany(u => u.Permissions) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasMany(u => u.Preferences) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasMany(u => u.AccessSchedules) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasMany(u => u.DisplayPreferences) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client }) .IsUnique(); From f1cadb27d9d6ddbb2d42777e4c546a73bd5bcfe3 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 18 Mar 2021 15:37:36 -0400 Subject: [PATCH 1349/1930] Add id properties for preferences and permissions --- Jellyfin.Data/Entities/Permission.cs | 6 ++++++ Jellyfin.Data/Entities/Preference.cs | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs index 005d1a10f2..2c58943181 100644 --- a/Jellyfin.Data/Entities/Permission.cs +++ b/Jellyfin.Data/Entities/Permission.cs @@ -1,5 +1,6 @@ #pragma warning disable CA1711 // Identifiers should not have incorrect suffix +using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Enums; @@ -33,6 +34,11 @@ namespace Jellyfin.Data.Entities [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; private set; } + /// + /// Gets or sets the id of the associated user. + /// + public Guid UserId { get; set; } + /// /// Gets the type of this permission. /// diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs index 048caeceef..a7d93f32c6 100644 --- a/Jellyfin.Data/Entities/Preference.cs +++ b/Jellyfin.Data/Entities/Preference.cs @@ -32,6 +32,11 @@ namespace Jellyfin.Data.Entities [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; private set; } + /// + /// Gets or sets the id of the associated user. + /// + public Guid UserId { get; set; } + /// /// Gets the type of this preference. /// From 3c4187e7803afd1d95eac20b30d2063ca2134413 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 18 Mar 2021 20:09:11 -0400 Subject: [PATCH 1350/1930] Add indexes for user permissions and preferences --- Jellyfin.Server.Implementations/JellyfinDb.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 88ed22086e..a2eaea3cac 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -174,6 +174,7 @@ namespace Jellyfin.Server.Implementations .WithOne() .OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client }) .IsUnique(); @@ -181,6 +182,19 @@ namespace Jellyfin.Server.Implementations modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client, entity.Key }) .IsUnique(); + + // Used to get a user's permissions or a specific permission for a user. + // Also prevents multiple values being created for a user. + // Filtered over non-null user ids for when other entities (groups, API keys) get permissions + modelBuilder.Entity() + .HasIndex(p => new { p.UserId, p.Kind }) + .HasFilter("[UserId] IS NOT NULL") + .IsUnique(); + + modelBuilder.Entity() + .HasIndex(p => new { p.UserId, p.Kind }) + .HasFilter("[UserId] IS NOT NULL") + .IsUnique(); } } } From a07ad7122281247a48c1f8a48588f49c6f64f2c4 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 18 Mar 2021 20:24:37 -0400 Subject: [PATCH 1351/1930] Use NOCASE collation and index on username field --- Jellyfin.Server.Implementations/JellyfinDb.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index a2eaea3cac..2ee6f625f8 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -149,6 +149,14 @@ namespace Jellyfin.Server.Implementations modelBuilder.HasDefaultSchema("jellyfin"); + // Collations + + modelBuilder.Entity() + .Property(user => user.Username) + .UseCollation("NOCASE"); + + // Delete behavior + modelBuilder.Entity() .HasOne(u => u.ProfileImage) .WithOne() @@ -174,6 +182,11 @@ namespace Jellyfin.Server.Implementations .WithOne() .OnDelete(DeleteBehavior.Cascade); + // Indexes + + modelBuilder.Entity() + .HasIndex(entity => entity.Username) + .IsUnique(); modelBuilder.Entity() .HasIndex(entity => new { entity.UserId, entity.ItemId, entity.Client }) From ea0a9c2cca4fd0f6ff84f79420281a7738602e60 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Fri, 19 Mar 2021 00:26:00 -0400 Subject: [PATCH 1352/1930] Properly configure foreign keys --- Jellyfin.Server.Implementations/JellyfinDb.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 2ee6f625f8..499d99a502 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -165,11 +165,13 @@ namespace Jellyfin.Server.Implementations modelBuilder.Entity() .HasMany(u => u.Permissions) .WithOne() + .HasForeignKey(p => p.UserId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity() .HasMany(u => u.Preferences) .WithOne() + .HasForeignKey(p => p.UserId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity() From daa21c9e99a8b7b6e9a76c130f8e0943692bd1da Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Fri, 19 Mar 2021 00:26:07 -0400 Subject: [PATCH 1353/1930] Add migration --- Jellyfin.Data/Entities/Permission.cs | 2 +- Jellyfin.Data/Entities/Preference.cs | 2 +- Jellyfin.Server.Implementations/JellyfinDb.cs | 10 + ...181425_AddIndexesAndCollations.Designer.cs | 535 ++++++++++++++++++ .../20210320181425_AddIndexesAndCollations.cs | 240 ++++++++ .../Migrations/JellyfinDbModelSnapshot.cs | 42 +- 6 files changed, 814 insertions(+), 17 deletions(-) create mode 100644 Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs create mode 100644 Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs diff --git a/Jellyfin.Data/Entities/Permission.cs b/Jellyfin.Data/Entities/Permission.cs index 2c58943181..6d2e68077c 100644 --- a/Jellyfin.Data/Entities/Permission.cs +++ b/Jellyfin.Data/Entities/Permission.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Data.Entities /// /// Gets or sets the id of the associated user. /// - public Guid UserId { get; set; } + public Guid? UserId { get; set; } /// /// Gets the type of this permission. diff --git a/Jellyfin.Data/Entities/Preference.cs b/Jellyfin.Data/Entities/Preference.cs index a7d93f32c6..a6ab275d31 100644 --- a/Jellyfin.Data/Entities/Preference.cs +++ b/Jellyfin.Data/Entities/Preference.cs @@ -35,7 +35,7 @@ namespace Jellyfin.Data.Entities /// /// Gets or sets the id of the associated user. /// - public Guid UserId { get; set; } + public Guid? UserId { get; set; } /// /// Gets the type of this preference. diff --git a/Jellyfin.Server.Implementations/JellyfinDb.cs b/Jellyfin.Server.Implementations/JellyfinDb.cs index 499d99a502..db648472d1 100644 --- a/Jellyfin.Server.Implementations/JellyfinDb.cs +++ b/Jellyfin.Server.Implementations/JellyfinDb.cs @@ -184,6 +184,16 @@ namespace Jellyfin.Server.Implementations .WithOne() .OnDelete(DeleteBehavior.Cascade); + modelBuilder.Entity() + .HasMany(u => u.ItemDisplayPreferences) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + + modelBuilder.Entity() + .HasMany(d => d.HomeSections) + .WithOne() + .OnDelete(DeleteBehavior.Cascade); + // Indexes modelBuilder.Entity() diff --git a/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs new file mode 100644 index 0000000000..8696768245 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.Designer.cs @@ -0,0 +1,535 @@ +#pragma warning disable CS1591 + +// +using System; +using Jellyfin.Server.Implementations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Jellyfin.Server.Implementations.Migrations +{ + [DbContext(typeof(JellyfinDb))] + [Migration("20210320181425_AddIndexesAndCollations")] + partial class AddIndexesAndCollations + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("jellyfin") + .HasAnnotation("ProductVersion", "5.0.3"); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DayOfWeek") + .HasColumnType("INTEGER"); + + b.Property("EndHour") + .HasColumnType("REAL"); + + b.Property("StartHour") + .HasColumnType("REAL"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AccessSchedules"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("ItemId") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("LogSeverity") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Overview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("ShortOverview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ActivityLogs"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.CustomItemDisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("Key") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "ItemId", "Client", "Key") + .IsUnique(); + + b.ToTable("CustomItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ChromecastVersion") + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("DashboardTheme") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("EnableNextVideoInfoOverlay") + .HasColumnType("INTEGER"); + + b.Property("IndexBy") + .HasColumnType("INTEGER"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("ScrollDirection") + .HasColumnType("INTEGER"); + + b.Property("ShowBackdrop") + .HasColumnType("INTEGER"); + + b.Property("ShowSidebar") + .HasColumnType("INTEGER"); + + b.Property("SkipBackwardLength") + .HasColumnType("INTEGER"); + + b.Property("SkipForwardLength") + .HasColumnType("INTEGER"); + + b.Property("TvHome") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "ItemId", "Client") + .IsUnique(); + + b.ToTable("DisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DisplayPreferencesId") + .HasColumnType("INTEGER"); + + b.Property("Order") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DisplayPreferencesId"); + + b.ToTable("HomeSection"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ImageInfos"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("IndexBy") + .HasColumnType("INTEGER"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("RememberIndexing") + .HasColumnType("INTEGER"); + + b.Property("RememberSorting") + .HasColumnType("INTEGER"); + + b.Property("SortBy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SortOrder") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("ViewType") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("ItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Kind") + .HasColumnType("INTEGER"); + + b.Property("Permission_Permissions_Guid") + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Kind") + .IsUnique() + .HasFilter("[UserId] IS NOT NULL"); + + b.ToTable("Permissions"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Kind") + .HasColumnType("INTEGER"); + + b.Property("Preference_Preferences_Guid") + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Kind") + .IsUnique() + .HasFilter("[UserId] IS NOT NULL"); + + b.ToTable("Preferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AudioLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("AuthenticationProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("DisplayCollectionsView") + .HasColumnType("INTEGER"); + + b.Property("DisplayMissingEpisodes") + .HasColumnType("INTEGER"); + + b.Property("EasyPassword") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property("EnableAutoLogin") + .HasColumnType("INTEGER"); + + b.Property("EnableLocalPassword") + .HasColumnType("INTEGER"); + + b.Property("EnableNextEpisodeAutoPlay") + .HasColumnType("INTEGER"); + + b.Property("EnableUserPreferenceAccess") + .HasColumnType("INTEGER"); + + b.Property("HidePlayedInLatest") + .HasColumnType("INTEGER"); + + b.Property("InternalId") + .HasColumnType("INTEGER"); + + b.Property("InvalidLoginAttemptCount") + .HasColumnType("INTEGER"); + + b.Property("LastActivityDate") + .HasColumnType("TEXT"); + + b.Property("LastLoginDate") + .HasColumnType("TEXT"); + + b.Property("LoginAttemptsBeforeLockout") + .HasColumnType("INTEGER"); + + b.Property("MaxActiveSessions") + .HasColumnType("INTEGER"); + + b.Property("MaxParentalAgeRating") + .HasColumnType("INTEGER"); + + b.Property("MustUpdatePassword") + .HasColumnType("INTEGER"); + + b.Property("Password") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property("PasswordResetProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PlayDefaultAudioTrack") + .HasColumnType("INTEGER"); + + b.Property("RememberAudioSelections") + .HasColumnType("INTEGER"); + + b.Property("RememberSubtitleSelections") + .HasColumnType("INTEGER"); + + b.Property("RemoteClientBitrateLimit") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("SubtitleLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("SubtitleMode") + .HasColumnType("INTEGER"); + + b.Property("SyncPlayAccess") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .UseCollation("NOCASE"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("AccessSchedules") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("DisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null) + .WithMany("HomeSections") + .HasForeignKey("DisplayPreferencesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithOne("ProfileImage") + .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId") + .OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("ItemDisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Permissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Preferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Navigation("HomeSections"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Navigation("AccessSchedules"); + + b.Navigation("DisplayPreferences"); + + b.Navigation("ItemDisplayPreferences"); + + b.Navigation("Permissions"); + + b.Navigation("Preferences"); + + b.Navigation("ProfileImage"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs new file mode 100644 index 0000000000..506e4ae661 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20210320181425_AddIndexesAndCollations.cs @@ -0,0 +1,240 @@ +#pragma warning disable CS1591 +#pragma warning disable SA1601 + +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Jellyfin.Server.Implementations.Migrations +{ + public partial class AddIndexesAndCollations : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ImageInfos_Users_UserId", + schema: "jellyfin", + table: "ImageInfos"); + + migrationBuilder.DropForeignKey( + name: "FK_Permissions_Users_Permission_Permissions_Guid", + schema: "jellyfin", + table: "Permissions"); + + migrationBuilder.DropForeignKey( + name: "FK_Preferences_Users_Preference_Preferences_Guid", + schema: "jellyfin", + table: "Preferences"); + + migrationBuilder.DropIndex( + name: "IX_Preferences_Preference_Preferences_Guid", + schema: "jellyfin", + table: "Preferences"); + + migrationBuilder.DropIndex( + name: "IX_Permissions_Permission_Permissions_Guid", + schema: "jellyfin", + table: "Permissions"); + + migrationBuilder.DropIndex( + name: "IX_DisplayPreferences_UserId", + schema: "jellyfin", + table: "DisplayPreferences"); + + migrationBuilder.DropIndex( + name: "IX_CustomItemDisplayPreferences_UserId", + schema: "jellyfin", + table: "CustomItemDisplayPreferences"); + + migrationBuilder.AlterColumn( + name: "Username", + schema: "jellyfin", + table: "Users", + type: "TEXT", + maxLength: 255, + nullable: false, + collation: "NOCASE", + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 255); + + migrationBuilder.AddColumn( + name: "UserId", + schema: "jellyfin", + table: "Preferences", + type: "TEXT", + nullable: true); + + migrationBuilder.AddColumn( + name: "UserId", + schema: "jellyfin", + table: "Permissions", + type: "TEXT", + nullable: true); + + migrationBuilder.Sql("UPDATE Preferences SET UserId = Preference_Preferences_Guid"); + migrationBuilder.Sql("UPDATE Permissions SET UserId = Permission_Permissions_Guid"); + + migrationBuilder.CreateIndex( + name: "IX_Users_Username", + schema: "jellyfin", + table: "Users", + column: "Username", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_Preferences_UserId_Kind", + schema: "jellyfin", + table: "Preferences", + columns: new[] { "UserId", "Kind" }, + unique: true, + filter: "[UserId] IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_Permissions_UserId_Kind", + schema: "jellyfin", + table: "Permissions", + columns: new[] { "UserId", "Kind" }, + unique: true, + filter: "[UserId] IS NOT NULL"); + + migrationBuilder.AddForeignKey( + name: "FK_ImageInfos_Users_UserId", + schema: "jellyfin", + table: "ImageInfos", + column: "UserId", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_Permissions_Users_UserId", + schema: "jellyfin", + table: "Permissions", + column: "UserId", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + + migrationBuilder.AddForeignKey( + name: "FK_Preferences_Users_UserId", + schema: "jellyfin", + table: "Preferences", + column: "UserId", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_ImageInfos_Users_UserId", + schema: "jellyfin", + table: "ImageInfos"); + + migrationBuilder.DropForeignKey( + name: "FK_Permissions_Users_UserId", + schema: "jellyfin", + table: "Permissions"); + + migrationBuilder.DropForeignKey( + name: "FK_Preferences_Users_UserId", + schema: "jellyfin", + table: "Preferences"); + + migrationBuilder.DropIndex( + name: "IX_Users_Username", + schema: "jellyfin", + table: "Users"); + + migrationBuilder.DropIndex( + name: "IX_Preferences_UserId_Kind", + schema: "jellyfin", + table: "Preferences"); + + migrationBuilder.DropIndex( + name: "IX_Permissions_UserId_Kind", + schema: "jellyfin", + table: "Permissions"); + + migrationBuilder.DropColumn( + name: "UserId", + schema: "jellyfin", + table: "Preferences"); + + migrationBuilder.DropColumn( + name: "UserId", + schema: "jellyfin", + table: "Permissions"); + + migrationBuilder.AlterColumn( + name: "Username", + schema: "jellyfin", + table: "Users", + type: "TEXT", + maxLength: 255, + nullable: false, + oldClrType: typeof(string), + oldType: "TEXT", + oldMaxLength: 255, + oldCollation: "NOCASE"); + + migrationBuilder.CreateIndex( + name: "IX_Preferences_Preference_Preferences_Guid", + schema: "jellyfin", + table: "Preferences", + column: "Preference_Preferences_Guid"); + + migrationBuilder.CreateIndex( + name: "IX_Permissions_Permission_Permissions_Guid", + schema: "jellyfin", + table: "Permissions", + column: "Permission_Permissions_Guid"); + + migrationBuilder.CreateIndex( + name: "IX_DisplayPreferences_UserId", + schema: "jellyfin", + table: "DisplayPreferences", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_CustomItemDisplayPreferences_UserId", + schema: "jellyfin", + table: "CustomItemDisplayPreferences", + column: "UserId"); + + migrationBuilder.AddForeignKey( + name: "FK_ImageInfos_Users_UserId", + schema: "jellyfin", + table: "ImageInfos", + column: "UserId", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Permissions_Users_Permission_Permissions_Guid", + schema: "jellyfin", + table: "Permissions", + column: "Permission_Permissions_Guid", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + + migrationBuilder.AddForeignKey( + name: "FK_Preferences_Users_Preference_Preferences_Guid", + schema: "jellyfin", + table: "Preferences", + column: "Preference_Preferences_Guid", + principalSchema: "jellyfin", + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs index 1614a88efb..d8e13ba0c6 100644 --- a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs +++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Migrations #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("jellyfin") - .HasAnnotation("ProductVersion", "5.0.0"); + .HasAnnotation("ProductVersion", "5.0.3"); modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => { @@ -115,8 +115,6 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasKey("Id"); - b.HasIndex("UserId"); - b.HasIndex("UserId", "ItemId", "Client", "Key") .IsUnique(); @@ -174,8 +172,6 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasKey("Id"); - b.HasIndex("UserId"); - b.HasIndex("UserId", "ItemId", "Client") .IsUnique(); @@ -289,12 +285,17 @@ namespace Jellyfin.Server.Implementations.Migrations .IsConcurrencyToken() .HasColumnType("INTEGER"); + b.Property("UserId") + .HasColumnType("TEXT"); + b.Property("Value") .HasColumnType("INTEGER"); b.HasKey("Id"); - b.HasIndex("Permission_Permissions_Guid"); + b.HasIndex("UserId", "Kind") + .IsUnique() + .HasFilter("[UserId] IS NOT NULL"); b.ToTable("Permissions"); }); @@ -315,6 +316,9 @@ namespace Jellyfin.Server.Implementations.Migrations .IsConcurrencyToken() .HasColumnType("INTEGER"); + b.Property("UserId") + .HasColumnType("TEXT"); + b.Property("Value") .IsRequired() .HasMaxLength(65535) @@ -322,7 +326,9 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasKey("Id"); - b.HasIndex("Preference_Preferences_Guid"); + b.HasIndex("UserId", "Kind") + .IsUnique() + .HasFilter("[UserId] IS NOT NULL"); b.ToTable("Preferences"); }); @@ -429,10 +435,14 @@ namespace Jellyfin.Server.Implementations.Migrations b.Property("Username") .IsRequired() .HasMaxLength(255) - .HasColumnType("TEXT"); + .HasColumnType("TEXT") + .UseCollation("NOCASE"); b.HasKey("Id"); + b.HasIndex("Username") + .IsUnique(); + b.ToTable("Users"); }); @@ -448,8 +458,8 @@ namespace Jellyfin.Server.Implementations.Migrations modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => { b.HasOne("Jellyfin.Data.Entities.User", null) - .WithOne("DisplayPreferences") - .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId") + .WithMany("DisplayPreferences") + .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); @@ -467,7 +477,8 @@ namespace Jellyfin.Server.Implementations.Migrations { b.HasOne("Jellyfin.Data.Entities.User", null) .WithOne("ProfileImage") - .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId"); + .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId") + .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => @@ -483,14 +494,16 @@ namespace Jellyfin.Server.Implementations.Migrations { b.HasOne("Jellyfin.Data.Entities.User", null) .WithMany("Permissions") - .HasForeignKey("Permission_Permissions_Guid"); + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => { b.HasOne("Jellyfin.Data.Entities.User", null) .WithMany("Preferences") - .HasForeignKey("Preference_Preferences_Guid"); + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => @@ -502,8 +515,7 @@ namespace Jellyfin.Server.Implementations.Migrations { b.Navigation("AccessSchedules"); - b.Navigation("DisplayPreferences") - .IsRequired(); + b.Navigation("DisplayPreferences"); b.Navigation("ItemDisplayPreferences"); From a7b29e2fe0bb08f4b8f37fa5aac7af66c7cb00e8 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 25 Mar 2021 19:48:30 -0400 Subject: [PATCH 1354/1930] Clean up user renaming --- Jellyfin.Server.Implementations/Users/UserManager.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index 50d7612f27..f9a1a8ee95 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -144,7 +144,13 @@ namespace Jellyfin.Server.Implementations.Users throw new ArgumentException("The new and old names must be different."); } - if (Users.Any(u => u.Id != user.Id && u.Username.Equals(newName, StringComparison.OrdinalIgnoreCase))) + await using var dbContext = _dbProvider.CreateContext(); + + if (await dbContext.Users + .AsQueryable() + .Where(u => u.Username == newName && u.Id != user.Id) + .AnyAsync() + .ConfigureAwait(false)) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, From 7364155579c52e5019cdcb71edc03546babe3fb3 Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 25 Mar 2021 19:49:52 -0400 Subject: [PATCH 1355/1930] Clean up user deletion --- Jellyfin.Server.Implementations/Users/UserManager.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/Jellyfin.Server.Implementations/Users/UserManager.cs b/Jellyfin.Server.Implementations/Users/UserManager.cs index f9a1a8ee95..b6b45e69b5 100644 --- a/Jellyfin.Server.Implementations/Users/UserManager.cs +++ b/Jellyfin.Server.Implementations/Users/UserManager.cs @@ -257,16 +257,6 @@ namespace Jellyfin.Server.Implementations.Users } await using var dbContext = _dbProvider.CreateContext(); - - // Clear all entities related to the user from the database. - if (user.ProfileImage != null) - { - dbContext.Remove(user.ProfileImage); - } - - dbContext.RemoveRange(user.Permissions); - dbContext.RemoveRange(user.Preferences); - dbContext.RemoveRange(user.AccessSchedules); dbContext.Users.Remove(user); await dbContext.SaveChangesAsync().ConfigureAwait(false); _users.Remove(userId); From 73fe9d3f696e5d144047e173553b1d1dba03c5d1 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 25 Mar 2021 18:06:25 -0600 Subject: [PATCH 1356/1930] Allow subtitle format to be set from query parameter. --- Jellyfin.Api/Controllers/SubtitleController.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 16a47f2d88..e260efc9aa 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -185,6 +185,7 @@ namespace Jellyfin.Api.Controllers /// The item id. /// The media source id. /// The subtitle stream index. + /// The (route) format of the returned subtitle. /// The format of the returned subtitle. /// Optional. The end position of the subtitle in ticks. /// Optional. Whether to copy the timestamps. @@ -192,19 +193,25 @@ namespace Jellyfin.Api.Controllers /// Optional. The start position of the subtitle in ticks. /// File returned. /// A with the subtitle file. - [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{format}")] + [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{routeFormat}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public async Task GetSubtitle( [FromRoute, Required] Guid itemId, [FromRoute, Required] string mediaSourceId, [FromRoute, Required] int index, - [FromRoute, Required] string format, + [FromRoute, Required] string routeFormat, + [FromQuery] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false, [FromQuery] long startPositionTicks = 0) { + if (string.IsNullOrEmpty(format)) + { + format = routeFormat; + } + if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase)) { format = "json"; @@ -255,13 +262,14 @@ namespace Jellyfin.Api.Controllers /// The media source id. /// The subtitle stream index. /// Optional. The start position of the subtitle in ticks. + /// The (route) format of the returned subtitle. /// The format of the returned subtitle. /// Optional. The end position of the subtitle in ticks. /// Optional. Whether to copy the timestamps. /// Optional. Whether to add a VTT time map. /// File returned. /// A with the subtitle file. - [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks}/Stream.{format}")] + [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks}/Stream.{routeFormat}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public Task GetSubtitleWithTicks( @@ -269,7 +277,8 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string mediaSourceId, [FromRoute, Required] int index, [FromRoute, Required] long startPositionTicks, - [FromRoute, Required] string format, + [FromRoute, Required] string routeFormat, + [FromQuery] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false) @@ -278,6 +287,7 @@ namespace Jellyfin.Api.Controllers itemId, mediaSourceId, index, + routeFormat, format, endPositionTicks, copyTimestamps, From e0ff51cf2af1d4b90e572ab3e012746748909ed8 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 25 Mar 2021 20:30:15 -0600 Subject: [PATCH 1357/1930] Mark query parameters as obsolete --- Jellyfin.Api/Controllers/SubtitleController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index e260efc9aa..a21d377acb 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -201,7 +201,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string mediaSourceId, [FromRoute, Required] int index, [FromRoute, Required] string routeFormat, - [FromQuery] string? format, + [FromQuery, ParameterObsolete] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false, @@ -278,7 +278,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] int index, [FromRoute, Required] long startPositionTicks, [FromRoute, Required] string routeFormat, - [FromQuery] string? format, + [FromQuery, ParameterObsolete] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false) From db2fbcef2b6398dc845b69affde0aef2cc432056 Mon Sep 17 00:00:00 2001 From: lmaonator Date: Fri, 26 Mar 2021 12:15:44 +0100 Subject: [PATCH 1358/1930] Fix stream selection having no effect when casting When casting to jellyfin-mpv-shim from jellyfin-web in the browser, jellyfin-web sends data about which version (for grouped items) and which streams the user selected in the browser to the "Sessions/{sessionId}/Playing" API endpoint. The API endpoint currently doesn't forward them to jellyfin-mpv-shim through the Play command, which results in the default streams being played instead of the browser selected ones. PlayRequest already has the properties and they are already sent to the cast client by SendPlayCommand when present. jellyfin-mpv-shim will already use them to select the wanted streams when it receives the Play command. All that's needed to make it work is to take the parameters and assign them to PlayRequest. --- Jellyfin.Api/Controllers/SessionController.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index e2269a2ce2..e178e3389a 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -153,6 +153,10 @@ namespace Jellyfin.Api.Controllers /// The type of play command to issue (PlayNow, PlayNext, PlayLast). Clients who have not yet implemented play next and play last may play now. /// The ids of the items to play, comma delimited. /// The starting position of the first item. + /// Optional. The media source id. + /// Optional. The index of the audio stream to play. + /// Optional. The index of the subtitle stream to play. + /// Optional. The start index. /// Instruction sent to session. /// A . [HttpPost("Sessions/{sessionId}/Playing")] @@ -162,13 +166,21 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string sessionId, [FromQuery, Required] PlayCommand playCommand, [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds, - [FromQuery] long? startPositionTicks) + [FromQuery] long? startPositionTicks, + [FromQuery] string mediaSourceId, + [FromQuery] int? audioStreamIndex, + [FromQuery] int? subtitleStreamIndex, + [FromQuery] int? startIndex) { var playRequest = new PlayRequest { ItemIds = itemIds, StartPositionTicks = startPositionTicks, - PlayCommand = playCommand + PlayCommand = playCommand, + MediaSourceId = mediaSourceId, + AudioStreamIndex = audioStreamIndex, + SubtitleStreamIndex = subtitleStreamIndex, + StartIndex = startIndex }; _sessionManager.SendPlayCommand( From 5b758c47119c0520ff543f7b8e812f67533ce4f2 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 26 Mar 2021 07:07:45 -0600 Subject: [PATCH 1359/1930] Mark query parameters as obsolete --- .../Controllers/SubtitleController.cs | 64 ++++++++++++------- 1 file changed, 41 insertions(+), 23 deletions(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index a21d377acb..7a44b26a4b 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -182,35 +182,42 @@ namespace Jellyfin.Api.Controllers /// /// Gets subtitles in a specified format. /// + /// The (route) item id. + /// The (route) media source id. + /// The (route) subtitle stream index. + /// The (route) format of the returned subtitle. /// The item id. /// The media source id. /// The subtitle stream index. - /// The (route) format of the returned subtitle. /// The format of the returned subtitle. /// Optional. The end position of the subtitle in ticks. /// Optional. Whether to copy the timestamps. /// Optional. Whether to add a VTT time map. - /// Optional. The start position of the subtitle in ticks. + /// The start position of the subtitle in ticks. /// File returned. /// A with the subtitle file. [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{routeFormat}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public async Task GetSubtitle( - [FromRoute, Required] Guid itemId, - [FromRoute, Required] string mediaSourceId, - [FromRoute, Required] int index, + [FromRoute, Required] Guid routeItemId, + [FromRoute, Required] string routeMediaSourceId, + [FromRoute, Required] int routeIndex, [FromRoute, Required] string routeFormat, + [FromQuery, ParameterObsolete] Guid? itemId, + [FromQuery, ParameterObsolete] string? mediaSourceId, + [FromQuery, ParameterObsolete] int? index, [FromQuery, ParameterObsolete] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false, [FromQuery] long startPositionTicks = 0) { - if (string.IsNullOrEmpty(format)) - { - format = routeFormat; - } + // Set parameters to route value if not provided via query. + itemId ??= routeItemId; + mediaSourceId ??= routeMediaSourceId; + index ??= routeIndex; + format ??= routeFormat; if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase)) { @@ -219,9 +226,9 @@ namespace Jellyfin.Api.Controllers if (string.IsNullOrEmpty(format)) { - var item = (Video)_libraryManager.GetItemById(itemId); + var item = (Video)_libraryManager.GetItemById(itemId.Value); - var idString = itemId.ToString("N", CultureInfo.InvariantCulture); + var idString = itemId.Value.ToString("N", CultureInfo.InvariantCulture); var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false) .First(i => string.Equals(i.Id, mediaSourceId ?? idString, StringComparison.Ordinal)); @@ -233,7 +240,7 @@ namespace Jellyfin.Api.Controllers if (string.Equals(format, "vtt", StringComparison.OrdinalIgnoreCase) && addVttTimeMap) { - await using Stream stream = await EncodeSubtitles(itemId, mediaSourceId, index, format, startPositionTicks, endPositionTicks, copyTimestamps).ConfigureAwait(false); + await using Stream stream = await EncodeSubtitles(itemId.Value, mediaSourceId, index.Value, format, startPositionTicks, endPositionTicks, copyTimestamps).ConfigureAwait(false); using var reader = new StreamReader(stream); var text = await reader.ReadToEndAsync().ConfigureAwait(false); @@ -245,9 +252,9 @@ namespace Jellyfin.Api.Controllers return File( await EncodeSubtitles( - itemId, + itemId.Value, mediaSourceId, - index, + index.Value, format, startPositionTicks, endPositionTicks, @@ -258,41 +265,52 @@ namespace Jellyfin.Api.Controllers /// /// Gets subtitles in a specified format. /// + /// The (route) item id. + /// The (route) media source id. + /// The (route) subtitle stream index. + /// The (route) start position of the subtitle in ticks. + /// The (route) format of the returned subtitle. /// The item id. /// The media source id. /// The subtitle stream index. - /// Optional. The start position of the subtitle in ticks. - /// The (route) format of the returned subtitle. + /// The start position of the subtitle in ticks. /// The format of the returned subtitle. /// Optional. The end position of the subtitle in ticks. /// Optional. Whether to copy the timestamps. /// Optional. Whether to add a VTT time map. /// File returned. /// A with the subtitle file. - [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks}/Stream.{routeFormat}")] + [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/{routeStartPositionTicks}/Stream.{routeFormat}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public Task GetSubtitleWithTicks( - [FromRoute, Required] Guid itemId, - [FromRoute, Required] string mediaSourceId, - [FromRoute, Required] int index, - [FromRoute, Required] long startPositionTicks, + [FromRoute, Required] Guid routeItemId, + [FromRoute, Required] string routeMediaSourceId, + [FromRoute, Required] int routeIndex, + [FromRoute, Required] long routeStartPositionTicks, [FromRoute, Required] string routeFormat, + [FromQuery, ParameterObsolete] Guid? itemId, + [FromQuery, ParameterObsolete] string? mediaSourceId, + [FromQuery, ParameterObsolete] int? index, + [FromQuery, ParameterObsolete] long? startPositionTicks, [FromQuery, ParameterObsolete] string? format, [FromQuery] long? endPositionTicks, [FromQuery] bool copyTimestamps = false, [FromQuery] bool addVttTimeMap = false) { return GetSubtitle( + routeItemId, + routeMediaSourceId, + routeIndex, + routeFormat, itemId, mediaSourceId, index, - routeFormat, format, endPositionTicks, copyTimestamps, addVttTimeMap, - startPositionTicks); + startPositionTicks ?? routeStartPositionTicks); } /// From 694d772b113b3f734e559b1dd083823dd931aad6 Mon Sep 17 00:00:00 2001 From: lmaonator <33778605+lmaonator@users.noreply.github.com> Date: Fri, 26 Mar 2021 14:13:45 +0100 Subject: [PATCH 1360/1930] Update Jellyfin.Api/Controllers/SessionController.cs Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/SessionController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index e178e3389a..0703d4255b 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -167,7 +167,7 @@ namespace Jellyfin.Api.Controllers [FromQuery, Required] PlayCommand playCommand, [FromQuery, Required, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] itemIds, [FromQuery] long? startPositionTicks, - [FromQuery] string mediaSourceId, + [FromQuery] string? mediaSourceId, [FromQuery] int? audioStreamIndex, [FromQuery] int? subtitleStreamIndex, [FromQuery] int? startIndex) From 78f7fdeaccee7f321740ede24dee797622b44f8b Mon Sep 17 00:00:00 2001 From: David Date: Fri, 26 Mar 2021 17:06:01 +0100 Subject: [PATCH 1361/1930] Rename methods and optimize allocations --- .../Library/PathExtensions.cs | 4 +-- .../Providers/ProviderIdParsers.cs | 34 ++++++++++--------- .../Parsers/BaseNfoParser.cs | 16 ++++----- .../Providers/ProviderIdParserTests.cs | 19 ++++++----- 4 files changed, 38 insertions(+), 35 deletions(-) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 72fe5a854a..73236bad83 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -44,8 +44,8 @@ namespace Emby.Server.Implementations.Library // for imdbid we also accept pattern matching if (string.Equals(attribute, "imdbid", StringComparison.OrdinalIgnoreCase)) { - var match = ProviderIdParsers.TryParseImdbId(str, out var imdbId); - return match ? imdbId : null; + var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId); + return match ? imdbId.ToString() : null; } return null; diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index 7744124eaa..26eaccac5f 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -12,6 +12,7 @@ namespace MediaBrowser.Common.Providers { private const int ImdbMinNumbers = 7; private const int ImdbMaxNumbers = 8; + private const string ImdbPrefix = "tt"; /// /// Parses an IMDb id from a string. @@ -19,9 +20,9 @@ namespace MediaBrowser.Common.Providers /// The text to parse. /// The parsed IMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseImdbId(ReadOnlySpan text, [NotNullWhen(true)] out string? imdbId) + public static bool TryFindImdbId(ReadOnlySpan text, [NotNullWhen(true)] out ReadOnlySpan imdbId) { - var tt = "tt".AsSpan(); + var tt = ImdbPrefix.AsSpan(); // imdb id is at least 9 chars (tt + 7 numbers) while (text.Length >= 2 + ImdbMinNumbers) @@ -33,9 +34,10 @@ namespace MediaBrowser.Common.Providers return false; } - text = text.Slice(ttPos + tt.Length); - var i = 0; - for (; i < Math.Min(text.Length, ImdbMaxNumbers); i++) + text = text.Slice(ttPos); + var i = 2; + var limit = Math.Min(text.Length, ImdbMaxNumbers + 2); + for (; i < limit; i++) { var c = text[i]; if (!IsDigit(c)) @@ -44,10 +46,10 @@ namespace MediaBrowser.Common.Providers } } - // skip if more than 8 digits - if (i <= ImdbMaxNumbers && i >= ImdbMinNumbers) + // skip if more than 8 digits + 2 chars for tt + if (i <= ImdbMaxNumbers + 2 && i >= ImdbMinNumbers + 2) { - imdbId = string.Concat(tt, text.Slice(0, i)); + imdbId = text.Slice(0, i); return true; } @@ -64,8 +66,8 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTmdbMovieId(ReadOnlySpan text, [NotNullWhen(true)] out string? tmdbId) - => TryParseProviderId(text, "themoviedb.org/movie/", out tmdbId); + public static bool TryFindTmdbMovieId(ReadOnlySpan text, [NotNullWhen(true)] out ReadOnlySpan tmdbId) + => TryFindProviderId(text, "themoviedb.org/movie/", out tmdbId); /// /// Parses an TMDb id from a series url. @@ -73,8 +75,8 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TMDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTmdbSeriesId(ReadOnlySpan text, [NotNullWhen(true)] out string? tmdbId) - => TryParseProviderId(text, "themoviedb.org/tv/", out tmdbId); + public static bool TryFindTmdbSeriesId(ReadOnlySpan text, [NotNullWhen(true)] out ReadOnlySpan tmdbId) + => TryFindProviderId(text, "themoviedb.org/tv/", out tmdbId); /// /// Parses an TVDb id from a url. @@ -82,10 +84,10 @@ namespace MediaBrowser.Common.Providers /// The text with the url to parse. /// The parsed TVDb id. /// True if parsing was successful, false otherwise. - public static bool TryParseTvdbId(ReadOnlySpan text, [NotNullWhen(true)] out string? tvdbId) - => TryParseProviderId(text, "thetvdb.com/?tab=series&id=", out tvdbId); + public static bool TryFindTvdbId(ReadOnlySpan text, [NotNullWhen(true)] out ReadOnlySpan tvdbId) + => TryFindProviderId(text, "thetvdb.com/?tab=series&id=", out tvdbId); - private static bool TryParseProviderId(ReadOnlySpan text, ReadOnlySpan searchString, [NotNullWhen(true)] out string? providerId) + private static bool TryFindProviderId(ReadOnlySpan text, ReadOnlySpan searchString, [NotNullWhen(true)] out ReadOnlySpan providerId) { var searchPos = text.IndexOf(searchString); if (searchPos == -1) @@ -109,7 +111,7 @@ namespace MediaBrowser.Common.Providers if (i >= 1) { - providerId = text.Slice(0, i).ToString(); + providerId = text.Slice(0, i); return true; } diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index d2fa120e8c..c5627f880c 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -219,29 +219,29 @@ namespace MediaBrowser.XbmcMetadata.Parsers protected void ParseProviderLinks(T item, string xml) { - if (ProviderIdParsers.TryParseImdbId(xml, out var imdbId)) + if (ProviderIdParsers.TryFindImdbId(xml, out var imdbId)) { - item.SetProviderId(MetadataProvider.Imdb, imdbId); + item.SetProviderId(MetadataProvider.Imdb, imdbId.ToString()); } if (item is Movie) { - if (ProviderIdParsers.TryParseTmdbMovieId(xml, out var tmdbId)) + if (ProviderIdParsers.TryFindTmdbMovieId(xml, out var tmdbId)) { - item.SetProviderId(MetadataProvider.Tmdb, tmdbId); + item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString()); } } if (item is Series) { - if (ProviderIdParsers.TryParseTmdbSeriesId(xml, out var tmdbId)) + if (ProviderIdParsers.TryFindTmdbSeriesId(xml, out var tmdbId)) { - item.SetProviderId(MetadataProvider.Tmdb, tmdbId); + item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString()); } - if (ProviderIdParsers.TryParseTvdbId(xml, out var tvdbId)) + if (ProviderIdParsers.TryFindTvdbId(xml, out var tvdbId)) { - item.SetProviderId(MetadataProvider.Tvdb, tvdbId); + item.SetProviderId(MetadataProvider.Tvdb, tvdbId.ToString()); } } } diff --git a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs index cfe1ea86bf..1ce54c59b5 100644 --- a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs +++ b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Common.Providers; +using System; +using MediaBrowser.Common.Providers; using Xunit; namespace Jellyfin.Common.Tests.Providers @@ -20,9 +21,9 @@ namespace Jellyfin.Common.Tests.Providers [InlineData("tt123456789", true, "tt12345678")] public void Parse_Imdb(string text, bool shouldSucceed, string? imdbId) { - var succeeded = ProviderIdParsers.TryParseImdbId(text, out string? parsedId); + var succeeded = ProviderIdParsers.TryFindImdbId(text, out ReadOnlySpan parsedId); Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(imdbId, parsedId); + Assert.Equal(imdbId ?? Span.Empty.ToString(), parsedId.ToString()); } [Theory] @@ -32,9 +33,9 @@ namespace Jellyfin.Common.Tests.Providers [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] public void Parse_TmdbMovie(string text, bool shouldSucceed, string? tmdbId) { - var succeeded = ProviderIdParsers.TryParseTmdbMovieId(text, out string? parsedId); + var succeeded = ProviderIdParsers.TryFindTmdbMovieId(text, out ReadOnlySpan parsedId); Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tmdbId, parsedId); + Assert.Equal(tmdbId ?? Span.Empty.ToString(), parsedId.ToString()); } [Theory] @@ -44,9 +45,9 @@ namespace Jellyfin.Common.Tests.Providers [InlineData("https://www.themoviedb.org/movie/30287-fallo", false, null)] public void Parse_TmdbSeries(string text, bool shouldSucceed, string? tmdbId) { - var succeeded = ProviderIdParsers.TryParseTmdbSeriesId(text, out string? parsedId); + var succeeded = ProviderIdParsers.TryFindTmdbSeriesId(text, out ReadOnlySpan parsedId); Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tmdbId, parsedId); + Assert.Equal(tmdbId ?? Span.Empty.ToString(), parsedId.ToString()); } [Theory] @@ -56,9 +57,9 @@ namespace Jellyfin.Common.Tests.Providers [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] public void Parse_Tvdb(string text, bool shouldSucceed, string? tvdbId) { - var succeeded = ProviderIdParsers.TryParseTvdbId(text, out string? parsedId); + var succeeded = ProviderIdParsers.TryFindTvdbId(text, out ReadOnlySpan parsedId); Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tvdbId, parsedId); + Assert.Equal(tvdbId ?? Span.Empty.ToString(), parsedId.ToString()); } } } From 7670189561302a88b576b3417594e036143ec7d7 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 27 Mar 2021 00:26:56 +0100 Subject: [PATCH 1362/1930] make directoryservice cache case sensitive --- .../Providers/DirectoryService.cs | 6 +- .../DirectoryServiceTests.cs | 200 ++++++++++++++++++ .../Jellyfin.Controller.Tests.csproj | 1 + 3 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 16fd1d42b0..5c92069b44 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -12,11 +12,11 @@ namespace MediaBrowser.Controller.Providers { private readonly IFileSystem _fileSystem; - private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _cache = new (StringComparer.Ordinal); - private readonly ConcurrentDictionary _fileCache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _fileCache = new (StringComparer.Ordinal); - private readonly ConcurrentDictionary> _filePathCache = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary> _filePathCache = new (StringComparer.Ordinal); public DirectoryService(IFileSystem fileSystem) { diff --git a/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs b/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs new file mode 100644 index 0000000000..feffb50e82 --- /dev/null +++ b/tests/Jellyfin.Controller.Tests/DirectoryServiceTests.cs @@ -0,0 +1,200 @@ +using System.Linq; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.IO; +using Moq; +using Xunit; + +namespace Jellyfin.Controller.Tests +{ + public class DirectoryServiceTests + { + private const string LowerCasePath = "/music/someartist"; + private const string UpperCasePath = "/music/SOMEARTIST"; + + private static readonly FileSystemMetadata[] _lowerCaseFileSystemMetadata = + { + new () + { + FullName = LowerCasePath + "/Artwork", + IsDirectory = true + }, + new () + { + FullName = LowerCasePath + "/Some Other Folder", + IsDirectory = true + }, + new () + { + FullName = LowerCasePath + "/Song 2.mp3", + IsDirectory = false + }, + new () + { + FullName = LowerCasePath + "/Song 3.mp3", + IsDirectory = false + } + }; + + private static readonly FileSystemMetadata[] _upperCaseFileSystemMetadata = + { + new () + { + FullName = UpperCasePath + "/Lyrics", + IsDirectory = true + }, + new () + { + FullName = UpperCasePath + "/Song 1.mp3", + IsDirectory = false + } + }; + + [Fact] + public void GetFileSystemEntries_GivenPathsWithDifferentCasing_CachesAll() + { + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is(x => x == UpperCasePath), false)).Returns(_upperCaseFileSystemMetadata); + fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is(x => x == LowerCasePath), false)).Returns(_lowerCaseFileSystemMetadata); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var upperCaseResult = directoryService.GetFileSystemEntries(UpperCasePath); + var lowerCaseResult = directoryService.GetFileSystemEntries(LowerCasePath); + + Assert.Equal(_upperCaseFileSystemMetadata, upperCaseResult); + Assert.Equal(_lowerCaseFileSystemMetadata, lowerCaseResult); + } + + [Fact] + public void GetFiles_GivenPathsWithDifferentCasing_ReturnsCorrectFiles() + { + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is(x => x == UpperCasePath), false)).Returns(_upperCaseFileSystemMetadata); + fileSystemMock.Setup(f => f.GetFileSystemEntries(It.Is(x => x == LowerCasePath), false)).Returns(_lowerCaseFileSystemMetadata); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var upperCaseResult = directoryService.GetFiles(UpperCasePath); + var lowerCaseResult = directoryService.GetFiles(LowerCasePath); + + Assert.Equal(_upperCaseFileSystemMetadata.Where(f => !f.IsDirectory), upperCaseResult); + Assert.Equal(_lowerCaseFileSystemMetadata.Where(f => !f.IsDirectory), lowerCaseResult); + } + + [Fact] + public void GetFile_GivenFilePathsWithDifferentCasing_ReturnsCorrectFile() + { + const string lowerCasePath = "/music/someartist/song 1.mp3"; + var lowerCaseFileSystemMetadata = new FileSystemMetadata + { + FullName = lowerCasePath, + Exists = true + }; + const string upperCasePath = "/music/SOMEARTIST/SONG 1.mp3"; + var upperCaseFileSystemMetadata = new FileSystemMetadata + { + FullName = upperCasePath, + Exists = false + }; + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFileInfo(It.Is(x => x == upperCasePath))).Returns(upperCaseFileSystemMetadata); + fileSystemMock.Setup(f => f.GetFileInfo(It.Is(x => x == lowerCasePath))).Returns(lowerCaseFileSystemMetadata); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var lowerCaseResult = directoryService.GetFile(lowerCasePath); + var upperCaseResult = directoryService.GetFile(upperCasePath); + + Assert.Equal(lowerCaseFileSystemMetadata, lowerCaseResult); + Assert.Null(upperCaseResult); + } + + [Fact] + public void GetFile_GivenCachedPath_ReturnsCachedFile() + { + const string path = "/music/someartist/song 1.mp3"; + var cachedFileSystemMetadata = new FileSystemMetadata + { + FullName = path, + Exists = true + }; + var newFileSystemMetadata = new FileSystemMetadata + { + FullName = "/music/SOMEARTIST/song 1.mp3", + Exists = true + }; + + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFileInfo(It.Is(x => x == path))).Returns(cachedFileSystemMetadata); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var result = directoryService.GetFile(path); + fileSystemMock.Setup(f => f.GetFileInfo(It.Is(x => x == path))).Returns(newFileSystemMetadata); + var secondResult = directoryService.GetFile(path); + + Assert.Equal(cachedFileSystemMetadata, result); + Assert.Equal(cachedFileSystemMetadata, secondResult); + } + + [Fact] + public void GetFilePaths_GivenCachedFilePathWithoutClear_ReturnsOnlyCachedPaths() + { + const string path = "/music/someartist"; + + var cachedPaths = new[] + { + "/music/someartist/song 1.mp3", + "/music/someartist/song 2.mp3", + "/music/someartist/song 3.mp3", + "/music/someartist/song 4.mp3", + }; + var newPaths = new[] + { + "/music/someartist/song 5.mp3", + "/music/someartist/song 6.mp3", + "/music/someartist/song 7.mp3", + "/music/someartist/song 8.mp3", + }; + + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFilePaths(It.Is(x => x == path), false)).Returns(cachedPaths); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var result = directoryService.GetFilePaths(path); + fileSystemMock.Setup(f => f.GetFilePaths(It.Is(x => x == path), false)).Returns(newPaths); + var secondResult = directoryService.GetFilePaths(path); + + Assert.Equal(cachedPaths, result); + Assert.Equal(cachedPaths, secondResult); + } + + [Fact] + public void GetFilePaths_GivenCachedFilePathWithClear_ReturnsNewPaths() + { + const string path = "/music/someartist"; + + var cachedPaths = new[] + { + "/music/someartist/song 1.mp3", + "/music/someartist/song 2.mp3", + "/music/someartist/song 3.mp3", + "/music/someartist/song 4.mp3", + }; + var newPaths = new[] + { + "/music/someartist/song 5.mp3", + "/music/someartist/song 6.mp3", + "/music/someartist/song 7.mp3", + "/music/someartist/song 8.mp3", + }; + + var fileSystemMock = new Mock(); + fileSystemMock.Setup(f => f.GetFilePaths(It.Is(x => x == path), false)).Returns(cachedPaths); + var directoryService = new DirectoryService(fileSystemMock.Object); + + var result = directoryService.GetFilePaths(path); + fileSystemMock.Setup(f => f.GetFilePaths(It.Is(x => x == path), false)).Returns(newPaths); + var secondResult = directoryService.GetFilePaths(path, true); + + Assert.Equal(cachedPaths, result); + Assert.Equal(newPaths, secondResult); + } + } +} diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index 6dec25aa4e..c56ccb3653 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -16,6 +16,7 @@ + From afe3b5999e00c7c705afe224e41755f5426e6b85 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 26 Mar 2021 17:40:55 -0600 Subject: [PATCH 1363/1930] Fix route naming --- Jellyfin.Api/Controllers/SubtitleController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SubtitleController.cs b/Jellyfin.Api/Controllers/SubtitleController.cs index 7a44b26a4b..1669a659dc 100644 --- a/Jellyfin.Api/Controllers/SubtitleController.cs +++ b/Jellyfin.Api/Controllers/SubtitleController.cs @@ -196,7 +196,7 @@ namespace Jellyfin.Api.Controllers /// The start position of the subtitle in ticks. /// File returned. /// A with the subtitle file. - [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{routeFormat}")] + [HttpGet("Videos/{routeItemId}/routeMediaSourceId/Subtitles/{routeIndex}/Stream.{routeFormat}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesFile("text/*")] public async Task GetSubtitle( From aae2aad0f25867f651c94a30d02a1893442d65da Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 27 Mar 2021 08:16:48 +0000 Subject: [PATCH 1364/1930] changed split to single quotes --- .../NetworkParseTests.cs | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 5d22b4d334..39fba1fb25 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -201,29 +201,29 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); // Test included. - Collection nc = nm.CreateIPCollection(settings.Split(","), false); + Collection nc = nm.CreateIPCollection(settings.Split(','), false); Assert.Equal(nc.AsString(), result1); // Test excluded. - nc = nm.CreateIPCollection(settings.Split(","), true); + nc = nm.CreateIPCollection(settings.Split(','), true); Assert.Equal(nc.AsString(), result3); conf.EnableIPV6 = false; nm.UpdateSettings(conf); // Test IP4 included. - nc = nm.CreateIPCollection(settings.Split(","), false); + nc = nm.CreateIPCollection(settings.Split(','), false); Assert.Equal(nc.AsString(), result2); // Test IP4 excluded. - nc = nm.CreateIPCollection(settings.Split(","), true); + nc = nm.CreateIPCollection(settings.Split(','), true); Assert.Equal(nc.AsString(), result4); conf.EnableIPV6 = true; nm.UpdateSettings(conf); // Test network addresses of collection. - nc = nm.CreateIPCollection(settings.Split(","), false); + nc = nm.CreateIPCollection(settings.Split(','), false); nc = nc.AsNetworks(); Assert.Equal(nc.AsString(), result5); } @@ -262,8 +262,8 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - Collection nc1 = nm.CreateIPCollection(settings.Split(","), false); - Collection nc2 = nm.CreateIPCollection(compare.Split(","), false); + Collection nc1 = nm.CreateIPCollection(settings.Split(','), false); + Collection nc2 = nm.CreateIPCollection(compare.Split(','), false); Assert.Equal(nc1.Union(nc2).AsString(), result); } @@ -372,10 +372,10 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); // Test included, IP6. - Collection ncSource = nm.CreateIPCollection(source.Split(",")); - Collection ncDest = nm.CreateIPCollection(dest.Split(",")); + Collection ncSource = nm.CreateIPCollection(source.Split(',')); + Collection ncDest = nm.CreateIPCollection(dest.Split(',')); Collection ncResult = ncSource.Union(ncDest); - Collection resultCollection = nm.CreateIPCollection(result.Split(",")); + Collection resultCollection = nm.CreateIPCollection(result.Split(',')); Assert.True(ncResult.Compare(resultCollection)); } @@ -527,7 +527,7 @@ namespace Jellyfin.Networking.Tests var conf = new NetworkConfiguration() { EnableIPV4 = true, - RemoteIPFilter = addresses.Split(","), + RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = false }; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); @@ -546,7 +546,7 @@ namespace Jellyfin.Networking.Tests var conf = new NetworkConfiguration() { EnableIPV4 = true, - RemoteIPFilter = addresses.Split(","), + RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = true }; From 364e8931af70b97881638109858734f4ecaa0d0a Mon Sep 17 00:00:00 2001 From: Dmitry Lyzo Date: Sat, 27 Mar 2021 11:48:59 +0300 Subject: [PATCH 1365/1930] Check appropriate profile type --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index bf33691c77..167fc984e6 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -514,6 +514,8 @@ namespace MediaBrowser.Model.Dlna private static List GetTranscodeReasonsFromDirectPlayProfile(MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream, IEnumerable directPlayProfiles) { + var mediaType = videoStream != null ? DlnaProfileType.Video : DlnaProfileType.Audio; + var containerSupported = false; var audioSupported = false; var videoSupported = false; @@ -521,7 +523,7 @@ namespace MediaBrowser.Model.Dlna foreach (var profile in directPlayProfiles) { // Check container type - if (profile.SupportsContainer(item.Container)) + if (profile.Type == mediaType && profile.SupportsContainer(item.Container)) { containerSupported = true; From 81e3e5ca4883309b38377729e0bbd1b9f163ec7c Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Fri, 26 Mar 2021 10:02:23 -0400 Subject: [PATCH 1366/1930] Changed SessionController.SendMessageCommand implementation receive data in the POST body, as that is how the jellyfin-web client currently posts the data to the server. Resolves: #5628 --- Jellyfin.Api/Controllers/SessionController.cs | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 0703d4255b..ba68b4cbf8 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -313,9 +313,7 @@ namespace Jellyfin.Api.Controllers /// Issues a command to a client to display a message to the user. /// /// The session id. - /// The message test. - /// The message header. - /// The message timeout. If omitted the user will have to confirm viewing the message. + /// The object containing Header, Message Text, and TimeoutMs. /// Message sent. /// A . [HttpPost("Sessions/{sessionId}/Message")] @@ -323,18 +321,25 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SendMessageCommand( [FromRoute, Required] string sessionId, - [FromQuery, Required] string text, - [FromQuery] string? header, - [FromQuery] long? timeoutMs) + [FromBody] MessageCommand command) { - var command = new MessageCommand + if (command == null) { - Header = string.IsNullOrEmpty(header) ? "Message from Server" : header, - TimeoutMs = timeoutMs, - Text = text + throw new ArgumentException("Request body may not be null"); + } + //Need to check if message.Text is null, since [Required] can't be applied to properties of a deserialized object. + if (string.IsNullOrWhiteSpace(command.Text)) + { + throw new ArgumentNullException("Message Text may not be empty."); + } + var nullCorrectedCommand = new MessageCommand + { + Header = string.IsNullOrWhiteSpace(command.Header) ? "Message from Server" : command.Header, + TimeoutMs = command.TimeoutMs, + Text = command.Text }; - _sessionManager.SendMessageCommand(RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id, sessionId, command, CancellationToken.None); + _sessionManager.SendMessageCommand(RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id, sessionId, nullCorrectedCommand, CancellationToken.None); return NoContent(); } From f114ba57dd24ed38786a478df7a641f81dd9d5c7 Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Fri, 26 Mar 2021 10:37:59 -0400 Subject: [PATCH 1367/1930] Fixed comment and code block runes to match coding standards required by Jellyfin team. --- Jellyfin.Api/Controllers/SessionController.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index ba68b4cbf8..82aa32a7ab 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -327,11 +327,13 @@ namespace Jellyfin.Api.Controllers { throw new ArgumentException("Request body may not be null"); } - //Need to check if message.Text is null, since [Required] can't be applied to properties of a deserialized object. + + // Need to check if message.Text is null, since [Required] can't be applied to properties of a deserialized object. if (string.IsNullOrWhiteSpace(command.Text)) { throw new ArgumentNullException("Message Text may not be empty."); } + var nullCorrectedCommand = new MessageCommand { Header = string.IsNullOrWhiteSpace(command.Header) ? "Message from Server" : command.Header, From 998833ea6e4c52f842949029b278008b276e3e6b Mon Sep 17 00:00:00 2001 From: "Brian C. Arnold" Date: Sat, 27 Mar 2021 23:28:08 -0400 Subject: [PATCH 1368/1930] Removed null check for body object and user [Required] attribute in replacement. --- Jellyfin.Api/Controllers/SessionController.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 82aa32a7ab..34dfb6ce7f 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -321,12 +321,8 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult SendMessageCommand( [FromRoute, Required] string sessionId, - [FromBody] MessageCommand command) + [FromBody, Required] MessageCommand command) { - if (command == null) - { - throw new ArgumentException("Request body may not be null"); - } // Need to check if message.Text is null, since [Required] can't be applied to properties of a deserialized object. if (string.IsNullOrWhiteSpace(command.Text)) From 1669cb661858676e40f0e7f89205e4e93111da85 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 29 Mar 2021 10:35:29 +0200 Subject: [PATCH 1369/1930] Split valid and invalid tests --- .../Providers/ProviderIdParsers.cs | 4 +- .../Providers/ProviderIdParserTests.cs | 100 +++++++++++------- 2 files changed, 61 insertions(+), 43 deletions(-) diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index 26eaccac5f..64c2e19766 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -22,12 +22,10 @@ namespace MediaBrowser.Common.Providers /// True if parsing was successful, false otherwise. public static bool TryFindImdbId(ReadOnlySpan text, [NotNullWhen(true)] out ReadOnlySpan imdbId) { - var tt = ImdbPrefix.AsSpan(); - // imdb id is at least 9 chars (tt + 7 numbers) while (text.Length >= 2 + ImdbMinNumbers) { - var ttPos = text.IndexOf(tt); + var ttPos = text.IndexOf(ImdbPrefix); if (ttPos == -1) { imdbId = default; diff --git a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs index 1ce54c59b5..ef9d31cc19 100644 --- a/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs +++ b/tests/Jellyfin.Common.Tests/Providers/ProviderIdParserTests.cs @@ -7,59 +7,79 @@ namespace Jellyfin.Common.Tests.Providers public class ProviderIdParserTests { [Theory] - [InlineData("tt123456", false, null)] - [InlineData("tt1234567", true, "tt1234567")] - [InlineData("tt12345678", true, "tt12345678")] - [InlineData("https://www.imdb.com/title/tt123456", false, null)] - [InlineData("https://www.imdb.com/title/tt1234567", true, "tt1234567")] - [InlineData("https://www.imdb.com/title/tt12345678", true, "tt12345678")] - [InlineData(@"multiline\nhttps://www.imdb.com/title/tt1234567", true, "tt1234567")] - [InlineData(@"multiline\nhttps://www.imdb.com/title/tt12345678", true, "tt12345678")] - [InlineData("Jellyfin", false, null)] - [InlineData("tt1234567tt7654321", true, "tt1234567")] - [InlineData("tt12345678tt7654321", true, "tt12345678")] - [InlineData("tt123456789", true, "tt12345678")] - public void Parse_Imdb(string text, bool shouldSucceed, string? imdbId) + [InlineData("tt1234567", "tt1234567")] + [InlineData("tt12345678", "tt12345678")] + [InlineData("https://www.imdb.com/title/tt1234567", "tt1234567")] + [InlineData("https://www.imdb.com/title/tt12345678", "tt12345678")] + [InlineData(@"multiline\nhttps://www.imdb.com/title/tt1234567", "tt1234567")] + [InlineData(@"multiline\nhttps://www.imdb.com/title/tt12345678", "tt12345678")] + [InlineData("tt1234567tt7654321", "tt1234567")] + [InlineData("tt12345678tt7654321", "tt12345678")] + [InlineData("tt123456789", "tt12345678")] + public void FindImdbId_Valid_Success(string text, string expected) { - var succeeded = ProviderIdParsers.TryFindImdbId(text, out ReadOnlySpan parsedId); - Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(imdbId ?? Span.Empty.ToString(), parsedId.ToString()); + Assert.True(ProviderIdParsers.TryFindImdbId(text, out ReadOnlySpan parsedId)); + Assert.Equal(expected, parsedId.ToString()); } [Theory] - [InlineData("https://www.themoviedb.org/movie/30287-fallo", true, "30287")] - [InlineData("themoviedb.org/movie/30287", true, "30287")] - [InlineData("https://www.themoviedb.org/movie/fallo-30287", false, null)] - [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] - public void Parse_TmdbMovie(string text, bool shouldSucceed, string? tmdbId) + [InlineData("tt123456")] + [InlineData("https://www.imdb.com/title/tt123456")] + [InlineData("Jellyfin")] + public void FindImdbId_Invalid_Success(string text) { - var succeeded = ProviderIdParsers.TryFindTmdbMovieId(text, out ReadOnlySpan parsedId); - Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tmdbId ?? Span.Empty.ToString(), parsedId.ToString()); + Assert.False(ProviderIdParsers.TryFindImdbId(text, out _)); } [Theory] - [InlineData("https://www.themoviedb.org/tv/1668-friends", true, "1668")] - [InlineData("themoviedb.org/tv/1668", true, "1668")] - [InlineData("https://www.themoviedb.org/tv/friends-1668", false, null)] - [InlineData("https://www.themoviedb.org/movie/30287-fallo", false, null)] - public void Parse_TmdbSeries(string text, bool shouldSucceed, string? tmdbId) + [InlineData("https://www.themoviedb.org/movie/30287-fallo", "30287")] + [InlineData("themoviedb.org/movie/30287", "30287")] + public void FindTmdbMovieId_Valid_Success(string text, string expected) { - var succeeded = ProviderIdParsers.TryFindTmdbSeriesId(text, out ReadOnlySpan parsedId); - Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tmdbId ?? Span.Empty.ToString(), parsedId.ToString()); + Assert.True(ProviderIdParsers.TryFindTmdbMovieId(text, out ReadOnlySpan parsedId)); + Assert.Equal(expected, parsedId.ToString()); } [Theory] - [InlineData("https://www.thetvdb.com/?tab=series&id=121361", true, "121361")] - [InlineData("thetvdb.com/?tab=series&id=121361", true, "121361")] - [InlineData("thetvdb.com/?tab=series&id=Jellyfin121361", false, null)] - [InlineData("https://www.themoviedb.org/tv/1668-friends", false, null)] - public void Parse_Tvdb(string text, bool shouldSucceed, string? tvdbId) + [InlineData("https://www.themoviedb.org/movie/fallo-30287")] + [InlineData("https://www.themoviedb.org/tv/1668-friends")] + public void FindTmdbMovieId_Invalid_Success(string text) { - var succeeded = ProviderIdParsers.TryFindTvdbId(text, out ReadOnlySpan parsedId); - Assert.Equal(shouldSucceed, succeeded); - Assert.Equal(tvdbId ?? Span.Empty.ToString(), parsedId.ToString()); + Assert.False(ProviderIdParsers.TryFindTmdbMovieId(text, out _)); + } + + [Theory] + [InlineData("https://www.themoviedb.org/tv/1668-friends", "1668")] + [InlineData("themoviedb.org/tv/1668", "1668")] + public void FindTmdbSeriesId_Valid_Success(string text, string expected) + { + Assert.True(ProviderIdParsers.TryFindTmdbSeriesId(text, out ReadOnlySpan parsedId)); + Assert.Equal(expected, parsedId.ToString()); + } + + [Theory] + [InlineData("https://www.themoviedb.org/tv/friends-1668")] + [InlineData("https://www.themoviedb.org/movie/30287-fallo")] + public void FindTmdbSeriesId_Invalid_Success(string text) + { + Assert.False(ProviderIdParsers.TryFindTmdbSeriesId(text, out _)); + } + + [Theory] + [InlineData("https://www.thetvdb.com/?tab=series&id=121361", "121361")] + [InlineData("thetvdb.com/?tab=series&id=121361", "121361")] + public void FindTvdbId_Valid_Success(string text, string expected) + { + Assert.True(ProviderIdParsers.TryFindTvdbId(text, out ReadOnlySpan parsedId)); + Assert.Equal(expected, parsedId.ToString()); + } + + [Theory] + [InlineData("thetvdb.com/?tab=series&id=Jellyfin121361")] + [InlineData("https://www.themoviedb.org/tv/1668-friends")] + public void FindTvdbId_Invalid_Success(string text) + { + Assert.False(ProviderIdParsers.TryFindTvdbId(text, out _)); } } } From a7c82b2681aa966e11958ee71d2d20fb20f8233f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Mon, 29 Mar 2021 12:11:38 +0200 Subject: [PATCH 1370/1930] [5644] [DLNA] [Music] Next track command from any DLNA device does not do anything. --- Emby.Dlna/PlayTo/Device.cs | 36 +++++++++++++++++++++++++ Emby.Dlna/PlayTo/PlayToController.cs | 40 ++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index 7bf7047fbb..9d45e89df7 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -368,6 +368,42 @@ namespace Emby.Dlna.PlayTo RestartTimer(true); } + /* + * SetNextAvTransport is used to specify to the DLNA device what is the next track to play. + * Without that information, the next track command on the device does not work. + */ + public async Task SetNextAvTransport(string url, string header, string metaData, CancellationToken cancellationToken = default) + { + var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false); + + url = url.Replace("&", "&", StringComparison.Ordinal); + + _logger.LogDebug("{0} - SetNextAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header); + + var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetNextAVTransportURI"); + if (command == null) + { + return; + } + + var dictionary = new Dictionary + { + { "NextURI", url }, + { "NextURIMetaData", CreateDidlMeta(metaData) } + }; + + var service = GetAvTransportService(); + + if (service == null) + { + throw new InvalidOperationException("Unable to find service"); + } + + var post = avCommands.BuildPost(command, service.ServiceType, url, dictionary); + await new SsdpHttpClient(_httpClientFactory).SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header: header, cancellationToken) + .ConfigureAwait(false); + } + private static string CreateDidlMeta(string value) { if (string.IsNullOrEmpty(value)) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 5abc1bc134..503c2eee21 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -102,6 +102,22 @@ namespace Emby.Dlna.PlayTo _deviceDiscovery.DeviceLeft += OnDeviceDiscoveryDeviceLeft; } + /* + * Send a message to the DLNA device to notify what is the next track in the playlist. + */ + private async void SendNextTrackMessage(int currentPlayListItemIndex, CancellationToken cancellationToken) + { + if (currentPlayListItemIndex >= 0 && currentPlayListItemIndex < _playlist.Count - 1) + { + // The current playing item is indeed in the play list and we are not yet at the end of the playlist. + var nextItemIndex = currentPlayListItemIndex + 1; + var nextItem = _playlist[nextItemIndex]; + + // Send the SetNextAvTransport message. + await _device.SetNextAvTransport(nextItem.StreamUrl, GetDlnaHeaders(nextItem), nextItem.Didl, cancellationToken).ConfigureAwait(false); + } + } + private void OnDeviceUnavailable() { try @@ -153,6 +169,14 @@ namespace Emby.Dlna.PlayTo return; } + // Create the new play list item : mainly to have the normalized StreamUrl and find it in the playlist. + var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null; + var newItem = CreatePlaylistItem(streamInfo.Item, user, 0, streamInfo.MediaSourceId, streamInfo.AudioStreamIndex, streamInfo.SubtitleStreamIndex); + + // Send a message to the DLNA device to notify what is the next track in the playlist. + var currentItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); + SendNextTrackMessage(currentItemIndex, CancellationToken.None); + var newItemProgress = GetProgressInfo(streamInfo); await _sessionManager.OnPlaybackStart(newItemProgress).ConfigureAwait(false); @@ -425,6 +449,11 @@ namespace Emby.Dlna.PlayTo var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, info.SubtitleStreamIndex); await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false); + + // Send a message to the DLNA device to notify what is the next track in the play list. + var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); + SendNextTrackMessage(newItemIndex, CancellationToken.None); + return; } @@ -623,6 +652,9 @@ namespace Emby.Dlna.PlayTo await _device.SetAvTransport(currentitem.StreamUrl, GetDlnaHeaders(currentitem), currentitem.Didl, cancellationToken).ConfigureAwait(false); + // Send a message to the DLNA device to notify what is the next track in the play list. + SendNextTrackMessage(index, CancellationToken.None); + var streamInfo = currentitem.StreamInfo; if (streamInfo.StartPositionTicks > 0 && EnableClientSideSeek(streamInfo)) { @@ -736,6 +768,10 @@ namespace Emby.Dlna.PlayTo await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false); + // Send a message to the DLNA device to notify what is the next track in the play list. + var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); + SendNextTrackMessage(newItemIndex, CancellationToken.None); + if (EnableClientSideSeek(newItem.StreamInfo)) { await SeekAfterTransportChange(newPosition, CancellationToken.None).ConfigureAwait(false); @@ -761,6 +797,10 @@ namespace Emby.Dlna.PlayTo await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl, CancellationToken.None).ConfigureAwait(false); + // Send a message to the DLNA device to notify what is the next track in the play list. + var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); + SendNextTrackMessage(newItemIndex, CancellationToken.None); + if (EnableClientSideSeek(newItem.StreamInfo) && newPosition > 0) { await SeekAfterTransportChange(newPosition, CancellationToken.None).ConfigureAwait(false); From 023467ebcee2ada86ba99d2dccb00141ab0ed264 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 29 Mar 2021 12:00:44 +0000 Subject: [PATCH 1371/1930] Bump Serilog.AspNetCore from 3.4.0 to 4.1.0 Bumps [Serilog.AspNetCore](https://github.com/serilog/serilog-aspnetcore) from 3.4.0 to 4.1.0. - [Release notes](https://github.com/serilog/serilog-aspnetcore/releases) - [Commits](https://github.com/serilog/serilog-aspnetcore/compare/v3.4.0...v4.1.0) Signed-off-by: dependabot[bot] --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 09799307b7..b7406d849a 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -41,7 +41,7 @@ - + From 949ef2ed10bd79387fe3e2e1ff34af98c89ee3b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 29 Mar 2021 12:00:57 +0000 Subject: [PATCH 1372/1930] Bump BlurHashSharp from 1.1.1 to 1.2.0 Bumps [BlurHashSharp](https://github.com/Bond-009/BlurHashSharp) from 1.1.1 to 1.2.0. - [Release notes](https://github.com/Bond-009/BlurHashSharp/releases) - [Commits](https://github.com/Bond-009/BlurHashSharp/commits/v1.2.0) Signed-off-by: dependabot[bot] --- Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index 3fc44640b0..5f9c4d6792 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -20,7 +20,7 @@ - + From ca25301e649342ef5598822fdd9ffc6eb2cd5065 Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Mon, 29 Mar 2021 10:10:44 -0400 Subject: [PATCH 1373/1930] Added Required attribute to Text property of MessageCommand. --- Jellyfin.Api/Controllers/SessionController.cs | 7 ------- MediaBrowser.Model/Session/MessageCommand.cs | 4 +++- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 34dfb6ce7f..14686222be 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -323,13 +323,6 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string sessionId, [FromBody, Required] MessageCommand command) { - - // Need to check if message.Text is null, since [Required] can't be applied to properties of a deserialized object. - if (string.IsNullOrWhiteSpace(command.Text)) - { - throw new ArgumentNullException("Message Text may not be empty."); - } - var nullCorrectedCommand = new MessageCommand { Header = string.IsNullOrWhiteSpace(command.Header) ? "Message from Server" : command.Header, diff --git a/MediaBrowser.Model/Session/MessageCommand.cs b/MediaBrowser.Model/Session/MessageCommand.cs index 09abfbb3f2..0ee3c720e5 100644 --- a/MediaBrowser.Model/Session/MessageCommand.cs +++ b/MediaBrowser.Model/Session/MessageCommand.cs @@ -1,12 +1,14 @@ #nullable disable #pragma warning disable CS1591 +using System.ComponentModel.DataAnnotations; + namespace MediaBrowser.Model.Session { public class MessageCommand { public string Header { get; set; } - + [Required(AllowEmptyStrings = false)] public string Text { get; set; } public long? TimeoutMs { get; set; } From 54107ae88262d835cac2d5a6f335b0c10d050b1a Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Mon, 29 Mar 2021 11:40:07 -0400 Subject: [PATCH 1374/1930] Fix spacing requirement for MessageCommand. --- MediaBrowser.Model/Session/MessageCommand.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Model/Session/MessageCommand.cs b/MediaBrowser.Model/Session/MessageCommand.cs index 0ee3c720e5..cc9db8e6c5 100644 --- a/MediaBrowser.Model/Session/MessageCommand.cs +++ b/MediaBrowser.Model/Session/MessageCommand.cs @@ -8,6 +8,7 @@ namespace MediaBrowser.Model.Session public class MessageCommand { public string Header { get; set; } + [Required(AllowEmptyStrings = false)] public string Text { get; set; } From ec113816aa9d9f973665501c869cab47a13e6125 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Mon, 29 Mar 2021 23:43:02 +0200 Subject: [PATCH 1375/1930] [5644] [DLNA] [Music] Next track command from any DLNA device does not do anything. --- Emby.Dlna/PlayTo/PlayToController.cs | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index 503c2eee21..e0c752c199 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -105,7 +105,7 @@ namespace Emby.Dlna.PlayTo /* * Send a message to the DLNA device to notify what is the next track in the playlist. */ - private async void SendNextTrackMessage(int currentPlayListItemIndex, CancellationToken cancellationToken) + private async Task SendNextTrackMessage(int currentPlayListItemIndex, CancellationToken cancellationToken) { if (currentPlayListItemIndex >= 0 && currentPlayListItemIndex < _playlist.Count - 1) { @@ -169,17 +169,13 @@ namespace Emby.Dlna.PlayTo return; } - // Create the new play list item : mainly to have the normalized StreamUrl and find it in the playlist. - var user = !_session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(_session.UserId) : null; - var newItem = CreatePlaylistItem(streamInfo.Item, user, 0, streamInfo.MediaSourceId, streamInfo.AudioStreamIndex, streamInfo.SubtitleStreamIndex); - - // Send a message to the DLNA device to notify what is the next track in the playlist. - var currentItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); - SendNextTrackMessage(currentItemIndex, CancellationToken.None); - var newItemProgress = GetProgressInfo(streamInfo); await _sessionManager.OnPlaybackStart(newItemProgress).ConfigureAwait(false); + + // Send a message to the DLNA device to notify what is the next track in the playlist. + var currentItemIndex = _playlist.FindIndex(item => item.StreamInfo.ItemId == streamInfo.ItemId); + await SendNextTrackMessage(currentItemIndex, CancellationToken.None); } catch (Exception ex) { @@ -452,7 +448,7 @@ namespace Emby.Dlna.PlayTo // Send a message to the DLNA device to notify what is the next track in the play list. var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); - SendNextTrackMessage(newItemIndex, CancellationToken.None); + await SendNextTrackMessage(newItemIndex, CancellationToken.None); return; } @@ -653,7 +649,7 @@ namespace Emby.Dlna.PlayTo await _device.SetAvTransport(currentitem.StreamUrl, GetDlnaHeaders(currentitem), currentitem.Didl, cancellationToken).ConfigureAwait(false); // Send a message to the DLNA device to notify what is the next track in the play list. - SendNextTrackMessage(index, CancellationToken.None); + await SendNextTrackMessage(index, CancellationToken.None); var streamInfo = currentitem.StreamInfo; if (streamInfo.StartPositionTicks > 0 && EnableClientSideSeek(streamInfo)) @@ -770,7 +766,7 @@ namespace Emby.Dlna.PlayTo // Send a message to the DLNA device to notify what is the next track in the play list. var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); - SendNextTrackMessage(newItemIndex, CancellationToken.None); + await SendNextTrackMessage(newItemIndex, CancellationToken.None); if (EnableClientSideSeek(newItem.StreamInfo)) { @@ -799,7 +795,7 @@ namespace Emby.Dlna.PlayTo // Send a message to the DLNA device to notify what is the next track in the play list. var newItemIndex = _playlist.FindIndex(item => item.StreamUrl == newItem.StreamUrl); - SendNextTrackMessage(newItemIndex, CancellationToken.None); + await SendNextTrackMessage(newItemIndex, CancellationToken.None); if (EnableClientSideSeek(newItem.StreamInfo) && newPosition > 0) { From 80fe48fda972eff0d6b58ac8a9e2f63d44a1b23e Mon Sep 17 00:00:00 2001 From: BrianCArnold Date: Tue, 30 Mar 2021 07:29:40 -0400 Subject: [PATCH 1376/1930] Update SessionController.cs Removed unnecessary construction of POCO to represent data from POST body --- Jellyfin.Api/Controllers/SessionController.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 14686222be..b64cbe30c7 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -323,12 +323,10 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string sessionId, [FromBody, Required] MessageCommand command) { - var nullCorrectedCommand = new MessageCommand + if (string.IsNullOrWhiteSpace(command.Header)) { - Header = string.IsNullOrWhiteSpace(command.Header) ? "Message from Server" : command.Header, - TimeoutMs = command.TimeoutMs, - Text = command.Text - }; + command.Header = "Message from Server"; + } _sessionManager.SendMessageCommand(RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id, sessionId, nullCorrectedCommand, CancellationToken.None); From 8c6bd2537c47dafab46ed9ca756b9f91f995603c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Tue, 30 Mar 2021 15:15:16 +0200 Subject: [PATCH 1377/1930] Return Major.Minor.Build instead of Major.Minor.Build.Revision for OpenAPI version --- Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index d26ac251c0..2b34370a09 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -260,7 +260,7 @@ namespace Jellyfin.Server.Extensions { return serviceCollection.AddSwaggerGen(c => { - var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString() ?? "0.0.0.1"; + var version = typeof(ApplicationHost).Assembly.GetName().Version?.ToString(3) ?? "0.0.1"; c.SwaggerDoc("api-docs", new OpenApiInfo { Title = "Jellyfin API", From 3164781ce09200547999762ca618d0b67c3cc46f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Senart?= Date: Tue, 30 Mar 2021 22:18:32 +0200 Subject: [PATCH 1378/1930] [5644] [DLNA] [Music] Next track command from any DLNA device does not do anything. --- Emby.Dlna/PlayTo/PlayToController.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index e0c752c199..41723bc6c5 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -175,6 +175,11 @@ namespace Emby.Dlna.PlayTo // Send a message to the DLNA device to notify what is the next track in the playlist. var currentItemIndex = _playlist.FindIndex(item => item.StreamInfo.ItemId == streamInfo.ItemId); + if (currentItemIndex >= 0) + { + _currentPlaylistIndex = currentItemIndex; + } + await SendNextTrackMessage(currentItemIndex, CancellationToken.None); } catch (Exception ex) From af03b280bc91f65712af2cc854e8bf1ad349748a Mon Sep 17 00:00:00 2001 From: BrianCArnold Date: Wed, 31 Mar 2021 01:23:51 -0400 Subject: [PATCH 1379/1930] Update SessionController.cs --- Jellyfin.Api/Controllers/SessionController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index b64cbe30c7..1981e213e8 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -323,7 +323,7 @@ namespace Jellyfin.Api.Controllers [FromRoute, Required] string sessionId, [FromBody, Required] MessageCommand command) { - if (string.IsNullOrWhiteSpace(command.Header)) + if (string.IsNullOrWhiteSpace(command.Header)) { command.Header = "Message from Server"; } From 4fa2a32d81e263ef51140e2ae8259a02fdfb0d7d Mon Sep 17 00:00:00 2001 From: BrianCArnold Date: Wed, 31 Mar 2021 01:24:38 -0400 Subject: [PATCH 1380/1930] Apply suggestions from code review Co-authored-by: Claus Vium --- Jellyfin.Api/Controllers/SessionController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/SessionController.cs b/Jellyfin.Api/Controllers/SessionController.cs index 1981e213e8..7bd0b6918f 100644 --- a/Jellyfin.Api/Controllers/SessionController.cs +++ b/Jellyfin.Api/Controllers/SessionController.cs @@ -325,10 +325,10 @@ namespace Jellyfin.Api.Controllers { if (string.IsNullOrWhiteSpace(command.Header)) { - command.Header = "Message from Server"; + command.Header = "Message from Server"; } - _sessionManager.SendMessageCommand(RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id, sessionId, nullCorrectedCommand, CancellationToken.None); + _sessionManager.SendMessageCommand(RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id, sessionId, command, CancellationToken.None); return NoContent(); } From 28a0eb6d53b472fd62d4cc6001770e0cabdf38cd Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Thu, 1 Apr 2021 14:28:03 +0200 Subject: [PATCH 1381/1930] set original title in tmdbmovieprovider --- MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 4963777bc4..833d1ae389 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -175,6 +175,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies var movie = new Movie { Name = movieResult.Title ?? movieResult.OriginalTitle, + OriginalTitle = movieResult.OriginalTitle, Overview = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture), Tagline = movieResult.Tagline, ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray() From df60d176b8105b36e186191bef7dc6811ce5dbcd Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Thu, 1 Apr 2021 15:27:28 +0200 Subject: [PATCH 1382/1930] ensure only valid images are saved in ItemImageProvider --- MediaBrowser.Providers/Manager/ItemImageProvider.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.Providers/Manager/ItemImageProvider.cs b/MediaBrowser.Providers/Manager/ItemImageProvider.cs index ffc6889fa2..4471a25b2f 100644 --- a/MediaBrowser.Providers/Manager/ItemImageProvider.cs +++ b/MediaBrowser.Providers/Manager/ItemImageProvider.cs @@ -469,6 +469,7 @@ namespace MediaBrowser.Providers.Manager try { using var response = await provider.GetImageResponse(url, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await _providerManager.SaveImage( From 11f7ab4dd4deec133a18e2f77e1d3a6dff2b9f3e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 1 Apr 2021 19:13:03 +0200 Subject: [PATCH 1383/1930] Add tests for CopyToExtensions --- .../Extensions/CopyToExtensionsTests.cs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 tests/Jellyfin.Common.Tests/Extensions/CopyToExtensionsTests.cs diff --git a/tests/Jellyfin.Common.Tests/Extensions/CopyToExtensionsTests.cs b/tests/Jellyfin.Common.Tests/Extensions/CopyToExtensionsTests.cs new file mode 100644 index 0000000000..9903409fa6 --- /dev/null +++ b/tests/Jellyfin.Common.Tests/Extensions/CopyToExtensionsTests.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using MediaBrowser.Common.Extensions; +using Xunit; + +namespace Jellyfin.Common.Tests.Extensions +{ + public static class CopyToExtensionsTests + { + public static IEnumerable CopyTo_Valid_Correct_TestData() + { + yield return new object[] { new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, 0, new[] { 0, 1, 2, 3, 4, 5 } }; + yield return new object[] { new[] { 0, 1, 2 }, new[] { 5, 4, 3, 2, 1, 0 }, 2, new[] { 5, 4, 0, 1, 2, 0 } }; + } + + [Theory] + [MemberData(nameof(CopyTo_Valid_Correct_TestData))] + public static void CopyTo_Valid_Correct(IReadOnlyList source, IList destination, int index, IList expected) + { + source.CopyTo(destination, index); + Assert.Equal(expected, destination); + } + + public static IEnumerable CopyTo_Invalid_ThrowsArgumentOutOfRangeException_TestData() + { + yield return new object[] { new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, -1 }; + yield return new object[] { new[] { 0, 1, 2 }, new[] { 5, 4, 3, 2, 1, 0 }, 6 }; + yield return new object[] { new[] { 0, 1, 2 }, Array.Empty(), 0 }; + yield return new object[] { new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0 }, 0 }; + yield return new object[] { new[] { 0, 1, 2, 3, 4, 5 }, new[] { 0, 0, 0, 0, 0, 0 }, 1 }; + } + + [Theory] + [MemberData(nameof(CopyTo_Invalid_ThrowsArgumentOutOfRangeException_TestData))] + public static void CopyTo_Invalid_ThrowsArgumentOutOfRangeException(IReadOnlyList source, IList destination, int index) + { + Assert.Throws(() => source.CopyTo(destination, index)); + } + } +} From aa769573387b051fb79246885be8eb5e8cf97e76 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 1 Apr 2021 19:16:00 +0200 Subject: [PATCH 1384/1930] Remove useless code --- Emby.Dlna/ConnectionManager/ControlHandler.cs | 2 +- Emby.Dlna/ContentDirectory/ControlHandler.cs | 45 ++++++------------- .../MediaReceiverRegistrar/ControlHandler.cs | 2 +- Emby.Dlna/Service/BaseControlHandler.cs | 2 +- .../Library/Resolvers/TV/SeriesResolver.cs | 22 +-------- .../LiveTv/EmbyTV/EpgChannelData.cs | 43 +++++++----------- 6 files changed, 35 insertions(+), 81 deletions(-) diff --git a/Emby.Dlna/ConnectionManager/ControlHandler.cs b/Emby.Dlna/ConnectionManager/ControlHandler.cs index 2f8d197a7a..1a1790ee6a 100644 --- a/Emby.Dlna/ConnectionManager/ControlHandler.cs +++ b/Emby.Dlna/ConnectionManager/ControlHandler.cs @@ -31,7 +31,7 @@ namespace Emby.Dlna.ConnectionManager } /// - protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) + protected override void WriteResult(string methodName, IReadOnlyDictionary methodParams, XmlWriter xmlWriter) { if (string.Equals(methodName, "GetProtocolInfo", StringComparison.OrdinalIgnoreCase)) { diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 27f1fdabad..713f950990 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -121,7 +121,7 @@ namespace Emby.Dlna.ContentDirectory } /// - protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) + protected override void WriteResult(string methodName, IReadOnlyDictionary methodParams, XmlWriter xmlWriter) { if (xmlWriter == null) { @@ -201,8 +201,8 @@ namespace Emby.Dlna.ContentDirectory /// /// Adds a "XSetBookmark" element to the xml document. /// - /// The . - private void HandleXSetBookmark(IDictionary sparams) + /// The method parameters. + private void HandleXSetBookmark(IReadOnlyDictionary sparams) { var id = sparams["ObjectID"]; @@ -305,35 +305,18 @@ namespace Emby.Dlna.ContentDirectory return builder.ToString(); } - /// - /// Returns the value in the key of the dictionary, or defaultValue if it doesn't exist. - /// - /// The . - /// The key. - /// The defaultValue. - /// The . - public static string GetValueOrDefault(IDictionary sparams, string key, string defaultValue) - { - if (sparams != null && sparams.TryGetValue(key, out string val)) - { - return val; - } - - return defaultValue; - } - /// /// Builds the "Browse" xml response. /// /// The . - /// The . + /// The method parameters. /// The device Id to use. - private void HandleBrowse(XmlWriter xmlWriter, IDictionary sparams, string deviceId) + private void HandleBrowse(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId) { var id = sparams["ObjectID"]; var flag = sparams["BrowseFlag"]; - var filter = new Filter(GetValueOrDefault(sparams, "Filter", "*")); - var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", string.Empty)); + var filter = new Filter(sparams.GetValueOrDefault("Filter", "*")); + var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty)); var provided = 0; @@ -435,9 +418,9 @@ namespace Emby.Dlna.ContentDirectory /// Builds the response to the "X_BrowseByLetter request. /// /// The . - /// The . + /// The method parameters. /// The device id. - private void HandleXBrowseByLetter(XmlWriter xmlWriter, IDictionary sparams, string deviceId) + private void HandleXBrowseByLetter(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId) { // TODO: Implement this method HandleSearch(xmlWriter, sparams, deviceId); @@ -447,13 +430,13 @@ namespace Emby.Dlna.ContentDirectory /// Builds a response to the "Search" request. /// /// The xmlWriter. - /// The sparams. + /// The method parameters. /// The deviceId. - private void HandleSearch(XmlWriter xmlWriter, IDictionary sparams, string deviceId) + private void HandleSearch(XmlWriter xmlWriter, IReadOnlyDictionary sparams, string deviceId) { - var searchCriteria = new SearchCriteria(GetValueOrDefault(sparams, "SearchCriteria", string.Empty)); - var sortCriteria = new SortCriteria(GetValueOrDefault(sparams, "SortCriteria", string.Empty)); - var filter = new Filter(GetValueOrDefault(sparams, "Filter", "*")); + var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", string.Empty)); + var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", string.Empty)); + var filter = new Filter(sparams.GetValueOrDefault("Filter", "*")); // sort example: dc:title, dc:date diff --git a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs index 464f71a6f1..d8fb127420 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/ControlHandler.cs @@ -24,7 +24,7 @@ namespace Emby.Dlna.MediaReceiverRegistrar } /// - protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter) + protected override void WriteResult(string methodName, IReadOnlyDictionary methodParams, XmlWriter xmlWriter) { if (string.Equals(methodName, "IsAuthorized", StringComparison.OrdinalIgnoreCase)) { diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index 8d2486fee6..fda8346f9e 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -210,7 +210,7 @@ namespace Emby.Dlna.Service } } - protected abstract void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter); + protected abstract void WriteResult(string methodName, IReadOnlyDictionary methodParams, XmlWriter xmlWriter); private void LogRequest(ControlRequest request) { diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 732bfd94dc..e8b5f4fe71 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -127,7 +127,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV { if (child.IsDirectory) { - if (IsSeasonFolder(child.FullName, isTvContentType, libraryManager)) + if (IsSeasonFolder(child.FullName, isTvContentType)) { logger.LogDebug("{Path} is a series because of season folder {Dir}.", path, child.FullName); return true; @@ -160,24 +160,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return false; } - /// - /// Determines whether [is place holder] [the specified path]. - /// - /// The path. - /// true if [is place holder] [the specified path]; otherwise, false. - /// path - private static bool IsVideoPlaceHolder(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(nameof(path)); - } - - var extension = Path.GetExtension(path); - - return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase); - } - /// /// Determines whether [is season folder] [the specified path]. /// @@ -185,7 +167,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// if set to true [is tv content type]. /// The library manager. /// true if [is season folder] [the specified path]; otherwise, false. - private static bool IsSeasonFolder(string path, bool isTvContentType, ILibraryManager libraryManager) + private static bool IsSeasonFolder(string path, bool isTvContentType) { var seasonNumber = SeasonPathParser.Parse(path, isTvContentType, isTvContentType).SeasonNumber; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs index 463d0ed0a3..8c27ca76e3 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs @@ -9,55 +9,44 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV internal class EpgChannelData { + + private readonly Dictionary _channelsById; + + private readonly Dictionary _channelsByNumber; + + private readonly Dictionary _channelsByName; + public EpgChannelData(IEnumerable channels) { - ChannelsById = new Dictionary(StringComparer.OrdinalIgnoreCase); - ChannelsByNumber = new Dictionary(StringComparer.OrdinalIgnoreCase); - ChannelsByName = new Dictionary(StringComparer.OrdinalIgnoreCase); + _channelsById = new Dictionary(StringComparer.OrdinalIgnoreCase); + _channelsByNumber = new Dictionary(StringComparer.OrdinalIgnoreCase); + _channelsByName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var channel in channels) { - ChannelsById[channel.Id] = channel; + _channelsById[channel.Id] = channel; if (!string.IsNullOrEmpty(channel.Number)) { - ChannelsByNumber[channel.Number] = channel; + _channelsByNumber[channel.Number] = channel; } var normalizedName = NormalizeName(channel.Name ?? string.Empty); if (!string.IsNullOrWhiteSpace(normalizedName)) { - ChannelsByName[normalizedName] = channel; + _channelsByName[normalizedName] = channel; } } } - private Dictionary ChannelsById { get; set; } - - private Dictionary ChannelsByNumber { get; set; } - - private Dictionary ChannelsByName { get; set; } - public ChannelInfo GetChannelById(string id) - { - ChannelsById.TryGetValue(id, out var result); - - return result; - } + => _channelsById.GetValueOrDefault(id); public ChannelInfo GetChannelByNumber(string number) - { - ChannelsByNumber.TryGetValue(number, out var result); - - return result; - } + => _channelsByNumber.GetValueOrDefault(number); public ChannelInfo GetChannelByName(string name) - { - ChannelsByName.TryGetValue(name, out var result); - - return result; - } + => _channelsByName.GetValueOrDefault(name); public static string NormalizeName(string value) { From 21e7ceae8e15e19bdb111e51aba41e6a3ac3333d Mon Sep 17 00:00:00 2001 From: Max Rumpf Date: Thu, 1 Apr 2021 19:18:14 +0200 Subject: [PATCH 1385/1930] StreamBuilder tweaks (#5668) Co-authored-by: Cody Robibero --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 33 ++++++++++++------------ 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index bf33691c77..8299059a5e 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -674,7 +674,7 @@ namespace MediaBrowser.Model.Dlna var videoStream = item.VideoStream; - // TODO: This doesn't accout for situation of device being able to handle media bitrate, but wifi connection not fast enough + // TODO: This doesn't account for situations where the device is able to handle the media's bitrate, but the connection isn't fast enough var directPlayEligibilityResult = IsEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options, true) ?? 0, subtitleStream, options, PlayMethod.DirectPlay); var directStreamEligibilityResult = IsEligibleForDirectPlay(item, options.GetMaxBitrate(false) ?? 0, subtitleStream, options, PlayMethod.DirectStream); bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1); @@ -1017,14 +1017,15 @@ namespace MediaBrowser.Model.Dlna } DeviceProfile profile = options.Profile; + string container = mediaSource.Container; // See if it can be direct played DirectPlayProfile directPlay = null; - foreach (var i in profile.DirectPlayProfiles) + foreach (var p in profile.DirectPlayProfiles) { - if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream)) + if (p.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(p, container, videoStream, audioStream)) { - directPlay = i; + directPlay = p; break; } } @@ -1032,23 +1033,23 @@ namespace MediaBrowser.Model.Dlna if (directPlay == null) { _logger.LogInformation( - "Profile: {0}, No video direct play profiles found for {1} with codec {2}", - profile?.Name ?? "Unknown Profile", - mediaSource?.Path ?? "Unknown path", - videoStream?.Codec ?? "Unknown codec"); + "Container: {Container}, Video: {Video}, Audio: {Audio} cannot be direct played by profile: {Profile} for path: {Path}", + container, + videoStream?.Codec ?? "no video", + audioStream?.Codec ?? "no audio", + profile.Name ?? "unknown profile", + mediaSource.Path ?? "unknown path"); return (null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles)); } - string container = mediaSource.Container; - var conditions = new List(); - foreach (var i in profile.ContainerProfiles) + foreach (var p in profile.ContainerProfiles) { - if (i.Type == DlnaProfileType.Video - && i.ContainsContainer(container)) + if (p.Type == DlnaProfileType.Video + && p.ContainsContainer(container)) { - foreach (var c in i.Conditions) + foreach (var c in p.Conditions) { conditions.Add(c); } @@ -1896,10 +1897,10 @@ namespace MediaBrowser.Model.Dlna return true; } - private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream) + private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, string container, MediaStream videoStream, MediaStream audioStream) { // Check container type - if (!profile.SupportsContainer(item.Container)) + if (!profile.SupportsContainer(container)) { return false; } From c533b204961b8fe19272b31b5fb5473be0eb801b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 1 Apr 2021 19:39:00 +0200 Subject: [PATCH 1386/1930] Remove ManagedFileSystem.IsRootPath `Path.IsPathRooted` should be used instead --- .../IO/ManagedFileSystem.cs | 32 ++++++------------- MediaBrowser.Model/IO/IFileSystem.cs | 7 ---- 2 files changed, 9 insertions(+), 30 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index c0e757543d..679795dd2c 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -55,7 +55,7 @@ namespace Emby.Server.Implementations.IO } var extension = Path.GetExtension(filename); - return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase)); + return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); } /// @@ -487,26 +487,9 @@ namespace Emby.Server.Implementations.IO throw new ArgumentNullException(nameof(path)); } - var separatorChar = Path.DirectorySeparatorChar; - - return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1; - } - - public virtual bool IsRootPath(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException(nameof(path)); - } - - var parent = Path.GetDirectoryName(path); - - if (!string.IsNullOrEmpty(parent)) - { - return false; - } - - return true; + return path.Contains( + Path.TrimEndingDirectorySeparator(parentPath) + Path.DirectorySeparatorChar, + _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } public virtual string NormalizePath(string path) @@ -521,7 +504,7 @@ namespace Emby.Server.Implementations.IO return path; } - return path.TrimEnd(Path.DirectorySeparatorChar); + return Path.TrimEndingDirectorySeparator(path); } public virtual bool AreEqual(string path1, string path2) @@ -536,7 +519,10 @@ namespace Emby.Server.Implementations.IO return false; } - return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase); + return string.Equals( + NormalizePath(path1), + NormalizePath(path2), + _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } public virtual string GetFileNameWithoutExtension(FileSystemMetadata info) diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index ef08ecec66..e5c26430a8 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -117,13 +117,6 @@ namespace MediaBrowser.Model.IO /// true if [contains sub path] [the specified parent path]; otherwise, false. bool ContainsSubPath(string parentPath, string path); - /// - /// Determines whether [is root path] [the specified path]. - /// - /// The path. - /// true if [is root path] [the specified path]; otherwise, false. - bool IsRootPath(string path); - /// /// Normalizes the path. /// From a0258618acc66b80e9f5cdd535a31baf12857fb0 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Thu, 1 Apr 2021 21:24:34 +0200 Subject: [PATCH 1387/1930] Update Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs Co-authored-by: Claus Vium --- .../Library/Resolvers/TV/SeriesResolver.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index e8b5f4fe71..4a9d2cf8ca 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -165,7 +165,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// /// The path. /// if set to true [is tv content type]. - /// The library manager. /// true if [is season folder] [the specified path]; otherwise, false. private static bool IsSeasonFolder(string path, bool isTvContentType) { From d9a50cb510cfe7b5a97def22fe3bc090cafc0638 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 2 Apr 2021 19:06:38 +0100 Subject: [PATCH 1388/1930] Various DLNA Optimizations --- Emby.Dlna/Didl/DidlBuilder.cs | 9 +- Emby.Dlna/PlayTo/PlayToController.cs | 8 +- Jellyfin.Api/Helpers/StreamingHelpers.cs | 5 +- .../Dlna/ContentFeatureBuilder.cs | 85 +++++++++---------- .../Dlna/MediaFormatProfileResolver.cs | 37 ++++---- 5 files changed, 68 insertions(+), 76 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 8b50d47fbd..66ae07329e 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -208,7 +208,8 @@ namespace Emby.Dlna.Didl var targetWidth = streamInfo.TargetWidth; var targetHeight = streamInfo.TargetHeight; - var contentFeatureList = new ContentFeatureBuilder(_profile).BuildVideoHeader( + var contentFeatureList = ContentFeatureBuilder.BuildVideoHeader( + _profile, streamInfo.Container, streamInfo.TargetVideoCodec.FirstOrDefault(), streamInfo.TargetAudioCodec.FirstOrDefault(), @@ -599,7 +600,8 @@ namespace Emby.Dlna.Didl ? MimeTypes.GetMimeType(filename) : mediaProfile.MimeType; - var contentFeatures = new ContentFeatureBuilder(_profile).BuildAudioHeader( + var contentFeatures = ContentFeatureBuilder.BuildAudioHeader( + _profile, streamInfo.Container, streamInfo.TargetAudioCodec.FirstOrDefault(), targetAudioBitrate, @@ -1033,8 +1035,7 @@ namespace Emby.Dlna.Didl var width = albumartUrlInfo.width ?? maxWidth; var height = albumartUrlInfo.height ?? maxHeight; - var contentFeatures = new ContentFeatureBuilder(_profile) - .BuildImageHeader(format, width, height, imageInfo.IsDirectStream, org_Pn); + var contentFeatures = ContentFeatureBuilder.BuildImageHeader(_profile, format, width, height, imageInfo.IsDirectStream, org_Pn); writer.WriteAttributeString( "protocolInfo", diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index e4923b9eb0..c6fdcd8eaf 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -499,8 +499,8 @@ namespace Emby.Dlna.PlayTo if (streamInfo.MediaType == DlnaProfileType.Audio) { - return new ContentFeatureBuilder(profile) - .BuildAudioHeader( + return ContentFeatureBuilder.BuildAudioHeader( + profile, streamInfo.Container, streamInfo.TargetAudioCodec.FirstOrDefault(), streamInfo.TargetAudioBitrate, @@ -514,8 +514,8 @@ namespace Emby.Dlna.PlayTo if (streamInfo.MediaType == DlnaProfileType.Video) { - var list = new ContentFeatureBuilder(profile) - .BuildVideoHeader( + var list = ContentFeatureBuilder.BuildVideoHeader( + profile, streamInfo.Container, streamInfo.TargetVideoCodec.FirstOrDefault(), streamInfo.TargetAudioCodec.FirstOrDefault(), diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index d20a02cf5d..23f90052a0 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -306,7 +306,8 @@ namespace Jellyfin.Api.Helpers if (!state.IsVideoRequest) { - responseHeaders.Add("contentFeatures.dlna.org", new ContentFeatureBuilder(profile).BuildAudioHeader( + responseHeaders.Add("contentFeatures.dlna.org", ContentFeatureBuilder.BuildAudioHeader( + profile, state.OutputContainer, audioCodec, state.OutputAudioBitrate, @@ -323,7 +324,7 @@ namespace Jellyfin.Api.Helpers responseHeaders.Add( "contentFeatures.dlna.org", - new ContentFeatureBuilder(profile).BuildVideoHeader(state.OutputContainer, videoCodec, audioCodec, state.OutputWidth, state.OutputHeight, state.TargetVideoBitDepth, state.OutputVideoBitrate, state.TargetTimestamp, isStaticallyStreamed, state.RunTimeTicks, state.TargetVideoProfile, state.TargetVideoLevel, state.TargetFramerate, state.TargetPacketLength, state.TranscodeSeekInfo, state.IsTargetAnamorphic, state.IsTargetInterlaced, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, state.TargetVideoCodecTag, state.IsTargetAVC).FirstOrDefault() ?? string.Empty); + ContentFeatureBuilder.BuildVideoHeader(profile, state.OutputContainer, videoCodec, audioCodec, state.OutputWidth, state.OutputHeight, state.TargetVideoBitDepth, state.OutputVideoBitrate, state.TargetTimestamp, isStaticallyStreamed, state.RunTimeTicks, state.TargetVideoProfile, state.TargetVideoLevel, state.TargetFramerate, state.TargetPacketLength, state.TranscodeSeekInfo, state.IsTargetAnamorphic, state.IsTargetInterlaced, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, state.TargetVideoCodecTag, state.IsTargetAVC).FirstOrDefault() ?? string.Empty); } } diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index ec106f1054..600a441570 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -10,14 +10,8 @@ namespace MediaBrowser.Model.Dlna { public class ContentFeatureBuilder { - private readonly DeviceProfile _profile; - - public ContentFeatureBuilder(DeviceProfile profile) - { - _profile = profile; - } - - public string BuildImageHeader( + public static string BuildImageHeader( + DeviceProfile profile, string container, int? width, int? height, @@ -38,27 +32,31 @@ namespace MediaBrowser.Model.Dlna ";DLNA.ORG_FLAGS={0}", DlnaMaps.FlagsToString(flagValue)); - ResponseProfile mediaProfile = _profile.GetImageMediaProfile( - container, - width, - height); - if (string.IsNullOrEmpty(orgPn)) { + ResponseProfile mediaProfile = profile.GetImageMediaProfile( + container, + width, + height); + orgPn = mediaProfile?.OrgPn; + + if (string.IsNullOrEmpty(orgPn)) + { + orgPn = GetImageOrgPnValue(container, width, height); + } } if (string.IsNullOrEmpty(orgPn)) { - orgPn = GetImageOrgPnValue(container, width, height); + return orgOp.TrimStart(';') + orgCi + dlnaflags; } - string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn; - - return (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';'); + return "DLNA.ORG_PN=" + orgPn + orgOp + orgCi + dlnaflags; } - public string BuildAudioHeader( + public static string BuildAudioHeader( + DeviceProfile profile, string container, string audioCodec, int? audioBitrate, @@ -94,7 +92,7 @@ namespace MediaBrowser.Model.Dlna ";DLNA.ORG_FLAGS={0}", DlnaMaps.FlagsToString(flagValue)); - ResponseProfile mediaProfile = _profile.GetAudioMediaProfile( + ResponseProfile mediaProfile = profile.GetAudioMediaProfile( container, audioCodec, audioChannels, @@ -109,12 +107,16 @@ namespace MediaBrowser.Model.Dlna orgPn = GetAudioOrgPnValue(container, audioBitrate, audioSampleRate, audioChannels); } - string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn; + if (string.IsNullOrEmpty(orgPn)) + { + return orgOp.TrimStart(';') + orgCi + dlnaflags; + } - return (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';'); + return "DLNA.ORG_PN=" + orgPn + orgOp + orgCi + dlnaflags; } - public List BuildVideoHeader( + public static List BuildVideoHeader( + DeviceProfile profile, string container, string videoCodec, string audioCodec, @@ -163,7 +165,7 @@ namespace MediaBrowser.Model.Dlna ";DLNA.ORG_FLAGS={0}", DlnaMaps.FlagsToString(flagValue)); - ResponseProfile mediaProfile = _profile.GetVideoMediaProfile( + ResponseProfile mediaProfile = profile.GetVideoMediaProfile( container, audioCodec, videoCodec, @@ -192,9 +194,9 @@ namespace MediaBrowser.Model.Dlna } else { - foreach (string s in GetVideoOrgPnValue(container, videoCodec, audioCodec, width, height, timestamp)) + foreach (var s in GetVideoOrgPnValue(container, videoCodec, audioCodec, width, height, timestamp)) { - orgPnValues.Add(s); + orgPnValues.Add(s.ToString()); break; } } @@ -203,20 +205,20 @@ namespace MediaBrowser.Model.Dlna foreach (string orgPn in orgPnValues) { - string contentFeatures = string.IsNullOrEmpty(orgPn) ? string.Empty : "DLNA.ORG_PN=" + orgPn; - - var value = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';'); - - contentFeatureList.Add(value); + if (string.IsNullOrEmpty(orgPn)) + { + contentFeatureList.Add(orgOp.TrimStart(';') + orgCi + dlnaflags); + continue; + } + else + { + contentFeatureList.Add("DLNA.ORG_PN=" + orgPn + orgCi + dlnaflags); + } } if (orgPnValues.Count == 0) { - string contentFeatures = string.Empty; - - var value = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';'); - - contentFeatureList.Add(value); + contentFeatureList.Add(orgOp.TrimStart(';') + orgCi + dlnaflags); } return contentFeatureList; @@ -224,19 +226,14 @@ namespace MediaBrowser.Model.Dlna private static string GetImageOrgPnValue(string container, int? width, int? height) { - MediaFormatProfile? format = new MediaFormatProfileResolver() - .ResolveImageFormat( - container, - width, - height); + MediaFormatProfile? format = MediaFormatProfileResolver.ResolveImageFormat(container, width, height); return format.HasValue ? format.Value.ToString() : null; } private static string GetAudioOrgPnValue(string container, int? audioBitrate, int? audioSampleRate, int? audioChannels) { - MediaFormatProfile? format = new MediaFormatProfileResolver() - .ResolveAudioFormat( + MediaFormatProfile? format = MediaFormatProfileResolver.ResolveAudioFormat( container, audioBitrate, audioSampleRate, @@ -245,9 +242,9 @@ namespace MediaBrowser.Model.Dlna return format.HasValue ? format.Value.ToString() : null; } - private static string[] GetVideoOrgPnValue(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestamp) + private static MediaFormatProfile[] GetVideoOrgPnValue(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestamp) { - return new MediaFormatProfileResolver().ResolveVideoFormat(container, videoCodec, audioCodec, width, height, timestamp); + return MediaFormatProfileResolver.ResolveVideoFormat(container, videoCodec, audioCodec, width, height, timestamp); } } } diff --git a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs index f61b8d59e8..7ce248509c 100644 --- a/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs +++ b/MediaBrowser.Model/Dlna/MediaFormatProfileResolver.cs @@ -9,16 +9,9 @@ using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Model.Dlna { - public class MediaFormatProfileResolver + public static class MediaFormatProfileResolver { - public string[] ResolveVideoFormat(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) - { - return ResolveVideoFormatInternal(container, videoCodec, audioCodec, width, height, timestampType) - .Select(i => i.ToString()) - .ToArray(); - } - - private MediaFormatProfile[] ResolveVideoFormatInternal(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) + public static MediaFormatProfile[] ResolveVideoFormat(string container, string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) { if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase)) { @@ -84,7 +77,7 @@ namespace MediaBrowser.Model.Dlna return Array.Empty(); } - private MediaFormatProfile[] ResolveVideoMPEG2TSFormat(string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) + private static MediaFormatProfile[] ResolveVideoMPEG2TSFormat(string videoCodec, string audioCodec, int? width, int? height, TransportStreamTimestamp timestampType) { string suffix = string.Empty; @@ -209,12 +202,12 @@ namespace MediaBrowser.Model.Dlna return Array.Empty(); } - private MediaFormatProfile ValueOf(string value) + private static MediaFormatProfile ValueOf(string value) { return (MediaFormatProfile)Enum.Parse(typeof(MediaFormatProfile), value, true); } - private MediaFormatProfile? ResolveVideoMP4Format(string videoCodec, string audioCodec, int? width, int? height) + private static MediaFormatProfile? ResolveVideoMP4Format(string videoCodec, string audioCodec, int? width, int? height) { if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { @@ -287,7 +280,7 @@ namespace MediaBrowser.Model.Dlna return null; } - private MediaFormatProfile? ResolveVideo3GPFormat(string videoCodec, string audioCodec) + private static MediaFormatProfile? ResolveVideo3GPFormat(string videoCodec, string audioCodec) { if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) { @@ -317,7 +310,7 @@ namespace MediaBrowser.Model.Dlna return null; } - private MediaFormatProfile? ResolveVideoASFFormat(string videoCodec, string audioCodec, int? width, int? height) + private static MediaFormatProfile? ResolveVideoASFFormat(string videoCodec, string audioCodec, int? width, int? height) { if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase) && (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "wmapro", StringComparison.OrdinalIgnoreCase))) @@ -371,7 +364,7 @@ namespace MediaBrowser.Model.Dlna return null; } - public MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels) + public static MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels) { if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase)) { @@ -413,7 +406,7 @@ namespace MediaBrowser.Model.Dlna return null; } - private MediaFormatProfile ResolveAudioASFFormat(int? bitrate) + private static MediaFormatProfile ResolveAudioASFFormat(int? bitrate) { if (bitrate.HasValue && bitrate.Value <= 193) { @@ -423,7 +416,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.WMA_FULL; } - private MediaFormatProfile? ResolveAudioLPCMFormat(int? frequency, int? channels) + private static MediaFormatProfile? ResolveAudioLPCMFormat(int? frequency, int? channels) { if (frequency.HasValue && channels.HasValue) { @@ -453,7 +446,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.LPCM16_48_STEREO; } - private MediaFormatProfile ResolveAudioMP4Format(int? bitrate) + private static MediaFormatProfile ResolveAudioMP4Format(int? bitrate) { if (bitrate.HasValue && bitrate.Value <= 320) { @@ -463,7 +456,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.AAC_ISO; } - private MediaFormatProfile ResolveAudioADTSFormat(int? bitrate) + private static MediaFormatProfile ResolveAudioADTSFormat(int? bitrate) { if (bitrate.HasValue && bitrate.Value <= 320) { @@ -473,7 +466,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.AAC_ADTS; } - public MediaFormatProfile? ResolveImageFormat(string container, int? width, int? height) + public static MediaFormatProfile? ResolveImageFormat(string container, int? width, int? height) { if (string.Equals(container, "jpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "jpg", StringComparison.OrdinalIgnoreCase)) @@ -499,7 +492,7 @@ namespace MediaBrowser.Model.Dlna return null; } - private MediaFormatProfile ResolveImageJPGFormat(int? width, int? height) + private static MediaFormatProfile ResolveImageJPGFormat(int? width, int? height) { if (width.HasValue && height.HasValue) { @@ -524,7 +517,7 @@ namespace MediaBrowser.Model.Dlna return MediaFormatProfile.JPEG_SM; } - private MediaFormatProfile ResolveImagePNGFormat(int? width, int? height) + private static MediaFormatProfile ResolveImagePNGFormat(int? width, int? height) { if (width.HasValue && height.HasValue) { From 820a3730161b98d5510847feee684797c23a3510 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Apr 2021 22:27:11 +0000 Subject: [PATCH 1389/1930] Bump Microsoft.Extensions.Diagnostics.HealthChecks from 5.0.3 to 5.0.4 Bumps [Microsoft.Extensions.Diagnostics.HealthChecks](https://github.com/dotnet/aspnetcore) from 5.0.3 to 5.0.4. - [Release notes](https://github.com/dotnet/aspnetcore/releases) - [Commits](https://github.com/dotnet/aspnetcore/compare/v5.0.3...v5.0.4) Signed-off-by: dependabot[bot] --- Jellyfin.Server/Jellyfin.Server.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index b7406d849a..e7f83aff16 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -37,7 +37,7 @@ - + From 7c7020532666714dc22ac87356b059c6d4c5520c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 2 Apr 2021 22:42:12 +0000 Subject: [PATCH 1390/1930] Bump Microsoft.NET.Test.Sdk from 16.9.1 to 16.9.4 Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.9.1 to 16.9.4. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.9.1...v16.9.4) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj | 2 +- .../Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj | 2 +- tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj | 2 +- .../Jellyfin.MediaEncoding.Tests.csproj | 2 +- tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj | 2 +- tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj | 2 +- .../Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- .../Jellyfin.XbmcMetadata.Tests.csproj | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 577b61d02a..57277be150 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -20,7 +20,7 @@ - + diff --git a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj index 017a67e9f9..8018b29663 100644 --- a/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj +++ b/tests/Jellyfin.Common.Tests/Jellyfin.Common.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj index c56ccb3653..ad16276989 100644 --- a/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj +++ b/tests/Jellyfin.Controller.Tests/Jellyfin.Controller.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 5d52f94c02..c2c0dca1bb 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -10,7 +10,7 @@ - + diff --git a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj index 4cc1d37ee9..8321d02552 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj +++ b/tests/Jellyfin.MediaEncoding.Tests/Jellyfin.MediaEncoding.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj index 0c7e262f59..c5b51ef766 100644 --- a/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj +++ b/tests/Jellyfin.Model.Tests/Jellyfin.Model.Tests.csproj @@ -10,7 +10,7 @@ - + diff --git a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj index cc12a99a61..ebb134fc3c 100644 --- a/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj +++ b/tests/Jellyfin.Naming.Tests/Jellyfin.Naming.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj index a76c0e9a06..d5268facc9 100644 --- a/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj +++ b/tests/Jellyfin.Networking.Tests/Jellyfin.Networking.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index c3c258b680..fe26ec3ae6 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -24,7 +24,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 34cef90050..079021e61b 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -14,7 +14,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index a310b0ea96..3ba49ff6a2 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj index 9380fe2af4..4132205c3f 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj +++ b/tests/Jellyfin.XbmcMetadata.Tests/Jellyfin.XbmcMetadata.Tests.csproj @@ -16,7 +16,7 @@ - + From 0a00a73fec7822a1a10b3fc48494108651ab1a98 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 3 Apr 2021 01:46:31 +0200 Subject: [PATCH 1391/1930] Remove useless null check --- .../Json/Converters/JsonCommaDelimitedArrayConverter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index d9f6519e98..2ec702165d 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -26,8 +26,8 @@ namespace MediaBrowser.Common.Json.Converters { if (reader.TokenType == JsonTokenType.String) { - var stringEntries = reader.GetString()?.Split(',', StringSplitOptions.RemoveEmptyEntries); - if (stringEntries == null || stringEntries.Length == 0) + var stringEntries = reader.GetString().Split(',', StringSplitOptions.RemoveEmptyEntries); + if (stringEntries.Length == 0) { return Array.Empty(); } From 31d1dbfda630e45a8884f1a10d172f8cc83df9b0 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 3 Apr 2021 06:54:09 -0600 Subject: [PATCH 1392/1930] Add SessionDiscoveryInfo to generated api-docs --- .../Extensions/ApiServiceCollectionExtensions.cs | 2 +- .../{WebsocketModelFilter.cs => AdditionalModelFilter.cs} | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) rename Jellyfin.Server/Filters/{WebsocketModelFilter.cs => AdditionalModelFilter.cs} (82%) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index d26ac251c0..233eab21b6 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -319,7 +319,7 @@ namespace Jellyfin.Server.Extensions c.OperationFilter(); c.OperationFilter(); c.OperationFilter(); - c.DocumentFilter(); + c.DocumentFilter(); }); } diff --git a/Jellyfin.Server/Filters/WebsocketModelFilter.cs b/Jellyfin.Server/Filters/AdditionalModelFilter.cs similarity index 82% rename from Jellyfin.Server/Filters/WebsocketModelFilter.cs rename to Jellyfin.Server/Filters/AdditionalModelFilter.cs index 38afb201db..87a59e0b45 100644 --- a/Jellyfin.Server/Filters/WebsocketModelFilter.cs +++ b/Jellyfin.Server/Filters/AdditionalModelFilter.cs @@ -1,5 +1,6 @@ using MediaBrowser.Common.Plugins; using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.ApiClient; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Session; using MediaBrowser.Model.SyncPlay; @@ -9,9 +10,9 @@ using Swashbuckle.AspNetCore.SwaggerGen; namespace Jellyfin.Server.Filters { /// - /// Add models used in websocket messaging. + /// Add models not directly used by the API, but used for discovery and websockets. /// - public class WebsocketModelFilter : IDocumentFilter + public class AdditionalModelFilter : IDocumentFilter { /// public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) @@ -27,6 +28,7 @@ namespace Jellyfin.Server.Filters context.SchemaGenerator.GenerateSchema(typeof(GroupUpdate), context.SchemaRepository); context.SchemaGenerator.GenerateSchema(typeof(SessionMessageType), context.SchemaRepository); + context.SchemaGenerator.GenerateSchema(typeof(ServerDiscoveryInfo), context.SchemaRepository); } } } From 36da7a06d7f433d88ef94b770036815847e4dd89 Mon Sep 17 00:00:00 2001 From: Dmitry Lyzo <56478732+dmitrylyzo@users.noreply.github.com> Date: Sun, 4 Apr 2021 02:09:57 +0300 Subject: [PATCH 1393/1930] Less negation Co-authored-by: Bond-009 --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 167fc984e6..b7327bc12b 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -514,7 +514,7 @@ namespace MediaBrowser.Model.Dlna private static List GetTranscodeReasonsFromDirectPlayProfile(MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream, IEnumerable directPlayProfiles) { - var mediaType = videoStream != null ? DlnaProfileType.Video : DlnaProfileType.Audio; + var mediaType = videoStream == null ? DlnaProfileType.Audio : DlnaProfileType.Video; var containerSupported = false; var audioSupported = false; From 2ed0801be25921335b6509b6ebf9af61ad458409 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 4 Apr 2021 01:45:15 +0200 Subject: [PATCH 1394/1930] Fix possible nullref when `ProviderManager.SaveMetadata` gets called before `ProviderManager.AddParts` ``` Error Message: System.ArgumentNullException : Value cannot be null. (Parameter 'source') Stack Trace: at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate) at MediaBrowser.Providers.Manager.ProviderManager.SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable`1 savers) in D:\a\1\s\MediaBrowser.Providers\Manager\ProviderManager.cs:line 674 at MediaBrowser.Providers.Manager.ProviderManager.SaveMetadata(BaseItem item, ItemUpdateType updateType) in D:\a\1\s\MediaBrowser.Providers\Manager\ProviderManager.cs:line 655 at Emby.Server.Implementations.Library.LibraryManager.RunMetadataSavers(BaseItem item, ItemUpdateType updateReason) in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 2012 at Emby.Server.Implementations.Library.LibraryManager.UpdateItemsAsync(IReadOnlyList`1 items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 1970 at Emby.Server.Implementations.Library.LibraryManager.CreateRootFolder() in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 775 at Emby.Server.Implementations.Library.LibraryManager.get_RootFolder() in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 180 at Emby.Server.Implementations.IO.LibraryMonitor.Start() in D:\a\1\s\Emby.Server.Implementations\IO\LibraryMonitor.cs:line 135 at Emby.Server.Implementations.IO.LibraryMonitorStartup.RunAsync() in D:\a\1\s\Emby.Server.Implementations\IO\LibraryMonitorStartup.cs:line 26 at Emby.Server.Implementations.ApplicationHost.StartEntryPoints(IEnumerable`1 entryPoints, Boolean isBeforeStartup)+MoveNext() in D:\a\1\s\Emby.Server.Implementations\ApplicationHost.cs:line 541 at System.Threading.Tasks.Task.WhenAll(IEnumerable`1 tasks) at Emby.Server.Implementations.ApplicationHost.RunStartupTasksAsync(CancellationToken cancellationToken) in D:\a\1\s\Emby.Server.Implementations\ApplicationHost.cs:line 525 at Jellyfin.Server.Integration.Tests.JellyfinApplicationFactory.CreateServer(IWebHostBuilder builder) in D:\a\1\s\tests\Jellyfin.Server.Integration.Tests\JellyfinApplicationFactory.cs:line 101 at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer() at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient() at Jellyfin.Server.Integration.Tests.OpenApiSpecTests.GetSpec_ReturnsCorrectResponse() in D:\a\1\s\tests\Jellyfin.Server.Integration.Tests\OpenApiSpecTests.cs:line 26 --- End of stack trace from previous location --- ``` --- MediaBrowser.Controller/Providers/IProviderManager.cs | 7 +++++-- MediaBrowser.Providers/Manager/ProviderManager.cs | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 2f5b1d4a32..7bc56c82ad 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -91,8 +91,11 @@ namespace MediaBrowser.Controller.Providers /// /// Adds the metadata providers. /// - void AddParts(IEnumerable imageProviders, IEnumerable metadataServices, IEnumerable metadataProviders, - IEnumerable savers, + void AddParts( + IEnumerable imageProviders, + IEnumerable metadataServices, + IEnumerable metadataProviders, + IEnumerable metadataSavers, IEnumerable externalIds); /// diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index d581dd4341..b4b0b826f4 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -60,8 +60,8 @@ namespace MediaBrowser.Providers.Manager private IMetadataService[] _metadataServices = Array.Empty(); private IMetadataProvider[] _metadataProviders = Array.Empty(); - private IEnumerable _savers; - private IExternalId[] _externalIds; + private IMetadataSaver[] _savers = Array.Empty(); + private IExternalId[] _externalIds = Array.Empty(); private bool _isProcessingRefreshQueue; private bool _disposed; @@ -125,7 +125,7 @@ namespace MediaBrowser.Providers.Manager _externalIds = externalIds.OrderBy(i => i.ProviderName).ToArray(); _savers = metadataSavers - .Where(i => !(i is IConfigurableProvider configurable) || configurable.IsEnabled) + .Where(i => i is not IConfigurableProvider configurable || configurable.IsEnabled) .ToArray(); } From e0f513232b0b03135fa09fe39862c10982cb469e Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sun, 4 Apr 2021 14:58:20 +0200 Subject: [PATCH 1395/1930] Reduce nesting --- MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs index b2d4db894d..e65c16ee22 100644 --- a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs +++ b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs @@ -85,12 +85,14 @@ namespace MediaBrowser.MediaEncoding.Probing { var val = GetDictionaryValue(tags, key); - if (!string.IsNullOrEmpty(val)) + if (string.IsNullOrEmpty(val)) { - if (DateTime.TryParse(val, out var i)) - { - return i.ToUniversalTime(); - } + return null; + } + + if (DateTime.TryParse(val, out var i)) + { + return i.ToUniversalTime(); } return null; From 8d27e10cb696fb440ec7773aae69441d0651e64a Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sun, 4 Apr 2021 15:04:01 +0200 Subject: [PATCH 1396/1930] Interpret ffprobe date as UTC Currently, dates are parsed according to the local time, which results in potentially wrong data being stored in the database after normalizing to UTC - e.g. 2021-04-04 would be stored as '2021-04-03 22:00:00Z' and displayed in the UI as 03.04.2021. --- MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs index e65c16ee22..da37687e8f 100644 --- a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs +++ b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; namespace MediaBrowser.MediaEncoding.Probing { @@ -90,7 +91,7 @@ namespace MediaBrowser.MediaEncoding.Probing return null; } - if (DateTime.TryParse(val, out var i)) + if (DateTime.TryParse(val, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.AssumeUniversal, out var i)) { return i.ToUniversalTime(); } From 873ad72c1893e87d1f8a0a744ebfe53b87781521 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sun, 4 Apr 2021 15:08:08 +0200 Subject: [PATCH 1397/1930] Support MKV DATE_RELEASED tag for PremiereDate https://www.matroska.org/technical/tagging.html#temporal-information --- MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 75067315f9..a87104cd67 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -131,6 +131,7 @@ namespace MediaBrowser.MediaEncoding.Probing info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ?? + FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "date"); if (isAudio) From e6d487f7ea311c91c307138f4d38dbd25281f7cf Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 5 Apr 2021 01:53:00 +0200 Subject: [PATCH 1398/1930] Add test for ProbeResultNormalizer.GetMediaInfo --- .../Probing/ProbeResultNormalizerTests.cs | 56 ++++++++++++++ .../Test Data/Probing/some_matadata.json | 74 +++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs new file mode 100644 index 0000000000..69e2aa4372 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs @@ -0,0 +1,56 @@ +using System.IO; +using System.Text.Json; +using MediaBrowser.Common.Json; +using MediaBrowser.MediaEncoding.Probing; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.MediaInfo; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Jellyfin.MediaEncoding.Tests.Probing +{ + public class ProbeResultNormalizerTests + { + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; + private readonly ProbeResultNormalizer _probeResultNormalizer = new ProbeResultNormalizer(new NullLogger(), null); + + [Fact] + public void GetMediaInfo_MetaData_Success() + { + var bytes = File.ReadAllBytes("Test Data/Probing/some_matadata.json"); + var internalMediaInfoResult = JsonSerializer.Deserialize(bytes, _jsonOptions); + MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/some_matadata.mkv", MediaProtocol.File); + + Assert.Single(res.MediaStreams); + + Assert.NotNull(res.VideoStream); + Assert.Equal("4:3", res.VideoStream.AspectRatio); + Assert.Equal(25f, res.VideoStream.AverageFrameRate); + Assert.Equal(8, res.VideoStream.BitDepth); + Assert.Equal(69432, res.VideoStream.BitRate); + Assert.Equal("h264", res.VideoStream.Codec); + Assert.Equal("1/50", res.VideoStream.CodecTimeBase); + Assert.Equal(240, res.VideoStream.Height); + Assert.Equal(320, res.VideoStream.Width); + Assert.Equal(0, res.VideoStream.Index); + Assert.False(res.VideoStream.IsAnamorphic); + Assert.True(res.VideoStream.IsAVC); + Assert.True(res.VideoStream.IsDefault); + Assert.False(res.VideoStream.IsExternal); + Assert.False(res.VideoStream.IsForced); + Assert.False(res.VideoStream.IsInterlaced); + Assert.False(res.VideoStream.IsTextSubtitleStream); + Assert.Equal(13d, res.VideoStream.Level); + Assert.Equal("4", res.VideoStream.NalLengthSize); + Assert.Equal("yuv444p", res.VideoStream.PixelFormat); + Assert.Equal("High 4:4:4 Predictive", res.VideoStream.Profile); + Assert.Equal(25f, res.VideoStream.RealFrameRate); + Assert.Equal(1, res.VideoStream.RefFrames); + Assert.Equal("1/1000", res.VideoStream.TimeBase); + Assert.Equal(MediaStreamType.Video, res.VideoStream.Type); + + Assert.Empty(res.Chapters); + Assert.Equal("Just color bars", res.Overview); + } + } +} diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json new file mode 100644 index 0000000000..720fc5c8fa --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json @@ -0,0 +1,74 @@ +{ + "streams": [ + { + "index": 0, + "codec_name": "h264", + "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", + "profile": "High 4:4:4 Predictive", + "codec_type": "video", + "codec_time_base": "1/50", + "codec_tag_string": "[0][0][0][0]", + "codec_tag": "0x0000", + "width": 320, + "height": 240, + "coded_width": 320, + "coded_height": 240, + "closed_captions": 0, + "has_b_frames": 2, + "sample_aspect_ratio": "1:1", + "display_aspect_ratio": "4:3", + "pix_fmt": "yuv444p", + "level": 13, + "chroma_location": "left", + "field_order": "progressive", + "refs": 1, + "is_avc": "true", + "nal_length_size": "4", + "r_frame_rate": "25/1", + "avg_frame_rate": "25/1", + "time_base": "1/1000", + "start_pts": 0, + "start_time": "0.000000", + "bits_per_raw_sample": "8", + "disposition": { + "default": 1, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + }, + "tags": { + "ENCODER": "Lavc57.107.100 libx264", + "DURATION": "00:00:01.000000000" + } + } + ], + "chapters": [ + + ], + "format": { + "filename": "some_metadata.mkv", + "nb_streams": 1, + "nb_programs": 0, + "format_name": "matroska,webm", + "format_long_name": "Matroska / WebM", + "start_time": "0.000000", + "duration": "1.000000", + "size": "8679", + "bit_rate": "69432", + "probe_score": 100, + "tags": { + "DESCRIPTION": "Just color bars", + "ARCHIVAL": "yes", + "PRESERVE_THIS": "okay", + "ENCODER": "Lavf57.83.100" + } + } +} From 14d0acf28572c6b5f5ecac6728b7a8184683b5f2 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 5 Apr 2021 15:12:47 +0200 Subject: [PATCH 1399/1930] add simple auth handling to websocketmanager --- Emby.Server.Implementations/HttpServer/WebSocketManager.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index d6cf6233e4..1bee1ac310 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -14,15 +14,18 @@ namespace Emby.Server.Implementations.HttpServer public class WebSocketManager : IWebSocketManager { private readonly IWebSocketListener[] _webSocketListeners; + private readonly IAuthService _authService; private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; public WebSocketManager( + IAuthService authService, IEnumerable webSocketListeners, ILogger logger, ILoggerFactory loggerFactory) { _webSocketListeners = webSocketListeners.ToArray(); + _authService = authService; _logger = logger; _loggerFactory = loggerFactory; } @@ -30,6 +33,7 @@ namespace Emby.Server.Implementations.HttpServer /// public async Task WebSocketRequestHandler(HttpContext context) { + _ = _authService.Authenticate(context.Request); try { _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress); From 24ac8a12233936955e31a409c1a131473041846e Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sun, 4 Apr 2021 23:34:29 +0200 Subject: [PATCH 1400/1930] Improve metadata probing to better support music videos --- .../Probing/ProbeResultNormalizer.cs | 95 +++++++++++-------- MediaBrowser.Model/MediaInfo/MediaInfo.cs | 2 + .../MediaInfo/FFProbeAudioInfo.cs | 5 + .../MediaInfo/FFProbeVideoInfo.cs | 11 +++ 4 files changed, 74 insertions(+), 39 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index a87104cd67..22624dfd7d 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -121,19 +121,67 @@ namespace MediaBrowser.MediaEncoding.Probing { info.Name = title; } + else + { + title = FFProbeHelpers.GetDictionaryValue(tags, "title-eng"); + if (!string.IsNullOrWhiteSpace(title)) + { + info.Name = title; + } + } + + var titleSort = FFProbeHelpers.GetDictionaryValue(tags, "titlesort"); + if (!string.IsNullOrWhiteSpace(titleSort)) + { + info.ForcedSortName = titleSort; + } info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort"); info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number"); info.ShowName = FFProbeHelpers.GetDictionaryValue(tags, "show_name"); info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date"); - // Several different forms of retaildate - info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ?? + // Several different forms of retail/premiere date + info.PremiereDate = + FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "date"); + // Set common metadata for music (audio) and music videos (video) + info.Album = FFProbeHelpers.GetDictionaryValue(tags, "album"); + + var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists"); + + if (!string.IsNullOrWhiteSpace(artists)) + { + info.Artists = SplitArtists(artists, new[] { '/', ';' }, false) + .DistinctNames() + .ToArray(); + } + else + { + var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist"); + if (string.IsNullOrWhiteSpace(artist)) + { + info.Artists = Array.Empty(); + } + else + { + info.Artists = SplitArtists(artist, _nameDelimiters, true) + .DistinctNames() + .ToArray(); + } + } + + // If we don't have a ProductionYear try and get it from PremiereDate + if (!info.ProductionYear.HasValue && info.PremiereDate.HasValue) + { + info.ProductionYear = info.PremiereDate.Value.Year; + } + + // Set mediaType-specific metadata if (isAudio) { SetAudioRuntimeTicks(data, info); @@ -1076,13 +1124,13 @@ namespace MediaBrowser.MediaEncoding.Probing private void SetAudioInfoFromTags(MediaInfo audio, Dictionary tags) { - var peoples = new List(); + var people = new List(); var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer"); if (!string.IsNullOrWhiteSpace(composer)) { foreach (var person in Split(composer, false)) { - peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer }); + people.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer }); } } @@ -1091,7 +1139,7 @@ namespace MediaBrowser.MediaEncoding.Probing { foreach (var person in Split(conductor, false)) { - peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor }); + people.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor }); } } @@ -1100,46 +1148,21 @@ namespace MediaBrowser.MediaEncoding.Probing { foreach (var person in Split(lyricist, false)) { - peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist }); + people.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist }); } } // Check for writer some music is tagged that way as alternative to composer/lyricist var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer"); - if (!string.IsNullOrWhiteSpace(writer)) { foreach (var person in Split(writer, false)) { - peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer }); + people.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer }); } } - audio.People = peoples.ToArray(); - audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album"); - - var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists"); - - if (!string.IsNullOrWhiteSpace(artists)) - { - audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false) - .DistinctNames() - .ToArray(); - } - else - { - var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist"); - if (string.IsNullOrWhiteSpace(artist)) - { - audio.Artists = Array.Empty(); - } - else - { - audio.Artists = SplitArtists(artist, _nameDelimiters, true) - .DistinctNames() - .ToArray(); - } - } + audio.People = people.ToArray(); var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist"); if (string.IsNullOrWhiteSpace(albumArtist)) @@ -1174,12 +1197,6 @@ namespace MediaBrowser.MediaEncoding.Probing // Disc number audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc"); - // If we don't have a ProductionYear try and get it from PremiereDate - if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue) - { - audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year; - } - // There's several values in tags may or may not be present FetchStudios(audio, tags, "organization"); FetchStudios(audio, tags, "ensemble"); diff --git a/MediaBrowser.Model/MediaInfo/MediaInfo.cs b/MediaBrowser.Model/MediaInfo/MediaInfo.cs index a268a4fa66..453aeb028a 100644 --- a/MediaBrowser.Model/MediaInfo/MediaInfo.cs +++ b/MediaBrowser.Model/MediaInfo/MediaInfo.cs @@ -51,6 +51,8 @@ namespace MediaBrowser.Model.MediaInfo public string ShowName { get; set; } + public string ForcedSortName { get; set; } + public int? IndexNumber { get; set; } public int? ParentIndexNumber { get; set; } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs index 9454636669..cf271e7db1 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs @@ -111,6 +111,11 @@ namespace MediaBrowser.Providers.MediaInfo audio.Name = data.Name; } + if (!string.IsNullOrEmpty(data.ForcedSortName)) + { + audio.ForcedSortName = data.ForcedSortName; + } + if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast)) { var people = new List(); diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 74849a5221..e7f9cf314f 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -394,6 +394,12 @@ namespace MediaBrowser.Providers.MediaInfo } } + if (video is MusicVideo musicVideo) + { + musicVideo.Album = data.Album; + musicVideo.Artists = data.Artists; + } + if (data.ProductionYear.HasValue) { if (!video.ProductionYear.HasValue || isFullRefresh) @@ -436,6 +442,11 @@ namespace MediaBrowser.Providers.MediaInfo video.Name = data.Name; } } + + if (!string.IsNullOrWhiteSpace(data.ForcedSortName)) + { + video.ForcedSortName = data.ForcedSortName; + } } // If we don't have a ProductionYear try and get it from PremiereDate From 07751768f438b7937ede411bb9c65dd6f5035ec4 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Mon, 5 Apr 2021 21:29:46 +0200 Subject: [PATCH 1401/1930] Add tests for music video metadata --- .../Probing/ProbeResultNormalizerTests.cs | 19 +++ .../Probing/music_video_metadata.json | 111 ++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs index 69e2aa4372..c8de785716 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs @@ -1,3 +1,5 @@ +using System; +using System.Globalization; using System.IO; using System.Text.Json; using MediaBrowser.Common.Json; @@ -52,5 +54,22 @@ namespace Jellyfin.MediaEncoding.Tests.Probing Assert.Empty(res.Chapters); Assert.Equal("Just color bars", res.Overview); } + + [Fact] + public void GetMediaInfo_MusicVideo_Success() + { + var bytes = File.ReadAllBytes("Test Data/Probing/music_video_metadata.json"); + var internalMediaInfoResult = JsonSerializer.Deserialize(bytes, _jsonOptions); + MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/music_video.mkv", MediaProtocol.File); + + Assert.Equal("The Title", res.Name); + Assert.Equal("Title, The", res.ForcedSortName); + Assert.Single(res.Artists); + Assert.Equal("The Artist", res.Artists[0]); + Assert.Equal("Album", res.Album); + Assert.Equal(2021, res.ProductionYear); + Assert.True(res.PremiereDate.HasValue); + Assert.Equal(DateTime.Parse("2021-01-01T00:00Z", DateTimeFormatInfo.CurrentInfo).ToUniversalTime(), res.PremiereDate); + } } } diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json new file mode 100644 index 0000000000..97d6600a4a --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/music_video_metadata.json @@ -0,0 +1,111 @@ +{ + "streams": [ + { + "index": 0, + "codec_name": "h264", + "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10", + "profile": "High", + "codec_type": "video", + "codec_time_base": "1001/48000", + "codec_tag_string": "[0][0][0][0]", + "codec_tag": "0x0000", + "width": 1920, + "height": 1080, + "coded_width": 1920, + "coded_height": 1088, + "closed_captions": 0, + "has_b_frames": 0, + "sample_aspect_ratio": "1:1", + "display_aspect_ratio": "16:9", + "pix_fmt": "yuv420p", + "level": 42, + "chroma_location": "left", + "field_order": "progressive", + "refs": 1, + "is_avc": "true", + "nal_length_size": "4", + "r_frame_rate": "24000/1001", + "avg_frame_rate": "24000/1001", + "time_base": "1/1000", + "start_pts": 0, + "start_time": "0.000000", + "bits_per_raw_sample": "8", + "disposition": { + "default": 1, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + }, + "tags": { + "language": "eng" + } + }, + { + "index": 1, + "codec_name": "aac", + "codec_long_name": "AAC (Advanced Audio Coding)", + "profile": "LC", + "codec_type": "audio", + "codec_time_base": "1/48000", + "codec_tag_string": "[0][0][0][0]", + "codec_tag": "0x0000", + "sample_fmt": "fltp", + "sample_rate": "48000", + "channels": 2, + "channel_layout": "stereo", + "bits_per_sample": 0, + "r_frame_rate": "0/0", + "avg_frame_rate": "0/0", + "time_base": "1/1000", + "start_pts": 0, + "start_time": "0.000000", + "disposition": { + "default": 1, + "dub": 0, + "original": 0, + "comment": 0, + "lyrics": 0, + "karaoke": 0, + "forced": 0, + "hearing_impaired": 0, + "visual_impaired": 0, + "clean_effects": 0, + "attached_pic": 0, + "timed_thumbnails": 0 + }, + "tags": { + "language": "eng" + } + } + ], + "chapters": [ + ], + "format": { + "filename": "music_video.mkv", + "nb_streams": 2, + "nb_programs": 0, + "format_name": "matroska,webm", + "format_long_name": "Matroska / WebM", + "start_time": "0.000000", + "duration": "180.000000", + "size": "500000000", + "bit_rate": "22222222", + "probe_score": 100, + "tags": { + "TITLE-eng": "The Title", + "TITLESORT": "Title, The", + "ARTIST": "The Artist", + "ARTISTSORT": "Artist, The", + "ALBUM": "Album", + "DATE_RELEASED": "2021-01-01" + } + } +} From a7c8bc632fc3f25b66b80b03c76d7577332e0582 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Mon, 5 Apr 2021 21:31:06 +0200 Subject: [PATCH 1402/1930] Fix typo in test data filename --- .../Probing/ProbeResultNormalizerTests.cs | 4 ++-- .../Probing/{some_matadata.json => video_metadata.json} | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/{some_matadata.json => video_metadata.json} (100%) diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs index c8de785716..98fbb00d52 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs @@ -19,9 +19,9 @@ namespace Jellyfin.MediaEncoding.Tests.Probing [Fact] public void GetMediaInfo_MetaData_Success() { - var bytes = File.ReadAllBytes("Test Data/Probing/some_matadata.json"); + var bytes = File.ReadAllBytes("Test Data/Probing/video_metadata.json"); var internalMediaInfoResult = JsonSerializer.Deserialize(bytes, _jsonOptions); - MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/some_matadata.mkv", MediaProtocol.File); + MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_metadata.mkv", MediaProtocol.File); Assert.Single(res.MediaStreams); diff --git a/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json b/tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json similarity index 100% rename from tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/some_matadata.json rename to tests/Jellyfin.MediaEncoding.Tests/Test Data/Probing/video_metadata.json From ba958c70d5359183660f94542954585bb6f67d9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Tue, 6 Apr 2021 17:24:01 +0200 Subject: [PATCH 1403/1930] (jellyfin-web): Switch to npm --- Dockerfile | 2 +- Dockerfile.arm | 2 +- Dockerfile.arm64 | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 41dd3d081e..6552546eaa 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && yarn install \ + && npm i \ && mv dist /dist FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim as builder diff --git a/Dockerfile.arm b/Dockerfile.arm index e0eaca0edd..1829982f5e 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -10,7 +10,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && yarn install \ + && npm i \ && mv dist /dist diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index db7de935cf..994df32ddc 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -10,7 +10,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && yarn install \ + && npm i \ && mv dist /dist From 8d6713af65e730c4508cea241439db315217ee8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Tue, 6 Apr 2021 17:33:51 +0200 Subject: [PATCH 1404/1930] Use npm ci instead of npm i --- Dockerfile | 2 +- Dockerfile.arm | 2 +- Dockerfile.arm64 | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6552546eaa..cafee737a1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm i \ + && npm ci --no-audit \ && mv dist /dist FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim as builder diff --git a/Dockerfile.arm b/Dockerfile.arm index 1829982f5e..d63dbee758 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -10,7 +10,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm i \ + && npm ci --no-audit \ && mv dist /dist diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index 994df32ddc..e95999f2a6 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -10,7 +10,7 @@ ARG JELLYFIN_WEB_VERSION=master RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm i \ + && npm ci --no-audit \ && mv dist /dist From 95327b842e9eb50ca2c53740674b8ed2f6615eae Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 6 Apr 2021 20:02:06 +0200 Subject: [PATCH 1405/1930] Enable NetAnalyzers for more projects --- Emby.Drawing/NullImageEncoder.cs | 2 +- Emby.Notifications/Emby.Notifications.csproj | 6 ++---- Emby.Photos/Emby.Photos.csproj | 6 ++---- .../Emby.Server.Implementations.csproj | 6 ++---- 4 files changed, 7 insertions(+), 13 deletions(-) diff --git a/Emby.Drawing/NullImageEncoder.cs b/Emby.Drawing/NullImageEncoder.cs index 2a1cfd3da5..1c05aa9161 100644 --- a/Emby.Drawing/NullImageEncoder.cs +++ b/Emby.Drawing/NullImageEncoder.cs @@ -32,7 +32,7 @@ namespace Emby.Drawing => throw new NotImplementedException(); /// - public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat) + public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat outputFormat) { throw new NotImplementedException(); } diff --git a/Emby.Notifications/Emby.Notifications.csproj b/Emby.Notifications/Emby.Notifications.csproj index 526a27229f..5a2aea6423 100644 --- a/Emby.Notifications/Emby.Notifications.csproj +++ b/Emby.Notifications/Emby.Notifications.csproj @@ -11,6 +11,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset @@ -30,8 +32,4 @@ - - ../jellyfin.ruleset - - diff --git a/Emby.Photos/Emby.Photos.csproj b/Emby.Photos/Emby.Photos.csproj index e64a658c51..2b66181599 100644 --- a/Emby.Photos/Emby.Photos.csproj +++ b/Emby.Photos/Emby.Photos.csproj @@ -24,6 +24,8 @@ true true enable + AllEnabledByDefault + ../jellyfin.ruleset @@ -33,8 +35,4 @@ - - ../jellyfin.ruleset - - diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index be552ef93a..9248053f54 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -46,6 +46,8 @@ true AD0001 + AllEnabledByDefault + ../jellyfin.ruleset @@ -55,10 +57,6 @@ - - ../jellyfin.ruleset - - From e85ac4d975c19e47637e11e76294de90e0481309 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Apr 2021 18:35:36 +0000 Subject: [PATCH 1406/1930] Bump Microsoft.AspNetCore.Authorization from 5.0.3 to 5.0.5 Bumps [Microsoft.AspNetCore.Authorization](https://github.com/dotnet/aspnetcore) from 5.0.3 to 5.0.5. - [Release notes](https://github.com/dotnet/aspnetcore/releases) - [Commits](https://github.com/dotnet/aspnetcore/compare/v5.0.3...v5.0.5) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index d5372d7526..d6dc5a2dc3 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,7 +15,7 @@ - + From 3651ee5ed32273b1b6e7f63afe0b9923235e4d14 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 6 Apr 2021 18:35:51 +0000 Subject: [PATCH 1407/1930] Bump Microsoft.AspNetCore.Mvc.Testing from 5.0.3 to 5.0.5 Bumps [Microsoft.AspNetCore.Mvc.Testing](https://github.com/dotnet/aspnetcore) from 5.0.3 to 5.0.5. - [Release notes](https://github.com/dotnet/aspnetcore/releases) - [Commits](https://github.com/dotnet/aspnetcore/compare/v5.0.3...v5.0.5) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 57277be150..f288561b74 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 079021e61b..8d4d9e3d23 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -12,7 +12,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 3ba49ff6a2..4a5cf1feee 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -13,7 +13,7 @@ - + From 65f880be323e154655505c702822ce381fc5569e Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 6 Apr 2021 20:59:47 +0100 Subject: [PATCH 1408/1930] Keep plugin status after update. --- Emby.Server.Implementations/Plugins/PluginManager.cs | 7 ++++--- .../Updates/InstallationManager.cs | 12 +++++++----- MediaBrowser.Common/Plugins/IPluginManager.cs | 4 +++- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 700396c4cf..3a8296455b 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; @@ -368,7 +369,7 @@ namespace Emby.Server.Implementations.Plugins } /// - public async Task GenerateManifest(PackageInfo packageInfo, Version version, string path) + public async Task GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status) { if (packageInfo == null) { @@ -411,9 +412,9 @@ namespace Emby.Server.Implementations.Plugins Overview = packageInfo.Overview, Owner = packageInfo.Owner, TargetAbi = versionInfo.TargetAbi ?? string.Empty, - Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp), + Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp, CultureInfo.InvariantCulture), Version = versionInfo.Version, - Status = PluginStatus.Active, + Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state. AutoUpdate = true, ImagePath = imagePath }; diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index fc34f93cdd..e7307aefef 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -22,6 +22,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Events; using MediaBrowser.Controller.Events.Updates; using MediaBrowser.Model.IO; +using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Updates; using Microsoft.Extensions.Logging; @@ -194,7 +195,7 @@ namespace Emby.Server.Implementations.Updates var plugin = _pluginManager.GetPlugin(packageGuid, version.VersionNumber); if (plugin != null) { - await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path); + await _pluginManager.GenerateManifest(package, version.VersionNumber, plugin.Path, plugin.Manifest.Status).ConfigureAwait(false); } // Remove versions with a target ABI greater then the current application version. @@ -500,7 +501,8 @@ namespace Emby.Server.Implementations.Updates var plugins = _pluginManager.Plugins; foreach (var plugin in plugins) { - if (plugin.Manifest?.AutoUpdate == false) + // Don't auto update when plugin marked not to, or when it's disabled. + if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == MediaBrowser.Model.Plugins.PluginStatus.Disabled) { continue; } @@ -515,7 +517,7 @@ namespace Emby.Server.Implementations.Updates } } - private async Task PerformPackageInstallation(InstallationInfo package, CancellationToken cancellationToken) + private async Task PerformPackageInstallation(InstallationInfo package, PluginStatus status, CancellationToken cancellationToken) { var extension = Path.GetExtension(package.SourceUrl); if (!string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase)) @@ -567,7 +569,7 @@ namespace Emby.Server.Implementations.Updates stream.Position = 0; _zipClient.ExtractAllFromZip(stream, targetDir, true); - await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir); + await _pluginManager.GenerateManifest(package.PackageInfo, package.Version, targetDir, status).ConfigureAwait(false); _pluginManager.ImportPluginFrom(targetDir); } @@ -576,7 +578,7 @@ namespace Emby.Server.Implementations.Updates LocalPlugin? plugin = _pluginManager.Plugins.FirstOrDefault(p => p.Id.Equals(package.Id) && p.Version.Equals(package.Version)) ?? _pluginManager.Plugins.FirstOrDefault(p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) && p.Version.Equals(package.Version)); - await PerformPackageInstallation(package, cancellationToken).ConfigureAwait(false); + await PerformPackageInstallation(package, plugin?.Manifest.Status ?? PluginStatus.Active, cancellationToken).ConfigureAwait(false); _logger.LogInformation(plugin == null ? "New plugin installed: {PluginName} {PluginVersion}" : "Plugin updated: {PluginName} {PluginVersion}", package.Name, package.Version); return plugin != null; diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index f9a8fb6f7a..0e2e814cb0 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; +using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Updates; using Microsoft.Extensions.DependencyInjection; @@ -51,8 +52,9 @@ namespace MediaBrowser.Common.Plugins /// The used to generate a manifest. /// Version to be installed. /// The path where to save the manifest. + /// Initial status of the plugin. /// True if successful. - Task GenerateManifest(PackageInfo packageInfo, Version version, string path); + Task GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status); /// /// Imports plugin details from a folder. From fbd9141ecdb6ecd8c8b887c33b0b04370f7002e3 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 6 Apr 2021 22:46:54 +0200 Subject: [PATCH 1409/1930] Add tests for unauthenticated websocket access --- .../WebSocketTests.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs diff --git a/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs b/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs new file mode 100644 index 0000000000..ffdc04ebaf --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/WebSocketTests.cs @@ -0,0 +1,32 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests +{ + public sealed class WebSocketTests : IClassFixture + { + private readonly JellyfinApplicationFactory _factory; + + public WebSocketTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task WebSocket_Unauthenticated_ThrowsInvalidOperationException() + { + var server = _factory.Server; + var client = server.CreateWebSocketClient(); + + await Assert.ThrowsAsync( + () => client.ConnectAsync( + new UriBuilder(server.BaseAddress) + { + Scheme = "ws", + Path = "websocket" + }.Uri, CancellationToken.None)); + } + } +} From d772fddfb3fcddd5f540cf2650eb7e405a6aec2c Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 7 Apr 2021 13:09:00 +0200 Subject: [PATCH 1410/1930] make custompref value nullable --- .../Entities/CustomItemDisplayPreferences.cs | 4 +- ...110544_NullableCustomPrefValue.Designer.cs | 520 ++++++++++++++++++ .../20210407110544_NullableCustomPrefValue.cs | 35 ++ .../Migrations/JellyfinDbModelSnapshot.cs | 10 +- .../Users/DisplayPreferencesManager.cs | 2 +- .../IDisplayPreferencesManager.cs | 2 +- 6 files changed, 563 insertions(+), 10 deletions(-) create mode 100644 Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs create mode 100644 Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs diff --git a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs index cc46248c75..de37fb5446 100644 --- a/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs +++ b/Jellyfin.Data/Entities/CustomItemDisplayPreferences.cs @@ -17,7 +17,7 @@ namespace Jellyfin.Data.Entities /// The client. /// The preference key. /// The preference value. - public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string key, string value) + public CustomItemDisplayPreferences(Guid userId, Guid itemId, string client, string key, string? value) { UserId = userId; ItemId = itemId; @@ -75,6 +75,6 @@ namespace Jellyfin.Data.Entities /// /// Required. /// - public string Value { get; set; } + public string? Value { get; set; } } } diff --git a/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs new file mode 100644 index 0000000000..d332d19f28 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.Designer.cs @@ -0,0 +1,520 @@ +#pragma warning disable CS1591 +// +using System; +using Jellyfin.Server.Implementations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace Jellyfin.Server.Implementations.Migrations +{ + [DbContext(typeof(JellyfinDb))] + [Migration("20210407110544_NullableCustomPrefValue")] + partial class NullableCustomPrefValue + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("jellyfin") + .HasAnnotation("ProductVersion", "5.0.3"); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DayOfWeek") + .HasColumnType("INTEGER"); + + b.Property("EndHour") + .HasColumnType("REAL"); + + b.Property("StartHour") + .HasColumnType("REAL"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AccessSchedules"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ActivityLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DateCreated") + .HasColumnType("TEXT"); + + b.Property("ItemId") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("LogSeverity") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Overview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("ShortOverview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ActivityLogs"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.CustomItemDisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("Key") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "ItemId", "Client", "Key") + .IsUnique(); + + b.ToTable("CustomItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ChromecastVersion") + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("DashboardTheme") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("EnableNextVideoInfoOverlay") + .HasColumnType("INTEGER"); + + b.Property("IndexBy") + .HasColumnType("INTEGER"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("ScrollDirection") + .HasColumnType("INTEGER"); + + b.Property("ShowBackdrop") + .HasColumnType("INTEGER"); + + b.Property("ShowSidebar") + .HasColumnType("INTEGER"); + + b.Property("SkipBackwardLength") + .HasColumnType("INTEGER"); + + b.Property("SkipForwardLength") + .HasColumnType("INTEGER"); + + b.Property("TvHome") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "ItemId", "Client") + .IsUnique(); + + b.ToTable("DisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("DisplayPreferencesId") + .HasColumnType("INTEGER"); + + b.Property("Order") + .HasColumnType("INTEGER"); + + b.Property("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DisplayPreferencesId"); + + b.ToTable("HomeSection"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("LastModified") + .HasColumnType("TEXT"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ImageInfos"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("IndexBy") + .HasColumnType("INTEGER"); + + b.Property("ItemId") + .HasColumnType("TEXT"); + + b.Property("RememberIndexing") + .HasColumnType("INTEGER"); + + b.Property("RememberSorting") + .HasColumnType("INTEGER"); + + b.Property("SortBy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SortOrder") + .HasColumnType("INTEGER"); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("ViewType") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("ItemDisplayPreferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Kind") + .HasColumnType("INTEGER"); + + b.Property("Permission_Permissions_Guid") + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Permission_Permissions_Guid"); + + b.ToTable("Permissions"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Kind") + .HasColumnType("INTEGER"); + + b.Property("Preference_Preferences_Guid") + .HasColumnType("TEXT"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Preference_Preferences_Guid"); + + b.ToTable("Preferences"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AudioLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("AuthenticationProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("DisplayCollectionsView") + .HasColumnType("INTEGER"); + + b.Property("DisplayMissingEpisodes") + .HasColumnType("INTEGER"); + + b.Property("EasyPassword") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property("EnableAutoLogin") + .HasColumnType("INTEGER"); + + b.Property("EnableLocalPassword") + .HasColumnType("INTEGER"); + + b.Property("EnableNextEpisodeAutoPlay") + .HasColumnType("INTEGER"); + + b.Property("EnableUserPreferenceAccess") + .HasColumnType("INTEGER"); + + b.Property("HidePlayedInLatest") + .HasColumnType("INTEGER"); + + b.Property("InternalId") + .HasColumnType("INTEGER"); + + b.Property("InvalidLoginAttemptCount") + .HasColumnType("INTEGER"); + + b.Property("LastActivityDate") + .HasColumnType("TEXT"); + + b.Property("LastLoginDate") + .HasColumnType("TEXT"); + + b.Property("LoginAttemptsBeforeLockout") + .HasColumnType("INTEGER"); + + b.Property("MaxActiveSessions") + .HasColumnType("INTEGER"); + + b.Property("MaxParentalAgeRating") + .HasColumnType("INTEGER"); + + b.Property("MustUpdatePassword") + .HasColumnType("INTEGER"); + + b.Property("Password") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property("PasswordResetProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("PlayDefaultAudioTrack") + .HasColumnType("INTEGER"); + + b.Property("RememberAudioSelections") + .HasColumnType("INTEGER"); + + b.Property("RememberSubtitleSelections") + .HasColumnType("INTEGER"); + + b.Property("RemoteClientBitrateLimit") + .HasColumnType("INTEGER"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property("SubtitleLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property("SubtitleMode") + .HasColumnType("INTEGER"); + + b.Property("SyncPlayAccess") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("AccessSchedules") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("DisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.HomeSection", b => + { + b.HasOne("Jellyfin.Data.Entities.DisplayPreferences", null) + .WithMany("HomeSections") + .HasForeignKey("DisplayPreferencesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ImageInfo", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithOne("ProfileImage") + .HasForeignKey("Jellyfin.Data.Entities.ImageInfo", "UserId"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.ItemDisplayPreferences", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("ItemDisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Permission", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Permissions") + .HasForeignKey("Permission_Permissions_Guid"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.Preference", b => + { + b.HasOne("Jellyfin.Data.Entities.User", null) + .WithMany("Preferences") + .HasForeignKey("Preference_Preferences_Guid"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => + { + b.Navigation("HomeSections"); + }); + + modelBuilder.Entity("Jellyfin.Data.Entities.User", b => + { + b.Navigation("AccessSchedules"); + + b.Navigation("DisplayPreferences"); + + b.Navigation("ItemDisplayPreferences"); + + b.Navigation("Permissions"); + + b.Navigation("Preferences"); + + b.Navigation("ProfileImage"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs new file mode 100644 index 0000000000..ade68612c0 --- /dev/null +++ b/Jellyfin.Server.Implementations/Migrations/20210407110544_NullableCustomPrefValue.cs @@ -0,0 +1,35 @@ +#pragma warning disable CS1591 +// +using Microsoft.EntityFrameworkCore.Migrations; + +namespace Jellyfin.Server.Implementations.Migrations +{ + public partial class NullableCustomPrefValue : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Value", + schema: "jellyfin", + table: "CustomItemDisplayPreferences", + type: "TEXT", + nullable: true, + oldClrType: typeof(string), + oldType: "TEXT"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "Value", + schema: "jellyfin", + table: "CustomItemDisplayPreferences", + type: "TEXT", + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "TEXT", + oldNullable: true); + } + } +} diff --git a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs index 1614a88efb..6a523ba685 100644 --- a/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs +++ b/Jellyfin.Server.Implementations/Migrations/JellyfinDbModelSnapshot.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Migrations #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("jellyfin") - .HasAnnotation("ProductVersion", "5.0.0"); + .HasAnnotation("ProductVersion", "5.0.3"); modelBuilder.Entity("Jellyfin.Data.Entities.AccessSchedule", b => { @@ -110,7 +110,6 @@ namespace Jellyfin.Server.Implementations.Migrations .HasColumnType("TEXT"); b.Property("Value") - .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); @@ -448,8 +447,8 @@ namespace Jellyfin.Server.Implementations.Migrations modelBuilder.Entity("Jellyfin.Data.Entities.DisplayPreferences", b => { b.HasOne("Jellyfin.Data.Entities.User", null) - .WithOne("DisplayPreferences") - .HasForeignKey("Jellyfin.Data.Entities.DisplayPreferences", "UserId") + .WithMany("DisplayPreferences") + .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); @@ -502,8 +501,7 @@ namespace Jellyfin.Server.Implementations.Migrations { b.Navigation("AccessSchedules"); - b.Navigation("DisplayPreferences") - .IsRequired(); + b.Navigation("DisplayPreferences"); b.Navigation("ItemDisplayPreferences"); diff --git a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs index a3e9516b9f..c89e3c74d5 100644 --- a/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs +++ b/Jellyfin.Server.Implementations/Users/DisplayPreferencesManager.cs @@ -68,7 +68,7 @@ namespace Jellyfin.Server.Implementations.Users } /// - public IDictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client) + public Dictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client) { return _dbContext.CustomItemDisplayPreferences .AsQueryable() diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index 041eeea62a..87b6f81c5c 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller /// The item id. /// The client string. /// The dictionary of custom item display preferences. - IDictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client); + Dictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client); /// /// Sets the custom item display preference for the user and client. From 4892e0cf064a2a392881b38a5965324aa80eac0c Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 7 Apr 2021 13:17:59 +0200 Subject: [PATCH 1411/1930] fix build...somehow --- MediaBrowser.Controller/IDisplayPreferencesManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index 87b6f81c5c..be1d974a47 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller /// The item id. /// The client string. /// The dictionary of custom item display preferences. - Dictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client); + Dictionary ListCustomItemDisplayPreferences(Guid userId, Guid itemId, string client); /// /// Sets the custom item display preference for the user and client. From 45a16c19a76d8fac36d3acf864f8030fb30d4e1c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 7 Apr 2021 21:29:15 +0200 Subject: [PATCH 1412/1930] Add code to test authenticated endpoints --- .../AuthHelper.cs | 59 +++++++++++++++++++ .../Controllers/ActivityLogControllerTests.cs | 30 ++++++++++ 2 files changed, 89 insertions(+) create mode 100644 tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs create mode 100644 tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs diff --git a/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs new file mode 100644 index 0000000000..4b8fac07fb --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs @@ -0,0 +1,59 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Mime; +using System.Text.Json; +using System.Threading.Tasks; +using Jellyfin.Api.Models.StartupDtos; +using Jellyfin.Api.Models.UserDtos; +using MediaBrowser.Common.Json; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests +{ + public static class AuthHelper + { + public const string AuthHeaderName = "X-Emby-Authorization"; + public const string DummyAuthHeader = "MediaBrowser Client=\"Jellyfin.Server Integration Tests\", DeviceId=\"69420\", Device=\"Apple II\", Version=\"10.8.0\""; + + public static async Task CompleteStartupAsync(HttpClient client) + { + var jsonOptions = JsonDefaults.Options; + var userResponse = await client.GetByteArrayAsync("/Startup/User").ConfigureAwait(false); + var user = JsonSerializer.Deserialize(userResponse, jsonOptions); + + using var completeResponse = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty())).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, completeResponse.StatusCode); + + using var content = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes( + new AuthenticateUserByName() + { + Username = user!.Name, + Pw = user.Password, + }, + jsonOptions)); + content.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + content.Headers.Add("X-Emby-Authorization", DummyAuthHeader); + + using var authResponse = await client.PostAsync("/Users/AuthenticateByName", content).ConfigureAwait(false); + var auth = await JsonSerializer.DeserializeAsync( + await authResponse.Content.ReadAsStreamAsync().ConfigureAwait(false), + jsonOptions).ConfigureAwait(false); + + return auth!.AccessToken; + } + + public static void AddAuthHeader(this HttpRequestHeaders headers, string accessToken) + { + headers.Add(AuthHeaderName, DummyAuthHeader + $", Token={accessToken}"); + } + + private class AuthenticationResultDto + { + public string AccessToken { get; set; } = string.Empty; + + public string ServerId { get; set; } = string.Empty; + } + } +} diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs new file mode 100644 index 0000000000..4657ee6e2f --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs @@ -0,0 +1,30 @@ +using System.Net; +using System.Net.Mime; +using System.Threading.Tasks; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests.Controllers +{ + public sealed class ActivityLogControllerTests : IClassFixture + { + private readonly JellyfinApplicationFactory _factory; + private string? _accessToken; + + public ActivityLogControllerTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task ActivityLog_GetEntries_Ok() + { + var client = _factory.CreateClient(); + client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false)); + + var response = await client.GetAsync("System/ActivityLog/Entries").ConfigureAwait(false); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType); + } + } +} From 7c457da9ab0803a467e8508203b527378066c099 Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Thu, 8 Apr 2021 02:39:58 -0400 Subject: [PATCH 1413/1930] Fixed issue with determining if a directory was a directory or file when it contained a '.' character in the directory path. Resolves: #2845 --- MediaBrowser.Controller/Playlists/Playlist.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index e8b7be7e20..faaceb828c 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.IO; using System.Linq; using System.Text.Json.Serialization; using System.Threading; @@ -43,6 +44,16 @@ namespace MediaBrowser.Controller.Playlists public static bool IsPlaylistFile(string path) { + //When a directory contains a `.`, calling "HasExtension" will return true, even if that location is a directory that exists. + //This kills the PlaylistXmlSaver, because instead of saving in "config/data/playlists/MyList2.0/playlist.xml", + //It saves the information in "config/data/playlists/MyList2.xml". So we just need to see if it's actually a real directory first. + //Lucky for us, when a new playlist is created, the directory on the drive is created first, then the Playlist object is created. + //And if there's not a directory there, then we can just check if it has an extension. + if (new System.IO.DirectoryInfo(path).Exists) + { //This is a directory, and therefore definitely not a playlist file. + return false; + } + //Well, there's no directory there, so if it /looks/ like a file path, then it probably is. return System.IO.Path.HasExtension(path); } From 2314487e38d77f5d3a123ad2f0e76ab6ea2134c7 Mon Sep 17 00:00:00 2001 From: BrianCArnold Date: Thu, 8 Apr 2021 04:03:43 -0400 Subject: [PATCH 1414/1930] Update MediaBrowser.Controller/Playlists/Playlist.cs Included suggested change from cvium Co-authored-by: Claus Vium --- MediaBrowser.Controller/Playlists/Playlist.cs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index faaceb828c..089d241bae 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -44,17 +44,8 @@ namespace MediaBrowser.Controller.Playlists public static bool IsPlaylistFile(string path) { - //When a directory contains a `.`, calling "HasExtension" will return true, even if that location is a directory that exists. - //This kills the PlaylistXmlSaver, because instead of saving in "config/data/playlists/MyList2.0/playlist.xml", - //It saves the information in "config/data/playlists/MyList2.xml". So we just need to see if it's actually a real directory first. - //Lucky for us, when a new playlist is created, the directory on the drive is created first, then the Playlist object is created. - //And if there's not a directory there, then we can just check if it has an extension. - if (new System.IO.DirectoryInfo(path).Exists) - { //This is a directory, and therefore definitely not a playlist file. - return false; - } - //Well, there's no directory there, so if it /looks/ like a file path, then it probably is. - return System.IO.Path.HasExtension(path); + // The path will sometimes be a directory and "Path.HasExtension" returns true if the name contains a '.' (dot). + return Path.HasExtension(path) && !Directory.Exists(path); } [JsonIgnore] From a2acfb02e994f9829c5a0131f583e720b3466ce8 Mon Sep 17 00:00:00 2001 From: Brian Arnold Date: Thu, 8 Apr 2021 05:19:28 -0400 Subject: [PATCH 1415/1930] Can't reference System.IO.Path as 'Path', even though System.IO is in the usings, because there is a Path property of the class. --- MediaBrowser.Controller/Playlists/Playlist.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index 089d241bae..977b14cb08 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -45,7 +45,7 @@ namespace MediaBrowser.Controller.Playlists public static bool IsPlaylistFile(string path) { // The path will sometimes be a directory and "Path.HasExtension" returns true if the name contains a '.' (dot). - return Path.HasExtension(path) && !Directory.Exists(path); + return System.IO.Path.HasExtension(path) && !Directory.Exists(path); } [JsonIgnore] From b1faf8c2e832d269c1bc6017037a17533913abf4 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 8 Apr 2021 07:36:13 -0600 Subject: [PATCH 1416/1930] Update to dotnet 5.0.5 --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- .../Jellyfin.Server.Implementations.csproj | 8 ++++---- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++-- MediaBrowser.Model/MediaBrowser.Model.csproj | 2 +- deployment/Dockerfile.debian.amd64 | 2 +- deployment/Dockerfile.debian.arm64 | 2 +- deployment/Dockerfile.debian.armhf | 2 +- deployment/Dockerfile.linux.amd64 | 2 +- deployment/Dockerfile.linux.amd64-musl | 2 +- deployment/Dockerfile.linux.arm64 | 2 +- deployment/Dockerfile.linux.armhf | 2 +- deployment/Dockerfile.macos | 2 +- deployment/Dockerfile.portable | 2 +- deployment/Dockerfile.ubuntu.amd64 | 2 +- deployment/Dockerfile.ubuntu.arm64 | 2 +- deployment/Dockerfile.ubuntu.armhf | 2 +- deployment/Dockerfile.windows.amd64 | 2 +- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 20 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index d5372d7526..d6dc5a2dc3 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,7 +15,7 @@ - + diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 96a4fa2fb4..2c6a176b69 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -27,13 +27,13 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index e7f83aff16..61171c0189 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -37,8 +37,8 @@ - - + + diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index f622a042ac..4db99f0b08 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -36,7 +36,7 @@ - + diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index 4280726135..ec0321f477 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index b540efc09a..8fd5ddb932 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 426ce02fcd..14615d19fb 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 3b91515f36..1f6ca15586 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl index 2ca9072bae..6af5d8baf5 100644 --- a/deployment/Dockerfile.linux.amd64-musl +++ b/deployment/Dockerfile.linux.amd64-musl @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 index 03efd306d7..15b59e29d1 100644 --- a/deployment/Dockerfile.linux.arm64 +++ b/deployment/Dockerfile.linux.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf index 585572204b..71a0fda215 100644 --- a/deployment/Dockerfile.linux.armhf +++ b/deployment/Dockerfile.linux.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index b37afdcfbc..9291bcbb94 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index 686b20197c..e98ba74f87 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index 3513bf8ecb..d1fd8818e6 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index 5acdf0d178..8e79d417cf 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 42f757d058..627caa95a8 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 6ed1193fb0..5723abcae6 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/a2052604-de46-4cd4-8256-9bc222537d32/a798771950904eaf91c0c37c58f516e1/dotnet-sdk-5.0.103-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 57277be150..f288561b74 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 079021e61b..8d4d9e3d23 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -12,7 +12,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 3ba49ff6a2..4a5cf1feee 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -13,7 +13,7 @@ - + From b645bb20deb92225e17dd87fcc7fbf2fc1631e80 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 8 Apr 2021 14:38:25 +0100 Subject: [PATCH 1417/1930] Update Emby.Server.Implementations/Updates/InstallationManager.cs Co-authored-by: Cody Robibero --- Emby.Server.Implementations/Updates/InstallationManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index e7307aefef..653b1381b9 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -502,7 +502,7 @@ namespace Emby.Server.Implementations.Updates foreach (var plugin in plugins) { // Don't auto update when plugin marked not to, or when it's disabled. - if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == MediaBrowser.Model.Plugins.PluginStatus.Disabled) + if (plugin.Manifest?.AutoUpdate == false || plugin.Manifest?.Status == PluginStatus.Disabled) { continue; } From cc0f191228d7444a598370ac93ba7312700d58b1 Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Thu, 8 Apr 2021 09:57:17 -0400 Subject: [PATCH 1418/1930] Disable hevc encoding by default --- MediaBrowser.Model/Configuration/EncodingOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Configuration/EncodingOptions.cs b/MediaBrowser.Model/Configuration/EncodingOptions.cs index a9b2803017..365bbeef66 100644 --- a/MediaBrowser.Model/Configuration/EncodingOptions.cs +++ b/MediaBrowser.Model/Configuration/EncodingOptions.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Model.Configuration EnableDecodingColorDepth10Vp9 = true; EnableEnhancedNvdecDecoder = true; EnableHardwareEncoding = true; - AllowHevcEncoding = true; + AllowHevcEncoding = false; EnableSubtitleExtraction = true; HardwareDecodingCodecs = new string[] { "h264", "vc1" }; } From 391554d391c1a045a0922fd5f0b43459afdfc550 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 9 Apr 2021 01:04:49 +0200 Subject: [PATCH 1419/1930] Add tests for UserController --- .../AuthHelper.cs | 2 +- .../Controllers/ActivityLogControllerTests.cs | 2 +- .../Controllers/UserControllerTests.cs | 170 ++++++++++++++++++ 3 files changed, 172 insertions(+), 2 deletions(-) create mode 100644 tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs diff --git a/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs index 4b8fac07fb..ea6838682a 100644 --- a/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs +++ b/tests/Jellyfin.Server.Integration.Tests/AuthHelper.cs @@ -44,7 +44,7 @@ namespace Jellyfin.Server.Integration.Tests return auth!.AccessToken; } - public static void AddAuthHeader(this HttpRequestHeaders headers, string accessToken) + public static void AddAuthHeader(this HttpHeaders headers, string accessToken) { headers.Add(AuthHeaderName, DummyAuthHeader + $", Token={accessToken}"); } diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs index 4657ee6e2f..be89fbc9a9 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs @@ -8,7 +8,7 @@ namespace Jellyfin.Server.Integration.Tests.Controllers public sealed class ActivityLogControllerTests : IClassFixture { private readonly JellyfinApplicationFactory _factory; - private string? _accessToken; + private static string? _accessToken; public ActivityLogControllerTests(JellyfinApplicationFactory factory) { diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs new file mode 100644 index 0000000000..6584490de5 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/UserControllerTests.cs @@ -0,0 +1,170 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Mime; +using System.Text.Json; +using System.Threading.Tasks; +using Jellyfin.Api.Models.UserDtos; +using MediaBrowser.Common.Json; +using MediaBrowser.Model.Dto; +using Xunit; +using Xunit.Priority; + +namespace Jellyfin.Server.Integration.Tests.Controllers +{ + [TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)] + public sealed class UserControllerTests : IClassFixture + { + private const string TestUsername = "testUser01"; + + private readonly JellyfinApplicationFactory _factory; + private readonly JsonSerializerOptions _jsonOpions = JsonDefaults.Options; + private static string? _accessToken; + private static Guid _testUserId = Guid.Empty; + + public UserControllerTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + private Task CreateUserByName(HttpClient httpClient, CreateUserByName request) + { + using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(request, _jsonOpions)); + postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + return httpClient.PostAsync("Users/New", postContent); + } + + private Task UpdateUserPassword(HttpClient httpClient, Guid userId, UpdateUserPassword request) + { + using var postContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(request, _jsonOpions)); + postContent.Headers.ContentType = MediaTypeHeaderValue.Parse(MediaTypeNames.Application.Json); + return httpClient.PostAsync("Users/" + userId.ToString("N", CultureInfo.InvariantCulture) + "/Password", postContent); + } + + [Fact] + [Priority(-1)] + public async Task GetPublicUsers_Valid_Success() + { + var client = _factory.CreateClient(); + + using var response = await client.GetAsync("Users/Public").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var users = await JsonSerializer.DeserializeAsync( + await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false); + // User are hidden by default + Assert.Empty(users); + } + + [Fact] + [Priority(-1)] + public async Task GetUsers_Valid_Success() + { + var client = _factory.CreateClient(); + client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client).ConfigureAwait(false)); + + using var response = await client.GetAsync("Users").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var users = await JsonSerializer.DeserializeAsync( + await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false); + Assert.Single(users); + Assert.False(users![0].HasConfiguredPassword); + } + + [Fact] + [Priority(0)] + public async Task New_Valid_Success() + { + var client = _factory.CreateClient(); + + // access token can't be null here as the previous test populated it + client.DefaultRequestHeaders.AddAuthHeader(_accessToken!); + + var createRequest = new CreateUserByName() + { + Name = TestUsername + }; + + using var response = await CreateUserByName(client, createRequest).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var user = await JsonSerializer.DeserializeAsync( + await response.Content.ReadAsStreamAsync().ConfigureAwait(false), _jsonOpions).ConfigureAwait(false); + Assert.Equal(TestUsername, user!.Name); + Assert.False(user.HasPassword); + Assert.False(user.HasConfiguredPassword); + + _testUserId = user.Id; + + Console.WriteLine(user.Id.ToString("N", CultureInfo.InvariantCulture)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("‼️")] + [Priority(0)] + public async Task New_Invalid_Fail(string? username) + { + var client = _factory.CreateClient(); + + // access token can't be null here as the previous test populated it + client.DefaultRequestHeaders.AddAuthHeader(_accessToken!); + + var createRequest = new CreateUserByName() + { + Name = username + }; + + using var response = await CreateUserByName(client, createRequest).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + [Priority(1)] + public async Task UpdateUserPassword_Valid_Success() + { + var client = _factory.CreateClient(); + client.DefaultRequestHeaders.AddAuthHeader(_accessToken!); + + var createRequest = new UpdateUserPassword() + { + NewPw = "4randomPa$$word" + }; + + using var response = await UpdateUserPassword(client, _testUserId, createRequest).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + + var users = await JsonSerializer.DeserializeAsync( + await client.GetStreamAsync("Users").ConfigureAwait(false), _jsonOpions).ConfigureAwait(false); + var user = users!.First(x => x.Id == _testUserId); + Assert.True(user.HasPassword); + Assert.True(user.HasConfiguredPassword); + } + + [Fact] + [Priority(2)] + public async Task UpdateUserPassword_Empty_RemoveSetPassword() + { + var client = _factory.CreateClient(); + + client.DefaultRequestHeaders.AddAuthHeader(_accessToken!); + + var createRequest = new UpdateUserPassword() + { + CurrentPw = "4randomPa$$word", + }; + + using var response = await UpdateUserPassword(client, _testUserId, createRequest).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + + var users = await JsonSerializer.DeserializeAsync( + await client.GetStreamAsync("Users").ConfigureAwait(false), _jsonOpions).ConfigureAwait(false); + var user = users!.First(x => x.Id == _testUserId); + Assert.False(user.HasPassword); + Assert.False(user.HasConfiguredPassword); + } + } +} From db530e61f5ac7047f8c5b88b3a30aa17e9253bbc Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Fri, 9 Apr 2021 11:32:19 +0200 Subject: [PATCH 1420/1930] move IsPlayed to outerquery IsPlayed is a column in UserDatas and does not belong in the inner query. None of the other UserDatas columns are in the innerquery. --- Emby.Server.Implementations/Data/SqliteItemRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 2ae8054478..694805ebe9 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -5415,7 +5415,6 @@ AND Type = @InternalPersonType)"); ItemIds = query.ItemIds, TopParentIds = query.TopParentIds, ParentId = query.ParentId, - IsPlayed = query.IsPlayed, IsAiring = query.IsAiring, IsMovie = query.IsMovie, IsSports = query.IsSports, @@ -5441,6 +5440,7 @@ AND Type = @InternalPersonType)"); var outerQuery = new InternalItemsQuery(query.User) { + IsPlayed = query.IsPlayed, IsFavorite = query.IsFavorite, IsFavoriteOrLiked = query.IsFavoriteOrLiked, IsLiked = query.IsLiked, From a21b2714e7957640afa140361d9886877e57d6df Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Fri, 9 Apr 2021 12:03:56 +0200 Subject: [PATCH 1421/1930] fetching images should not kill the scanner --- .../Library/LibraryManager.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index c18838caf7..494eb59292 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1914,12 +1914,17 @@ namespace Emby.Server.Implementations.Library } catch (ArgumentException) { - _logger.LogWarning("Cannot get image index for {0}", img.Path); + _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path); continue; } catch (InvalidOperationException) { - _logger.LogWarning("Cannot fetch image from {0}", img.Path); + _logger.LogWarning("Cannot fetch image from {ImagePath}", img.Path); + continue; + } + catch (HttpRequestException ex) + { + _logger.LogWarning("Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode); continue; } } @@ -1932,7 +1937,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Cannot get image dimensions for {0}", image.Path); + _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path); image.Width = 0; image.Height = 0; continue; @@ -1944,7 +1949,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Cannot compute blurhash for {0}", image.Path); + _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path); image.BlurHash = string.Empty; } @@ -1954,7 +1959,7 @@ namespace Emby.Server.Implementations.Library } catch (Exception ex) { - _logger.LogError(ex, "Cannot update DateModified for {0}", image.Path); + _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path); } } From 08ccf2a49cc5c67026b324570a975aa9adab8915 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:20:12 +0200 Subject: [PATCH 1422/1930] Resolve name from episode folder --- .../Library/LibraryManager.cs | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index c18838caf7..f92c300938 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -27,6 +27,7 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; @@ -48,6 +49,7 @@ using MediaBrowser.Providers.MediaInfo; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Episode = MediaBrowser.Controller.Entities.TV.Episode; +using EpisodeInfo = Emby.Naming.TV.EpisodeInfo; using Genre = MediaBrowser.Controller.Entities.Genre; using Person = MediaBrowser.Controller.Entities.Person; using VideoResolver = Emby.Naming.Video.VideoResolver; @@ -2512,7 +2514,7 @@ namespace Emby.Server.Implementations.Library public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh) { var series = episode.Series; - bool? isAbsoluteNaming = series == null ? false : string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase); + bool? isAbsoluteNaming = series != null && string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase); if (!isAbsoluteNaming.Value) { // In other words, no filter applied @@ -2524,9 +2526,32 @@ namespace Emby.Server.Implementations.Library var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd; // TODO nullable - what are we trying to do there with empty episodeInfo? - var episodeInfo = episode.IsFileProtocol - ? resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new Naming.TV.EpisodeInfo(episode.Path) - : new Naming.TV.EpisodeInfo(episode.Path); + EpisodeInfo episodeInfo = null; + if (episode.IsFileProtocol) + { + episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new EpisodeInfo(episode.Path); + // Resolve from parent folder if it's not the Season folder + if (!episodeInfo.EpisodeNumber.HasValue && episode.Parent is not Season) + { + var episodeInfoFromFolder = resolver.Resolve(Path.GetDirectoryName(episode.Path)!, true, null, null, isAbsoluteNaming); + // merge the missing information + episodeInfo.SeriesName = episodeInfoFromFolder?.SeriesName; + episodeInfo.EpisodeNumber ??= episodeInfoFromFolder?.EpisodeNumber; + episodeInfo.EndingEpisodeNumber ??= episodeInfoFromFolder?.EndingEpisodeNumber; + episodeInfo.SeasonNumber ??= episodeInfoFromFolder?.SeasonNumber; + episodeInfo.Container ??= episodeInfoFromFolder?.Container; + episodeInfo.Format3D ??= episodeInfoFromFolder?.Format3D; + episodeInfo.Is3D = episodeInfoFromFolder?.Is3D ?? episodeInfo.Is3D; + episodeInfo.IsStub = episodeInfoFromFolder?.IsStub ?? episodeInfo.IsStub; + episodeInfo.StubType = episodeInfoFromFolder?.StubType; + episodeInfo.IsByDate = episodeInfoFromFolder?.IsStub ?? episodeInfo.IsByDate; + episodeInfo.Day ??= episodeInfoFromFolder?.Day; + episodeInfo.Month ??= episodeInfoFromFolder?.Month; + episodeInfo.Year ??= episodeInfoFromFolder?.Year; + } + } + + episodeInfo ??= new EpisodeInfo(episode.Path); try { From e7fc18d0f31c5516889c9dbb65d3cb3421d8b271 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:28:27 +0200 Subject: [PATCH 1423/1930] Fix type check --- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index f92c300938..c69b8991b8 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2531,7 +2531,7 @@ namespace Emby.Server.Implementations.Library { episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new EpisodeInfo(episode.Path); // Resolve from parent folder if it's not the Season folder - if (!episodeInfo.EpisodeNumber.HasValue && episode.Parent is not Season) + if (!episodeInfo.EpisodeNumber.HasValue && episode.Parent.GetType() == typeof(Folder)) { var episodeInfoFromFolder = resolver.Resolve(Path.GetDirectoryName(episode.Path)!, true, null, null, isAbsoluteNaming); // merge the missing information From 69d2368fbcf734f48341edf73a9e8baae6229343 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:31:17 +0200 Subject: [PATCH 1424/1930] Copy paste error --- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index c69b8991b8..aed098e1b4 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2544,7 +2544,7 @@ namespace Emby.Server.Implementations.Library episodeInfo.Is3D = episodeInfoFromFolder?.Is3D ?? episodeInfo.Is3D; episodeInfo.IsStub = episodeInfoFromFolder?.IsStub ?? episodeInfo.IsStub; episodeInfo.StubType = episodeInfoFromFolder?.StubType; - episodeInfo.IsByDate = episodeInfoFromFolder?.IsStub ?? episodeInfo.IsByDate; + episodeInfo.IsByDate = episodeInfoFromFolder?.IsByDate ?? episodeInfo.IsByDate; episodeInfo.Day ??= episodeInfoFromFolder?.Day; episodeInfo.Month ??= episodeInfoFromFolder?.Month; episodeInfo.Year ??= episodeInfoFromFolder?.Year; From 457229c56de2bf13af8852611a9c47c4950f1561 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:43:40 +0200 Subject: [PATCH 1425/1930] Simplification --- Emby.Naming/TV/EpisodeResolver.cs | 5 ++++ .../Library/LibraryManager.cs | 25 ++++++------------- 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index f7df587864..eac192be51 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -68,6 +68,11 @@ namespace Emby.Naming.TV var parsingResult = new EpisodePathParser(_options) .Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo); + if (!parsingResult.Success) + { + return null; + } + return new EpisodeInfo(path) { Container = container, diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index aed098e1b4..f840f36955 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2529,25 +2529,16 @@ namespace Emby.Server.Implementations.Library EpisodeInfo episodeInfo = null; if (episode.IsFileProtocol) { - episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) ?? new EpisodeInfo(episode.Path); + episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming); // Resolve from parent folder if it's not the Season folder - if (!episodeInfo.EpisodeNumber.HasValue && episode.Parent.GetType() == typeof(Folder)) + if (episodeInfo == null && episode.Parent.GetType() == typeof(Folder)) { - var episodeInfoFromFolder = resolver.Resolve(Path.GetDirectoryName(episode.Path)!, true, null, null, isAbsoluteNaming); - // merge the missing information - episodeInfo.SeriesName = episodeInfoFromFolder?.SeriesName; - episodeInfo.EpisodeNumber ??= episodeInfoFromFolder?.EpisodeNumber; - episodeInfo.EndingEpisodeNumber ??= episodeInfoFromFolder?.EndingEpisodeNumber; - episodeInfo.SeasonNumber ??= episodeInfoFromFolder?.SeasonNumber; - episodeInfo.Container ??= episodeInfoFromFolder?.Container; - episodeInfo.Format3D ??= episodeInfoFromFolder?.Format3D; - episodeInfo.Is3D = episodeInfoFromFolder?.Is3D ?? episodeInfo.Is3D; - episodeInfo.IsStub = episodeInfoFromFolder?.IsStub ?? episodeInfo.IsStub; - episodeInfo.StubType = episodeInfoFromFolder?.StubType; - episodeInfo.IsByDate = episodeInfoFromFolder?.IsByDate ?? episodeInfo.IsByDate; - episodeInfo.Day ??= episodeInfoFromFolder?.Day; - episodeInfo.Month ??= episodeInfoFromFolder?.Month; - episodeInfo.Year ??= episodeInfoFromFolder?.Year; + episodeInfo = resolver.Resolve(Path.GetDirectoryName(episode.Path)!, true, null, null, isAbsoluteNaming); + if (episodeInfo != null) + { + // add the container + episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.'); + } } } From 53db1a1ffcba7edf9e5da677b6ed7e7e67f0d63a Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:47:47 +0200 Subject: [PATCH 1426/1930] ... --- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index f840f36955..dd678eca05 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2533,7 +2533,7 @@ namespace Emby.Server.Implementations.Library // Resolve from parent folder if it's not the Season folder if (episodeInfo == null && episode.Parent.GetType() == typeof(Folder)) { - episodeInfo = resolver.Resolve(Path.GetDirectoryName(episode.Path)!, true, null, null, isAbsoluteNaming); + episodeInfo = resolver.Resolve(episode.Parent.Path, true, null, null, isAbsoluteNaming); if (episodeInfo != null) { // add the container From 5c4be2416d89bf31c6f62042f833e8f91621d8f6 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 13:48:25 +0200 Subject: [PATCH 1427/1930] Remove unused import --- Emby.Server.Implementations/Library/LibraryManager.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index dd678eca05..ac50288273 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -27,7 +27,6 @@ using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.IO; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; From 381db60ed37c8d1fa56d57f9e63b750949ad974b Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 15:05:39 +0200 Subject: [PATCH 1428/1930] fix test --- Emby.Naming/TV/EpisodeResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index eac192be51..c63aec64e4 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -68,7 +68,7 @@ namespace Emby.Naming.TV var parsingResult = new EpisodePathParser(_options) .Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo); - if (!parsingResult.Success) + if (!parsingResult.Success && !isStub) { return null; } From ce4f73022116bb7910d7a73daf69f7a0624b2437 Mon Sep 17 00:00:00 2001 From: Mohamed Akram Date: Fri, 9 Apr 2021 20:02:23 +0400 Subject: [PATCH 1429/1930] Add support for TMDB series absolute and DVD order --- .../MediaBrowser.Providers.csproj | 2 +- .../Tmdb/TV/TmdbEpisodeImageProvider.cs | 2 +- .../Plugins/Tmdb/TV/TmdbEpisodeProvider.cs | 2 +- .../Plugins/Tmdb/TmdbClientManager.cs | 69 ++++++++++++++++++- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 152ea664a1..de7860b2e1 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -22,7 +22,7 @@ - + diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs index d923366242..ba18c542fe 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeImageProvider.cs @@ -65,7 +65,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here var episodeResult = await _tmdbClientManager - .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, null, null, cancellationToken) + .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, series.DisplayOrder, null, null, cancellationToken) .ConfigureAwait(false); var stills = episodeResult?.Images?.Stills; diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs index b455e56349..36e7fe91a1 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs @@ -92,7 +92,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV } var episodeResult = await _tmdbClientManager - .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken) + .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.SeriesDisplayOrder, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken) .ConfigureAwait(false); if (episodeResult == null) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index bf0f027fce..3aa673274f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -125,7 +125,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb tmdbId, language: TmdbUtils.NormalizeLanguage(language), includeImageLanguage: imageLanguages, - extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings, + extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings | TvShowMethods.EpisodeGroups, cancellationToken: cancellationToken).ConfigureAwait(false); if (series != null) @@ -136,6 +136,56 @@ namespace MediaBrowser.Providers.Plugins.Tmdb return series; } + /// + /// Gets a tv show episode group from the TMDb API based on the show id and the display order. + /// + /// The tv show's TMDb id. + /// The display order. + /// The tv show's language. + /// A comma-separated list of image languages. + /// The cancellation token. + /// The TMDb tv show episode group information or null if not found. + public async Task GetSeriesGroupAsync(int tvShowId, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken) + { + var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}"; + if (_memoryCache.TryGetValue(key, out TvGroupCollection group)) + { + return group; + } + + await EnsureClientConfigAsync().ConfigureAwait(false); + + TvGroupType? groupType = + displayOrder == "absolute" ? TvGroupType.Absolute : + displayOrder == "dvd" ? TvGroupType.DVD : + null; + + if (groupType == null) + { + return null; + } + + var series = await GetSeriesAsync(tvShowId, language, imageLanguages, cancellationToken); + var episodeGroupId = series.EpisodeGroups.Results.Find(g => g.Type == groupType)?.Id; + + if (episodeGroupId == null) + { + return null; + } + + group = await _tmDbClient.GetTvEpisodeGroupsAsync( + episodeGroupId, + language: TmdbUtils.NormalizeLanguage(language), + cancellationToken: cancellationToken).ConfigureAwait(false); + + if (group != null) + { + _memoryCache.Set(key, group, TimeSpan.FromHours(CacheDurationInHours)); + } + + return group; + } + /// /// Gets a tv season from the TMDb API based on the tv show's TMDb id. /// @@ -177,13 +227,14 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// The tv show's TMDb id. /// The season number. /// The episode number. + /// The display order. /// The episode's language. /// A comma-separated list of image languages. /// The cancellation token. /// The TMDb tv episode information or null if not found. - public async Task GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string language, string imageLanguages, CancellationToken cancellationToken) + public async Task GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken) { - var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{language}"; + var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}"; if (_memoryCache.TryGetValue(key, out TvEpisode episode)) { return episode; @@ -191,6 +242,18 @@ namespace MediaBrowser.Providers.Plugins.Tmdb await EnsureClientConfigAsync().ConfigureAwait(false); + var group = await GetSeriesGroupAsync(tvShowId, displayOrder, language, imageLanguages, cancellationToken); + if (group != null) + { + var season = group.Groups.Find(s => s.Order == seasonNumber); + var ep = season?.Episodes.Find(e => e.Order == episodeNumber - 1); + if (ep != null) + { + seasonNumber = ep.SeasonNumber; + episodeNumber = ep.EpisodeNumber; + } + } + episode = await _tmDbClient.GetTvEpisodeAsync( tvShowId, seasonNumber, From 1a3352003d0736d4d18513fb0055ae3b6452cded Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 23:02:36 +0200 Subject: [PATCH 1430/1930] don't die on dangling symlinks --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 679795dd2c..7c9b7c2d01 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -249,9 +249,18 @@ namespace Emby.Server.Implementations.IO // Issue #2354 get the size of files behind symbolic links if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) { - using (Stream thisFileStream = File.OpenRead(fileInfo.FullName)) + try { - result.Length = thisFileStream.Length; + using (Stream thisFileStream = File.OpenRead(fileInfo.FullName)) + { + result.Length = thisFileStream.Length; + } + } + catch (FileNotFoundException ex) + { + // Dangling symlinks cannot be detected before opening the file unfortunately... + Logger.LogError("Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", ex); + result.Exists = false; } } From f2cba352e58f5d52693875365fdd400ad7c11863 Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 9 Apr 2021 23:30:07 +0200 Subject: [PATCH 1431/1930] catch ioexception and include stack trace --- Emby.Server.Implementations/Library/LibraryManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 494eb59292..7f29e3e99a 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1917,14 +1917,14 @@ namespace Emby.Server.Implementations.Library _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path); continue; } - catch (InvalidOperationException) + catch (Exception ex) when (ex is InvalidOperationException || ex is IOException) { - _logger.LogWarning("Cannot fetch image from {ImagePath}", img.Path); + _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path); continue; } catch (HttpRequestException ex) { - _logger.LogWarning("Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode); + _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode); continue; } } From ef527df28f1a48f31aa4bbab36c9443075b68084 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 10 Apr 2021 00:06:48 +0200 Subject: [PATCH 1432/1930] Set mediatype to Audio for playlists in a music library --- .../Library/Resolvers/PlaylistResolver.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs index c76d41e5cc..5f051321f6 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs @@ -63,7 +63,8 @@ namespace Emby.Server.Implementations.Library.Resolvers { Path = args.Path, Name = Path.GetFileNameWithoutExtension(args.Path), - IsInMixedFolder = true + IsInMixedFolder = true, + PlaylistMediaType = MediaType.Audio }; } } From f99237cf9b7c2c33c18fefafe79d50b5b414781f Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Sat, 10 Apr 2021 00:16:37 +0200 Subject: [PATCH 1433/1930] Update Emby.Server.Implementations/IO/ManagedFileSystem.cs Co-authored-by: Cody Robibero --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 7c9b7c2d01..3893a15771 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -259,7 +259,7 @@ namespace Emby.Server.Implementations.IO catch (FileNotFoundException ex) { // Dangling symlinks cannot be detected before opening the file unfortunately... - Logger.LogError("Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", ex); + Logger.LogError(ex, "Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", fileInfo.FullName); result.Exists = false; } } From 321e383965cf593991c0cbd4e9367cce4e408dc2 Mon Sep 17 00:00:00 2001 From: Ian Walton Date: Fri, 9 Apr 2021 19:22:22 -0400 Subject: [PATCH 1434/1930] Fix setting audio stream in PlaybackInfo for jellyfin-web. --- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index a2d0e7030a..f07271821d 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -283,6 +283,7 @@ namespace Jellyfin.Api.Helpers if (streamInfo != null) { SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex; } } } @@ -327,6 +328,7 @@ namespace Jellyfin.Api.Helpers if (streamInfo != null) { SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex; } } } @@ -354,6 +356,7 @@ namespace Jellyfin.Api.Helpers // Do this after the above so that StartPositionTicks is set SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex; } } else @@ -391,6 +394,7 @@ namespace Jellyfin.Api.Helpers // Do this after the above so that StartPositionTicks is set SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token); + mediaSource.DefaultAudioStreamIndex = streamInfo.AudioStreamIndex; } } } From 117736aac9d0267c3a1a26192d564fc4e5541fe5 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 10 Apr 2021 17:09:45 +0200 Subject: [PATCH 1435/1930] Fix LogUnmatchedProfile formatting --- Emby.Dlna/DlnaManager.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index c94d803e1e..3417076dc1 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -126,14 +126,14 @@ namespace Emby.Dlna var builder = new StringBuilder(); builder.AppendLine("No matching device profile found. The default will need to be used."); - builder.Append("FriendlyName:").AppendLine(profile.FriendlyName); - builder.Append("Manufacturer:").AppendLine(profile.Manufacturer); - builder.Append("ManufacturerUrl:").AppendLine(profile.ManufacturerUrl); - builder.Append("ModelDescription:").AppendLine(profile.ModelDescription); - builder.Append("ModelName:").AppendLine(profile.ModelName); - builder.Append("ModelNumber:").AppendLine(profile.ModelNumber); - builder.Append("ModelUrl:").AppendLine(profile.ModelUrl); - builder.Append("SerialNumber:").AppendLine(profile.SerialNumber); + builder.Append("FriendlyName: ").AppendLine(profile.FriendlyName); + builder.Append("Manufacturer: ").AppendLine(profile.Manufacturer); + builder.Append("ManufacturerUrl: ").AppendLine(profile.ManufacturerUrl); + builder.Append("ModelDescription: ").AppendLine(profile.ModelDescription); + builder.Append("ModelName: ").AppendLine(profile.ModelName); + builder.Append("ModelNumber: ").AppendLine(profile.ModelNumber); + builder.Append("ModelUrl: ").AppendLine(profile.ModelUrl); + builder.Append("SerialNumber: ").AppendLine(profile.SerialNumber); _logger.LogInformation(builder.ToString()); } From 1fe26fe352a854523337842b16d6d0be5e68be5a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 10 Apr 2021 19:44:09 +0100 Subject: [PATCH 1436/1930] Work through dns failure on test. --- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index caea0d2658..b6bbfc5e12 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -382,6 +382,8 @@ namespace Jellyfin.Networking.Tests [InlineData("jellyfin.org", "eth16", false, "eth16")] // User on external network, no binding - so result is the 1st external. [InlineData("jellyfin.org", "", false, "eth11")] + // Dns failure - should skip the test. + [InlineData("ospoakdposkd.abc", "", false, "eth11")] // User assumed to be internal, no binding - so result is the 1st internal. [InlineData("", "", false, "eth16")] public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result) @@ -414,10 +416,13 @@ namespace Jellyfin.Networking.Tests _ = nm.TryParseInterface(result, out Collection? resultObj); - if (resultObj != null) + // Check to see if dns resolution is working. If not, skip test. + _ = IPHost.TryParse(source, out var host); + + if (resultObj != null && host?.HasAddress == true) { result = ((IPNetAddress)resultObj[0]).ToString(true); - var intf = nm.GetBindInterface(source, out int? _); + var intf = nm.GetBindInterface(source, out _); Assert.Equal(intf, result); } From be9cb7af2c38c41e466b565f39109489fdfb61aa Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 10 Apr 2021 22:42:09 +0200 Subject: [PATCH 1437/1930] Minor improvements to IPObjects --- MediaBrowser.Common/Net/IPHost.cs | 8 ++++---- MediaBrowser.Common/Net/IPNetAddress.cs | 16 ++++++++-------- MediaBrowser.Common/Net/IPObject.cs | 16 +++------------- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index d67b6b8e15..fb3ef9b12b 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -135,7 +135,7 @@ namespace MediaBrowser.Common.Net } // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. - int i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); + int i = host.IndexOf(']', StringComparison.Ordinal); if (i != -1) { return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); @@ -389,8 +389,8 @@ namespace MediaBrowser.Common.Net /// protected override IPObject CalculateNetworkAddress() { - var netAddr = NetworkAddressOf(this[0], PrefixLength); - return new IPNetAddress(netAddr.Address, netAddr.PrefixLength); + var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength); + return new IPNetAddress(address, prefixLength); } /// @@ -427,7 +427,7 @@ namespace MediaBrowser.Common.Net // Resolves the host name - so save a DNS lookup. if (string.Equals(HostName, "localhost", StringComparison.OrdinalIgnoreCase)) { - _addresses = new IPAddress[] { new IPAddress(Ipv4Loopback), new IPAddress(Ipv6Loopback) }; + _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }; return; } diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index 59e37a5c6c..589aad4b09 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Common.Net /// /// IP6Loopback address host. /// - public static readonly IPNetAddress IP6Loopback = IPNetAddress.Parse("::1"); + public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback); /// /// Object's IP address. @@ -113,7 +113,7 @@ namespace MediaBrowser.Common.Net } // Is it a network? - string[] tokens = addr.Split("/"); + string[] tokens = addr.Split('/'); if (tokens.Length == 2) { @@ -171,8 +171,8 @@ namespace MediaBrowser.Common.Net address = address.MapToIPv4(); } - var altAddress = NetworkAddressOf(address, PrefixLength); - return NetworkAddress.Address.Equals(altAddress.Address) && NetworkAddress.PrefixLength >= altAddress.PrefixLength; + var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength); + return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix; } /// @@ -196,8 +196,8 @@ namespace MediaBrowser.Common.Net return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength; } - var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength); - return NetworkAddress.Address.Equals(altAddress.Address); + var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength).address; + return NetworkAddress.Address.Equals(altAddress); } return false; @@ -270,8 +270,8 @@ namespace MediaBrowser.Common.Net /// protected override IPObject CalculateNetworkAddress() { - var value = NetworkAddressOf(_address, PrefixLength); - return new IPNetAddress(value.Address, value.PrefixLength); + var (address, prefixLength) = NetworkAddressOf(_address, PrefixLength); + return new IPNetAddress(address, prefixLength); } } } diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index 69cd57f8ae..3542dcd75e 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -10,16 +10,6 @@ namespace MediaBrowser.Common.Net /// public abstract class IPObject : IEquatable { - /// - /// IPv6 Loopback address. - /// - protected static readonly byte[] Ipv6Loopback = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; - - /// - /// IPv4 Loopback address. - /// - protected static readonly byte[] Ipv4Loopback = { 127, 0, 0, 1 }; - /// /// The network address of this object. /// @@ -64,7 +54,7 @@ namespace MediaBrowser.Common.Net /// IP Address to convert. /// Subnet prefix. /// IPAddress. - public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength) + public static (IPAddress address, byte prefixLength) NetworkAddressOf(IPAddress address, byte prefixLength) { if (address == null) { @@ -78,7 +68,7 @@ namespace MediaBrowser.Common.Net if (IsLoopback(address)) { - return (Address: address, PrefixLength: prefixLength); + return (address, prefixLength); } // An ip address is just a list of bytes, each one representing a segment on the network. @@ -110,7 +100,7 @@ namespace MediaBrowser.Common.Net } // Return the network address for the prefix. - return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); + return (new IPAddress(addressBytes), prefixLength); } /// From f2e74917550e8c5d532d180d01eeaa01d92a6cf2 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 10 Apr 2021 22:58:32 +0200 Subject: [PATCH 1438/1930] Do not check permissions for Folders collectiontype --- Jellyfin.Api/Controllers/ItemsController.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Controllers/ItemsController.cs b/Jellyfin.Api/Controllers/ItemsController.cs index 2c9760f6d0..74cf3b1624 100644 --- a/Jellyfin.Api/Controllers/ItemsController.cs +++ b/Jellyfin.Api/Controllers/ItemsController.cs @@ -246,8 +246,13 @@ namespace Jellyfin.Api.Controllers folder = _libraryManager.GetUserRootFolder(); } - if (folder is IHasCollectionType hasCollectionType - && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase)) + string? collectionType = null; + if (folder is IHasCollectionType hasCollectionType) + { + collectionType = hasCollectionType.CollectionType; + } + + if (string.Equals(collectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase)) { recursive = true; includeItemTypes = new[] { BaseItemKind.Playlist }; @@ -270,10 +275,11 @@ namespace Jellyfin.Api.Controllers } } - if (!(item is UserRootFolder) + if (item is not UserRootFolder && !isInEnabledFolder && !user.HasPermission(PermissionKind.EnableAllFolders) - && !user.HasPermission(PermissionKind.EnableAllChannels)) + && !user.HasPermission(PermissionKind.EnableAllChannels) + && !string.Equals(collectionType, CollectionType.Folders, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}.", user.Username, item.Name); return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}."); From 42bcf171d98276cd8472a8400e6bd960f475e19b Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 10 Apr 2021 23:54:35 +0200 Subject: [PATCH 1439/1930] Use sync Serialize when writing scheduled tasks to disk --- .../ScheduledTasks/ScheduledTaskWorker.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index a145a84237..3cc2cefb99 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -178,7 +178,8 @@ namespace Emby.Server.Implementations.ScheduledTasks lock (_lastExecutionResultSyncLock) { using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); - JsonSerializer.SerializeAsync(createStream, value, _jsonOptions); + using Utf8JsonWriter jsonStream = new Utf8JsonWriter(createStream); + JsonSerializer.Serialize(jsonStream, value, _jsonOptions); } } } @@ -578,7 +579,8 @@ namespace Emby.Server.Implementations.ScheduledTasks Directory.CreateDirectory(Path.GetDirectoryName(path)); using FileStream createStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); - JsonSerializer.SerializeAsync(createStream, triggers, _jsonOptions); + using Utf8JsonWriter jsonWriter = new Utf8JsonWriter(createStream); + JsonSerializer.Serialize(jsonWriter, triggers, _jsonOptions); } /// From 35cfd760d41a27676dfbe9f215ba913d9d71451b Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 11 Apr 2021 00:27:53 +0200 Subject: [PATCH 1440/1930] Do not touch "old" local artwork unless saving locally --- MediaBrowser.Providers/Manager/ImageSaver.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Manager/ImageSaver.cs b/MediaBrowser.Providers/Manager/ImageSaver.cs index 5bb85be7bf..fb1d4f4906 100644 --- a/MediaBrowser.Providers/Manager/ImageSaver.cs +++ b/MediaBrowser.Providers/Manager/ImageSaver.cs @@ -172,7 +172,9 @@ namespace MediaBrowser.Providers.Manager SetImagePath(item, type, imageIndex, savedPaths[0]); // Delete the current path - if (currentImageIsLocalFile && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase)) + if (currentImageIsLocalFile + && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase) + && (saveLocally || currentImagePath.Contains(_config.ApplicationPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase))) { var currentPath = currentImagePath; From 5fc664fd4f8e600887a4220abb366b75cc92ac01 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 11 Apr 2021 00:35:32 +0200 Subject: [PATCH 1441/1930] Add test for handling dangling symlinks --- jellyfin.ruleset | 2 ++ .../IO/ManagedFileSystemTests.cs | 25 +++++++++++++++++++ ...llyfin.Server.Implementations.Tests.csproj | 1 + 3 files changed, 28 insertions(+) diff --git a/jellyfin.ruleset b/jellyfin.ruleset index b012d2b003..19c0a08b23 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -78,5 +78,7 @@ + + diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 671c59b2ec..5a535ac51f 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -1,3 +1,7 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; using AutoFixture; using AutoFixture.AutoMoq; using Emby.Server.Implementations.IO; @@ -38,5 +42,26 @@ namespace Jellyfin.Server.Implementations.Tests.IO Assert.Equal(expectedAbsolutePath, generatedPath); } } + + [SkippableFact] + public void GetFileInfo_DanglingSymlink_ExistsFalse() + { + Skip.If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); + + string testFileDir = Path.Combine(Path.GetTempPath(), "jellyfin-test-data"); + string testFileName = Path.Combine(testFileDir, Path.GetRandomFileName() + "-danglingsym.link"); + + Directory.CreateDirectory(testFileDir); + Assert.Equal(0, symlink("thispathdoesntexist", testFileName)); + Assert.True(File.Exists(testFileName)); + + var metadata = _sut.GetFileInfo(testFileName); + Assert.False(metadata.Exists); + } + + [SuppressMessage("Naming Rules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Have to")] + [DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)] + [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] + private static extern int symlink(string target, string linkpath); } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index fe26ec3ae6..ee59dad5a8 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -28,6 +28,7 @@ + From 383aa4e4d9cf4b0997b9277df838728102e0db3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Wed, 17 Mar 2021 00:15:09 +0100 Subject: [PATCH 1442/1930] Add Resize to fill box alternative to image endpoints --- Jellyfin.Api/Controllers/ImageController.cs | 124 +++++++++++++++--- .../Drawing/ImageHelper.cs | 2 +- .../Drawing/ImageProcessingOptions.cs | 4 + MediaBrowser.Model/Drawing/DrawingUtils.cs | 48 +++++++ 4 files changed, 161 insertions(+), 17 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 2119e8e2c1..1da5677939 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -490,6 +490,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Supply the cache tag from the item object to receive strong caching headers. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. The of the returned image. @@ -528,7 +530,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -549,6 +553,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -570,6 +576,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Supply the cache tag from the item object to receive strong caching headers. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. The of the returned image. @@ -607,7 +615,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? unplayedCount, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -628,6 +638,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -648,6 +660,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Supply the cache tag from the item object to receive strong caching headers. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Determines the output format of the image - original,gif,jpg,png. @@ -686,7 +700,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute, Required] int imageIndex) + [FromRoute, Required] int imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -707,6 +723,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -731,6 +749,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -765,7 +785,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute, Required] int imageIndex) + [FromRoute, Required] int imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetArtist(name); if (item == null) @@ -786,6 +808,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -810,6 +834,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -844,7 +870,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetGenre(name); if (item == null) @@ -865,6 +893,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -890,6 +920,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -923,7 +955,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetGenre(name); if (item == null) @@ -944,6 +978,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -968,6 +1004,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1002,7 +1040,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetMusicGenre(name); if (item == null) @@ -1023,6 +1063,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1048,6 +1090,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1081,7 +1125,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetMusicGenre(name); if (item == null) @@ -1102,6 +1148,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1126,6 +1174,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1160,7 +1210,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetPerson(name); if (item == null) @@ -1181,6 +1233,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1206,6 +1260,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1239,7 +1295,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetPerson(name); if (item == null) @@ -1260,6 +1318,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1284,6 +1344,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1318,7 +1380,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetStudio(name); if (item == null) @@ -1339,6 +1403,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1364,6 +1430,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1397,7 +1465,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var item = _libraryManager.GetStudio(name); if (item == null) @@ -1418,6 +1488,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1442,6 +1514,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1476,7 +1550,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex) + [FromQuery] int? imageIndex, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var user = _userManager.GetUserById(userId); if (user?.ProfileImage == null) @@ -1514,6 +1590,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1540,6 +1618,8 @@ namespace Jellyfin.Api.Controllers /// The fixed image width to return. /// The fixed image height to return. /// Optional. Quality setting, from 0-100. Defaults to 90 and should suffice in most cases. + /// Width of box to fill. + /// Height of box to fill. /// Optional. Specify if whitespace should be cropped out of the image. True/False. If unspecified, whitespace will be cropped from logos and clear art. /// Optional. Add a played indicator. /// Optional. Blur image. @@ -1573,7 +1653,9 @@ namespace Jellyfin.Api.Controllers [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer) + [FromQuery] string? foregroundLayer, + [FromQuery] int? fillHeight, + [FromQuery] int? fillWidth) { var user = _userManager.GetUserById(userId); if (user?.ProfileImage == null) @@ -1611,6 +1693,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, + fillHeight, + fillWidth, cropWhitespace, addPlayedIndicator, blur, @@ -1695,6 +1779,8 @@ namespace Jellyfin.Api.Controllers int? width, int? height, int? quality, + int? fillHeight, + int? fillWidth, bool? cropWhitespace, // TODO: Remove bool? addPlayedIndicator, int? blur, @@ -1773,7 +1859,9 @@ namespace Jellyfin.Api.Controllers outputFormats, cacheDuration, responseHeaders, - isHeadRequest).ConfigureAwait(false); + isHeadRequest, + fillHeight, + fillWidth).ConfigureAwait(false); } private ImageFormat[] GetOutputFormats(ImageFormat? format) @@ -1871,7 +1959,9 @@ namespace Jellyfin.Api.Controllers IReadOnlyCollection supportedFormats, TimeSpan? cacheDuration, IDictionary headers, - bool isHeadRequest) + bool isHeadRequest, + int? fillHeight, + int? fillWidth) { if (!imageInfo.IsLocalFile && item != null) { @@ -1887,6 +1977,8 @@ namespace Jellyfin.Api.Controllers ItemId = itemId, MaxHeight = maxHeight, MaxWidth = maxWidth, + FillHeight = fillHeight, + FillWidth = fillWidth, Quality = quality ?? 100, Width = width, AddPlayedIndicator = addPlayedIndicator ?? false, diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 87c28d5773..7407261196 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.Drawing { // Determine the output size based on incoming parameters var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width ?? 0, options.Height ?? 0, options.MaxWidth ?? 0, options.MaxHeight ?? 0); - + newSize = DrawingUtils.ResizeFill(newSize, options.FillWidth, options.FillHeight); return newSize; } diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 22de9a43e8..4befb29c42 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -32,6 +32,10 @@ namespace MediaBrowser.Controller.Drawing public int? MaxHeight { get; set; } + public int? FillWidth { get; set; } + + public int? FillHeight { get; set; } + public int Quality { get; set; } public IReadOnlyCollection SupportedOutputFormats { get; set; } diff --git a/MediaBrowser.Model/Drawing/DrawingUtils.cs b/MediaBrowser.Model/Drawing/DrawingUtils.cs index 1512c52337..8fb9bdc0ac 100644 --- a/MediaBrowser.Model/Drawing/DrawingUtils.cs +++ b/MediaBrowser.Model/Drawing/DrawingUtils.cs @@ -57,6 +57,54 @@ namespace MediaBrowser.Model.Drawing return new ImageDimensions(newWidth, newHeight); } + /// + /// Resizes to fill box. + /// Returns original size if both width and height are null or zero. + /// + /// The original size object. + /// A new fixed width, if desired. + /// A new fixed height, if desired. + /// A new size object or size. + public static ImageDimensions ResizeFill( + ImageDimensions size, + int? fillWidth, + int? fillHeight) + { + // Return original size if input is invalid. + if ( + (fillWidth == null && fillHeight == null) + || (fillWidth == 0 || fillHeight == 0)) + { + return size; + } + + if (fillWidth == null || fillWidth == 0) + { + fillWidth = 1; + } + + if (fillHeight == null || fillHeight == 0) + { + fillHeight = 1; + } + + double widthRatio = (double)size.Width / (double)fillWidth; + double heightRatio = (double)size.Height / (double)fillHeight!; + // min() + double scaleRatio = widthRatio > heightRatio ? heightRatio : widthRatio; + + // Clamp to current size. + if (scaleRatio < 1) + { + return size; + } + + int newWidth = Convert.ToInt32(Math.Ceiling((double)size.Width / scaleRatio)); + int newHeight = Convert.ToInt32(Math.Ceiling((double)size.Height / scaleRatio)); + + return new ImageDimensions(newWidth, newHeight); + } + /// /// Gets the new width. /// From 13d0837b78011925d308e7ff593207b0e1cb330f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Wed, 17 Mar 2021 19:45:28 +0100 Subject: [PATCH 1443/1930] (mostly)Fix ResizeFill --- Jellyfin.Api/Controllers/ImageController.cs | 142 +++++++++--------- .../Drawing/ImageProcessingOptions.cs | 10 ++ MediaBrowser.Model/Drawing/DrawingUtils.cs | 12 +- 3 files changed, 86 insertions(+), 78 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 1da5677939..55c2fe735e 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -521,6 +521,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] string? tag, [FromQuery] bool? cropWhitespace, [FromQuery] ImageFormat? format, @@ -530,9 +532,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -553,8 +553,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -607,6 +607,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] string? tag, [FromQuery] bool? cropWhitespace, [FromQuery] ImageFormat? format, @@ -615,9 +617,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? unplayedCount, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -638,8 +638,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -691,6 +691,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromRoute, Required] string tag, [FromQuery] bool? cropWhitespace, [FromRoute, Required] ImageFormat format, @@ -700,9 +702,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute, Required] int imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromRoute, Required] int imageIndex) { var item = _libraryManager.GetItemById(itemId); if (item == null) @@ -723,8 +723,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -780,14 +780,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromRoute, Required] int imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromRoute, Required] int imageIndex) { var item = _libraryManager.GetArtist(name); if (item == null) @@ -808,8 +808,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -865,14 +865,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetGenre(name); if (item == null) @@ -893,8 +893,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -951,13 +951,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetGenre(name); if (item == null) @@ -978,8 +978,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1035,14 +1035,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetMusicGenre(name); if (item == null) @@ -1063,8 +1063,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1121,13 +1121,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetMusicGenre(name); if (item == null) @@ -1148,8 +1148,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1205,14 +1205,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetPerson(name); if (item == null) @@ -1233,8 +1233,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1291,13 +1291,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetPerson(name); if (item == null) @@ -1318,8 +1318,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1375,14 +1375,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var item = _libraryManager.GetStudio(name); if (item == null) @@ -1403,8 +1403,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1461,13 +1461,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var item = _libraryManager.GetStudio(name); if (item == null) @@ -1488,8 +1488,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1545,14 +1545,14 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, [FromQuery] string? foregroundLayer, - [FromQuery] int? imageIndex, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] int? imageIndex) { var user = _userManager.GetUserById(userId); if (user?.ProfileImage == null) @@ -1590,8 +1590,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1649,13 +1649,13 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? width, [FromQuery] int? height, [FromQuery] int? quality, + [FromQuery] int? fillWidth, + [FromQuery] int? fillHeight, [FromQuery] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, - [FromQuery] string? foregroundLayer, - [FromQuery] int? fillHeight, - [FromQuery] int? fillWidth) + [FromQuery] string? foregroundLayer) { var user = _userManager.GetUserById(userId); if (user?.ProfileImage == null) @@ -1693,8 +1693,8 @@ namespace Jellyfin.Api.Controllers width, height, quality, - fillHeight, fillWidth, + fillHeight, cropWhitespace, addPlayedIndicator, blur, @@ -1779,8 +1779,8 @@ namespace Jellyfin.Api.Controllers int? width, int? height, int? quality, - int? fillHeight, int? fillWidth, + int? fillHeight, bool? cropWhitespace, // TODO: Remove bool? addPlayedIndicator, int? blur, @@ -1844,11 +1844,13 @@ namespace Jellyfin.Api.Controllers item, itemId, imageIndex, - height, - maxHeight, - maxWidth, - quality, width, + height, + maxWidth, + maxHeight, + fillWidth, + fillHeight, + quality, addPlayedIndicator, percentPlayed, unplayedCount, @@ -1859,9 +1861,7 @@ namespace Jellyfin.Api.Controllers outputFormats, cacheDuration, responseHeaders, - isHeadRequest, - fillHeight, - fillWidth).ConfigureAwait(false); + isHeadRequest).ConfigureAwait(false); } private ImageFormat[] GetOutputFormats(ImageFormat? format) @@ -1944,11 +1944,13 @@ namespace Jellyfin.Api.Controllers BaseItem? item, Guid itemId, int? index, - int? height, - int? maxHeight, - int? maxWidth, - int? quality, int? width, + int? height, + int? maxWidth, + int? maxHeight, + int? fillWidth, + int? fillHeight, + int? quality, bool? addPlayedIndicator, double? percentPlayed, int? unplayedCount, @@ -1959,9 +1961,7 @@ namespace Jellyfin.Api.Controllers IReadOnlyCollection supportedFormats, TimeSpan? cacheDuration, IDictionary headers, - bool isHeadRequest, - int? fillHeight, - int? fillWidth) + bool isHeadRequest) { if (!imageInfo.IsLocalFile && item != null) { diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 4befb29c42..e1a2811ac7 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -97,6 +97,16 @@ namespace MediaBrowser.Controller.Drawing return false; } + if (FillWidth.HasValue && sizeValue.Width > FillWidth.Value) + { + return false; + } + + if (FillHeight.HasValue && sizeValue.Height > FillHeight.Value) + { + return false; + } + return true; } diff --git a/MediaBrowser.Model/Drawing/DrawingUtils.cs b/MediaBrowser.Model/Drawing/DrawingUtils.cs index 8fb9bdc0ac..c2a144f817 100644 --- a/MediaBrowser.Model/Drawing/DrawingUtils.cs +++ b/MediaBrowser.Model/Drawing/DrawingUtils.cs @@ -58,7 +58,7 @@ namespace MediaBrowser.Model.Drawing } /// - /// Resizes to fill box. + /// Scale down to fill box. /// Returns original size if both width and height are null or zero. /// /// The original size object. @@ -71,9 +71,8 @@ namespace MediaBrowser.Model.Drawing int? fillHeight) { // Return original size if input is invalid. - if ( - (fillWidth == null && fillHeight == null) - || (fillWidth == 0 || fillHeight == 0)) + if ((fillWidth == null || fillWidth == 0) + && (fillHeight == null || fillHeight == 0)) { return size; } @@ -89,9 +88,8 @@ namespace MediaBrowser.Model.Drawing } double widthRatio = (double)size.Width / (double)fillWidth; - double heightRatio = (double)size.Height / (double)fillHeight!; - // min() - double scaleRatio = widthRatio > heightRatio ? heightRatio : widthRatio; + double heightRatio = (double)size.Height / (double)fillHeight; + double scaleRatio = Math.Min(widthRatio, heightRatio); // Clamp to current size. if (scaleRatio < 1) From e57c1655fb2b7d92db33ff3a3b6b09a09b69cf68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Wed, 17 Mar 2021 20:46:45 +0100 Subject: [PATCH 1444/1930] Remove GetSizeEstimate & GetEstimatedAspectRatio from MediaBrowser.Controller.Drawing.ImageHelper Rework GetCacheFilePath to take requested with and height parameters in stead of using estimated output size --- Emby.Drawing/ImageProcessor.cs | 112 +++++++++++++++--- .../Drawing/ImageHelper.cs | 66 +---------- 2 files changed, 101 insertions(+), 77 deletions(-) diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 978173d5a2..646620c435 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -171,11 +171,26 @@ namespace Emby.Drawing return (originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); } - ImageDimensions newSize = ImageHelper.GetNewImageSize(options, null); int quality = options.Quality; ImageFormat outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); - string cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); + string cacheFilePath = GetCacheFilePath( + originalImagePath, + options.Width, + options.Height, + options.MaxWidth, + options.MaxHeight, + options.FillWidth, + options.FillHeight, + quality, + dateModified, + outputFormat, + options.AddPlayedIndicator, + options.PercentPlayed, + options.UnplayedCount, + options.Blur, + options.BackgroundColor, + options.ForegroundLayer); try { @@ -241,48 +256,111 @@ namespace Emby.Drawing /// /// Gets the cache file path based on a set of parameters. /// - private string GetCacheFilePath(string originalPath, ImageDimensions outputSize, int quality, DateTime dateModified, ImageFormat format, bool addPlayedIndicator, double percentPlayed, int? unwatchedCount, int? blur, string backgroundColor, string foregroundLayer) + private string GetCacheFilePath( + string originalPath, + int? width, + int? height, + int? maxWidth, + int? maxHeight, + int? fillWidth, + int? fillHeight, + int quality, + DateTime dateModified, + ImageFormat format, + bool addPlayedIndicator, + double percentPlayed, + int? unwatchedCount, + int? blur, + string backgroundColor, + string foregroundLayer) { - var filename = originalPath - + "width=" + outputSize.Width - + "height=" + outputSize.Height - + "quality=" + quality - + "datemodified=" + dateModified.Ticks - + "f=" + format; + System.Text.StringBuilder filename = new System.Text.StringBuilder(128); + filename.Append(originalPath); + + filename.Append(",quality="); + filename.Append(quality); + + filename.Append(",datemodified="); + filename.Append(dateModified.Ticks); + + filename.Append(",f="); + filename.Append(format); + + if (width.HasValue) + { + filename.Append(",width="); + filename.Append(width.Value); + } + + if (height.HasValue) + { + filename.Append(",height="); + filename.Append(height.Value); + } + + if (maxWidth.HasValue) + { + filename.Append(",maxwidth="); + filename.Append(maxWidth.Value); + } + + if (maxHeight.HasValue) + { + filename.Append(",maxheight="); + filename.Append(maxHeight.Value); + } + + if (fillWidth.HasValue) + { + filename.Append(",fillwidth="); + filename.Append(fillWidth.Value); + } + + if (fillHeight.HasValue) + { + filename.Append(",fillheight="); + filename.Append(fillHeight.Value); + } if (addPlayedIndicator) { - filename += "pl=true"; + filename.Append(",pl=true"); } if (percentPlayed > 0) { - filename += "p=" + percentPlayed; + filename.Append(",p="); + filename.Append(percentPlayed); } if (unwatchedCount.HasValue) { - filename += "p=" + unwatchedCount.Value; + filename.Append(",p="); + filename.Append(unwatchedCount.Value); } if (blur.HasValue) { - filename += "blur=" + blur.Value; + filename.Append(",blur="); + filename.Append(blur.Value); } if (!string.IsNullOrEmpty(backgroundColor)) { - filename += "b=" + backgroundColor; + filename.Append(",b="); + filename.Append(backgroundColor); } if (!string.IsNullOrEmpty(foregroundLayer)) { - filename += "fl=" + foregroundLayer; + filename.Append(",fl="); + filename.Append(foregroundLayer); } - filename += "v=" + Version; + filename.Append(",v="); + filename.Append(Version); - return GetCachePath(ResizedImageCachePath, filename, "." + format.ToString().ToLowerInvariant()); + return GetCachePath(ResizedImageCachePath, filename.ToString(), "." + format.ToString().ToLowerInvariant()); } /// diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 7407261196..181f8e905f 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -1,4 +1,5 @@ #pragma warning disable CS1591 +#nullable enable using System; using MediaBrowser.Controller.Entities; @@ -9,67 +10,12 @@ namespace MediaBrowser.Controller.Drawing { public static class ImageHelper { - public static ImageDimensions GetNewImageSize(ImageProcessingOptions options, ImageDimensions? originalImageSize) + public static ImageDimensions GetNewImageSize(ImageProcessingOptions options, ImageDimensions originalImageSize) { - if (originalImageSize.HasValue) - { - // Determine the output size based on incoming parameters - var newSize = DrawingUtils.Resize(originalImageSize.Value, options.Width ?? 0, options.Height ?? 0, options.MaxWidth ?? 0, options.MaxHeight ?? 0); - newSize = DrawingUtils.ResizeFill(newSize, options.FillWidth, options.FillHeight); - return newSize; - } - - return GetSizeEstimate(options); - } - - private static ImageDimensions GetSizeEstimate(ImageProcessingOptions options) - { - if (options.Width.HasValue && options.Height.HasValue) - { - return new ImageDimensions(options.Width.Value, options.Height.Value); - } - - double aspect = GetEstimatedAspectRatio(options.Image.Type, options.Item); - - int? width = options.Width ?? options.MaxWidth; - - if (width.HasValue) - { - int heightValue = Convert.ToInt32((double)width.Value / aspect); - return new ImageDimensions(width.Value, heightValue); - } - - var height = options.Height ?? options.MaxHeight ?? 200; - int widthValue = Convert.ToInt32(aspect * height); - return new ImageDimensions(widthValue, height); - } - - private static double GetEstimatedAspectRatio(ImageType type, BaseItem item) - { - switch (type) - { - case ImageType.Art: - case ImageType.Backdrop: - case ImageType.Chapter: - case ImageType.Screenshot: - case ImageType.Thumb: - return 1.78; - case ImageType.Banner: - return 5.4; - case ImageType.Box: - case ImageType.BoxRear: - case ImageType.Disc: - case ImageType.Menu: - case ImageType.Profile: - return 1; - case ImageType.Logo: - return 2.58; - case ImageType.Primary: - double defaultPrimaryImageAspectRatio = item.GetDefaultPrimaryImageAspectRatio(); - return defaultPrimaryImageAspectRatio > 0 ? defaultPrimaryImageAspectRatio : 2.0 / 3; - default: - return 1; - } + // Determine the output size based on incoming parameters + var newSize = DrawingUtils.Resize(originalImageSize, options.Width ?? 0, options.Height ?? 0, options.MaxWidth ?? 0, options.MaxHeight ?? 0); + newSize = DrawingUtils.ResizeFill(newSize, options.FillWidth, options.FillHeight); + return newSize; } } } From afff226514a6f645a6738f1e407208826b84f1d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Thu, 18 Mar 2021 23:40:45 +0100 Subject: [PATCH 1445/1930] Apply suggestions from code review Co-authored-by: Cody Robibero --- MediaBrowser.Model/Drawing/DrawingUtils.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Model/Drawing/DrawingUtils.cs b/MediaBrowser.Model/Drawing/DrawingUtils.cs index c2a144f817..5567927682 100644 --- a/MediaBrowser.Model/Drawing/DrawingUtils.cs +++ b/MediaBrowser.Model/Drawing/DrawingUtils.cs @@ -87,8 +87,8 @@ namespace MediaBrowser.Model.Drawing fillHeight = 1; } - double widthRatio = (double)size.Width / (double)fillWidth; - double heightRatio = (double)size.Height / (double)fillHeight; + double widthRatio = size.Width / (double)fillWidth; + double heightRatio = size.Height / (double)fillHeight; double scaleRatio = Math.Min(widthRatio, heightRatio); // Clamp to current size. @@ -97,8 +97,8 @@ namespace MediaBrowser.Model.Drawing return size; } - int newWidth = Convert.ToInt32(Math.Ceiling((double)size.Width / scaleRatio)); - int newHeight = Convert.ToInt32(Math.Ceiling((double)size.Height / scaleRatio)); + int newWidth = Convert.ToInt32(Math.Ceiling(size.Width / scaleRatio)); + int newHeight = Convert.ToInt32(Math.Ceiling(size.Height / scaleRatio)); return new ImageDimensions(newWidth, newHeight); } From e0edbc5754ad4d6afad1f01874ca2085d4f0791d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Mon, 29 Mar 2021 00:46:19 +0200 Subject: [PATCH 1446/1930] Apply suggestions from code review Co-authored-by: Claus Vium --- Emby.Drawing/ImageProcessor.cs | 2 +- MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 646620c435..78b53f36a2 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -274,7 +274,7 @@ namespace Emby.Drawing string backgroundColor, string foregroundLayer) { - System.Text.StringBuilder filename = new System.Text.StringBuilder(128); + var filename = new StringBuilder(128); filename.Append(originalPath); filename.Append(",quality="); diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index e1a2811ac7..230a0af60c 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -97,12 +97,7 @@ namespace MediaBrowser.Controller.Drawing return false; } - if (FillWidth.HasValue && sizeValue.Width > FillWidth.Value) - { - return false; - } - - if (FillHeight.HasValue && sizeValue.Height > FillHeight.Value) + if (sizeValue.Width > FillWidth || sizeValue.Height > FillHeight) { return false; } From d0857cf6553ffa9560b42720af04e0b5ebcc9c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Odd=20Str=C3=A5b=C3=B8?= Date: Mon, 29 Mar 2021 00:48:59 +0200 Subject: [PATCH 1447/1930] Fix build, increase StringBuilder starting size --- Emby.Drawing/ImageProcessor.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs index 78b53f36a2..7d952aa23b 100644 --- a/Emby.Drawing/ImageProcessor.cs +++ b/Emby.Drawing/ImageProcessor.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Text; using System.Threading.Tasks; using Jellyfin.Data.Entities; using MediaBrowser.Common.Extensions; @@ -274,7 +275,7 @@ namespace Emby.Drawing string backgroundColor, string foregroundLayer) { - var filename = new StringBuilder(128); + var filename = new StringBuilder(256); filename.Append(originalPath); filename.Append(",quality="); From 01491796a285a621c6aebe4f886ee74413e5fbee Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 11 Apr 2021 12:57:28 +0200 Subject: [PATCH 1448/1930] Enable Workstation GC mode --- Jellyfin.Server/Jellyfin.Server.csproj | 1 + debian/conf/jellyfin | 5 +++++ fedora/jellyfin.env | 4 ++++ 3 files changed, 10 insertions(+) diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index e7f83aff16..98d9903440 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -9,6 +9,7 @@ jellyfin Exe net5.0 + false false true true diff --git a/debian/conf/jellyfin b/debian/conf/jellyfin index 7cbfa88ee8..9ebaf2bd88 100644 --- a/debian/conf/jellyfin +++ b/debian/conf/jellyfin @@ -33,6 +33,11 @@ JELLYFIN_FFMPEG_OPT="--ffmpeg=/usr/lib/jellyfin-ffmpeg/ffmpeg" # [OPTIONAL] run Jellyfin without the web app #JELLYFIN_NOWEBAPP_OPT="--nowebclient" +# [OPTIONAL] run Jellyfin with ASP.NET Server Garbage Collection (uses more RAM and less CPU than Workstation GC) +# 0 = Workstation +# 1 = Server +#COMPlus_gcServer=1 + # # SysV init/Upstart options # diff --git a/fedora/jellyfin.env b/fedora/jellyfin.env index bf64acd3f9..56b7a3558d 100644 --- a/fedora/jellyfin.env +++ b/fedora/jellyfin.env @@ -35,3 +35,7 @@ JELLYFIN_RESTART_OPT="--restartpath=/usr/libexec/jellyfin/restart.sh" # [OPTIONAL] run Jellyfin without the web app #JELLYFIN_NOWEBAPP_OPT="--noautorunwebapp" +# [OPTIONAL] run Jellyfin with ASP.NET Server Garbage Collection (uses more RAM and less CPU than Workstation GC) +# 0 = Workstation +# 1 = Server +#COMPlus_gcServer=1 From 7aa53b060e5e7c4315e203034114b9d585d039da Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sun, 11 Apr 2021 14:34:45 -0400 Subject: [PATCH 1449/1930] Add label commenter workflow Right now the main purpose is to handle instructions for stable backports. Can be expanded in the future. --- .github/workflows/label-commenter-config.yml | 41 ++++++++++++++++++++ .github/workflows/label-commenter.yml | 22 +++++++++++ 2 files changed, 63 insertions(+) create mode 100644 .github/workflows/label-commenter-config.yml create mode 100644 .github/workflows/label-commenter.yml diff --git a/.github/workflows/label-commenter-config.yml b/.github/workflows/label-commenter-config.yml new file mode 100644 index 0000000000..6ee967f55d --- /dev/null +++ b/.github/workflows/label-commenter-config.yml @@ -0,0 +1,41 @@ +comment: + header: Hello @{{ issue.user.login }} + footer: "\ + ---\n\n + > This is an automated comment created by the [peaceiris/actions-label-commenter]. \ + Responding to the bot or mentioning it won't have any effect.\n\n + [peaceiris/actions-label-commenter]: https://github.com/peaceiris/actions-label-commenter + " + +labels: + - name: stable backport + labeled: + pr: + body: | + This pull request has been tagged as a stable backport. It will be cherry-picked into the next stable point release. + + Please observe the following: + + * Any dependent PRs that this PR requires **must** be tagged for stable backporting as well. + + * Any issue(s) this PR fixes or closes **should** target the current stable release or a previous stable release to which a fix has not yet entered the current stable release. + + * This PR **must** be test cherry-picked against the current release branch (`release-X.Y.z` where X and Y are numbers). It must apply cleanly, or a diff of the expected change must be provided. + + To do this, run the following commands from your local copy of the Jellyfin repository: + + 1. `git checkout master` + + 1. `git merge --no-ff ` + + 1. `git log` -> `commit xxxxxxxxx`, grab hash + + 1. `git checkout release-X.Y.z` replacing X and Y with the *current* stable version (e.g. `release-10.7.z`) + + 1. `git cherry-pick -sx -m1 ` + + Ensure the `cherry-pick` applies cleanly. If it does not, fix any merge conflicts *preserving as much of the original code as possible*, and make note of the resulting diff. + + **Do not** push your merges to either branch. Use `git reset --hard HEAD~1` to revert both branches to their original state. + + Reply to this PR with a comment beginning "Cherry-pick test completed." and including the merge-conflict-ixing diff(s) if applicable. diff --git a/.github/workflows/label-commenter.yml b/.github/workflows/label-commenter.yml new file mode 100644 index 0000000000..be9216cc19 --- /dev/null +++ b/.github/workflows/label-commenter.yml @@ -0,0 +1,22 @@ +name: Label Commenter + +on: + issues: + types: + - labeled + - unlabeled + pull_request_target: + types: + - labeled + - unlabeled + +jobs: + comment: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + with: + ref: master + + - name: Label Commenter + uses: peaceiris/actions-label-commenter@v1 From f381c536342760a53db85a1ed527091da2d3abfc Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sun, 11 Apr 2021 14:51:45 -0400 Subject: [PATCH 1450/1930] Fix typo --- .github/workflows/label-commenter-config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/label-commenter-config.yml b/.github/workflows/label-commenter-config.yml index 6ee967f55d..c12c5cf85c 100644 --- a/.github/workflows/label-commenter-config.yml +++ b/.github/workflows/label-commenter-config.yml @@ -38,4 +38,4 @@ labels: **Do not** push your merges to either branch. Use `git reset --hard HEAD~1` to revert both branches to their original state. - Reply to this PR with a comment beginning "Cherry-pick test completed." and including the merge-conflict-ixing diff(s) if applicable. + Reply to this PR with a comment beginning "Cherry-pick test completed." and including the merge-conflict-fixing diff(s) if applicable. From 4deccd451ea09c3c34d9236f3b7426277b32a0bb Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sun, 11 Apr 2021 16:31:10 -0400 Subject: [PATCH 1451/1930] Mention testing too --- .github/workflows/label-commenter-config.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/label-commenter-config.yml b/.github/workflows/label-commenter-config.yml index c12c5cf85c..78b75be434 100644 --- a/.github/workflows/label-commenter-config.yml +++ b/.github/workflows/label-commenter-config.yml @@ -36,6 +36,8 @@ labels: Ensure the `cherry-pick` applies cleanly. If it does not, fix any merge conflicts *preserving as much of the original code as possible*, and make note of the resulting diff. + Test your changes with a build to ensure they are successful. If not, adjust the diff accordingly. + **Do not** push your merges to either branch. Use `git reset --hard HEAD~1` to revert both branches to their original state. Reply to this PR with a comment beginning "Cherry-pick test completed." and including the merge-conflict-fixing diff(s) if applicable. From a4ffc7a813389e8cc2e075d3c9e740a66896ad5c Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 12 Apr 2021 00:28:17 +0200 Subject: [PATCH 1452/1930] Fix random failing of tests Fully initialize the configuration manager at the init stage ``` Failed Jellyfin.Server.Integration.Tests.Controllers.ActivityLogControllerTests.ActivityLog_GetEntries_Ok [2 s] Error Message: MediaBrowser.Common.Extensions.ResourceNotFoundException : Configuration with key metadata not found. Stack Trace: at Emby.Server.Implementations.AppBase.BaseConfigurationManager.<>c__DisplayClass43_0.b__0(String k) in D:\a\1\s\Emby.Server.Implementations\AppBase\BaseConfigurationManager.cs:line 309 at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Emby.Server.Implementations.AppBase.BaseConfigurationManager.GetConfiguration(String key) in D:\a\1\s\Emby.Server.Implementations\AppBase\BaseConfigurationManager.cs:line 300 at MediaBrowser.Common.Configuration.ConfigurationManagerExtensions.GetConfiguration[T](IConfigurationManager manager, String key) in D:\a\1\s\MediaBrowser.Common\Configuration\IConfigurationManager.cs:line 88 at MediaBrowser.Controller.Library.MetadataConfigurationExtensions.GetMetadataConfiguration(IConfigurationManager config) in D:\a\1\s\MediaBrowser.Controller\Library\MetadataConfigurationStore.cs:line 28 at Emby.Server.Implementations.Library.ResolverHelper.SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemMetadata info) in D:\a\1\s\Emby.Server.Implementations\Library\ResolverHelper.cs:line 159 at Emby.Server.Implementations.Library.ResolverHelper.EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args) in D:\a\1\s\Emby.Server.Implementations\Library\ResolverHelper.cs:line 153 at Emby.Server.Implementations.Library.ResolverHelper.SetInitialItemValues(BaseItem item, ItemResolveArgs args, IFileSystem fileSystem, ILibraryManager libraryManager) in D:\a\1\s\Emby.Server.Implementations\Library\ResolverHelper.cs:line 81 at Emby.Server.Implementations.Library.LibraryManager.ResolveItem(ItemResolveArgs args, IItemResolver[] resolvers) in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 480 at Emby.Server.Implementations.Library.LibraryManager.ResolvePath(FileSystemMetadata fileInfo, IDirectoryService directoryService, IItemResolver[] resolvers, Folder parent, String collectionType, LibraryOptions libraryOptions) in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 618 at Emby.Server.Implementations.Library.LibraryManager.ResolvePath(FileSystemMetadata fileInfo, Folder parent) in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 536 at Emby.Server.Implementations.Library.LibraryManager.CreateRootFolder() in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 732 at Emby.Server.Implementations.Library.LibraryManager.get_RootFolder() in D:\a\1\s\Emby.Server.Implementations\Library\LibraryManager.cs:line 180 at Emby.Server.Implementations.IO.LibraryMonitor.Start() in D:\a\1\s\Emby.Server.Implementations\IO\LibraryMonitor.cs:line 135 at Emby.Server.Implementations.IO.LibraryMonitorStartup.RunAsync() in D:\a\1\s\Emby.Server.Implementations\IO\LibraryMonitorStartup.cs:line 26 at Emby.Server.Implementations.ApplicationHost.StartEntryPoints(IEnumerable`1 entryPoints, Boolean isBeforeStartup)+MoveNext() in D:\a\1\s\Emby.Server.Implementations\ApplicationHost.cs:line 541 at System.Threading.Tasks.Task.WhenAll(IEnumerable`1 tasks) at Emby.Server.Implementations.ApplicationHost.RunStartupTasksAsync(CancellationToken cancellationToken) in D:\a\1\s\Emby.Server.Implementations\ApplicationHost.cs:line 525 at Jellyfin.Server.Integration.Tests.JellyfinApplicationFactory.CreateServer(IWebHostBuilder builder) in D:\a\1\s\tests\Jellyfin.Server.Integration.Tests\JellyfinApplicationFactory.cs:line 101 at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer() at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient() at Jellyfin.Server.Integration.Tests.Controllers.ActivityLogControllerTests.ActivityLog_GetEntries_Ok() in D:\a\1\s\tests\Jellyfin.Server.Integration.Tests\Controllers\ActivityLogControllerTests.cs:line 21 --- End of stack trace from previous location --- ``` --- .../ApplicationHost.cs | 87 ++++++++----------- Jellyfin.Server/Migrations/MigrationRunner.cs | 8 +- Jellyfin.Server/Program.cs | 2 +- .../MetadataConfigurationExtensions.cs | 15 ++++ .../Library/MetadataConfigurationStore.cs | 12 +-- 5 files changed, 59 insertions(+), 65 deletions(-) create mode 100644 MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 3846de5fd4..0512adf106 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -210,7 +210,7 @@ namespace Emby.Server.Implementations /// Gets or sets the configuration manager. /// /// The configuration manager. - protected IConfigurationManager ConfigurationManager { get; set; } + public ServerConfigurationManager ConfigurationManager { get; set; } /// /// Gets or sets the service provider. @@ -232,12 +232,6 @@ namespace Emby.Server.Implementations /// public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey]; - /// - /// Gets the server configuration manager. - /// - /// The server configuration manager. - public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager; - /// /// Initializes a new instance of the class. /// @@ -255,43 +249,26 @@ namespace Emby.Server.Implementations IFileSystem fileSystem, IServiceCollection serviceCollection) { - _xmlSerializer = new MyXmlSerializer(); - - ServiceCollection = serviceCollection; - ApplicationPaths = applicationPaths; LoggerFactory = loggerFactory; - _fileSystemManager = fileSystem; - - ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); - // Have to migrate settings here as migration subsystem not yet initialised. - MigrateNetworkConfiguration(); - - // Have to pre-register the NetworkConfigurationFactory, as the configuration sub-system is not yet initialised. - ConfigurationManager.RegisterConfiguration(); - NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger()); - - Logger = LoggerFactory.CreateLogger(); - _startupOptions = options; _startupConfig = startupConfig; + _fileSystemManager = fileSystem; + ServiceCollection = serviceCollection; - // Initialize runtime stat collection - if (ServerConfigurationManager.Configuration.EnableMetrics) - { - DotNetRuntimeStatsBuilder.Default().StartCollecting(); - } - + Logger = LoggerFactory.CreateLogger(); fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem)); ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version; ApplicationVersionString = ApplicationVersion.ToString(3); ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString; + _xmlSerializer = new MyXmlSerializer(); + ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager); _pluginManager = new PluginManager( LoggerFactory.CreateLogger(), this, - ServerConfigurationManager.Configuration, + ConfigurationManager.Configuration, ApplicationPaths.PluginsPath, ApplicationVersion); } @@ -306,9 +283,9 @@ namespace Emby.Server.Implementations if (!File.Exists(path)) { var networkSettings = new NetworkConfiguration(); - ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings); + ClassMigrationHelper.CopyProperties(ConfigurationManager.Configuration, networkSettings); _xmlSerializer.SerializeToFile(networkSettings, path); - Logger?.LogDebug("Successfully migrated network settings."); + Logger.LogDebug("Successfully migrated network settings."); } } @@ -545,7 +522,21 @@ namespace Emby.Server.Implementations /// public void Init() { - var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); + DiscoverTypes(); + + ConfigurationManager.AddParts(GetExports()); + + // Have to migrate settings here as migration subsystem not yet initialised. + MigrateNetworkConfiguration(); + NetManager = new NetworkManager(ConfigurationManager, LoggerFactory.CreateLogger()); + + // Initialize runtime stat collection + if (ConfigurationManager.Configuration.EnableMetrics) + { + DotNetRuntimeStatsBuilder.Default().StartCollecting(); + } + + var networkConfiguration = ConfigurationManager.GetNetworkConfiguration(); HttpPort = networkConfiguration.HttpServerPortNumber; HttpsPort = networkConfiguration.HttpsPortNumber; @@ -563,8 +554,6 @@ namespace Emby.Server.Implementations }; Certificate = GetCertificate(CertificateInfo); - DiscoverTypes(); - RegisterServices(); _pluginManager.RegisterServices(ServiceCollection); @@ -579,7 +568,8 @@ namespace Emby.Server.Implementations ServiceCollection.AddMemoryCache(); - ServiceCollection.AddSingleton(ConfigurationManager); + ServiceCollection.AddSingleton(ConfigurationManager); + ServiceCollection.AddSingleton(ConfigurationManager); ServiceCollection.AddSingleton(this); ServiceCollection.AddSingleton(_pluginManager); ServiceCollection.AddSingleton(ApplicationPaths); @@ -606,8 +596,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(this); ServiceCollection.AddSingleton(ApplicationPaths); - ServiceCollection.AddSingleton(ServerConfigurationManager); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -796,7 +784,7 @@ namespace Emby.Server.Implementations { // For now there's no real way to inject these properly BaseItem.Logger = Resolve>(); - BaseItem.ConfigurationManager = ServerConfigurationManager; + BaseItem.ConfigurationManager = ConfigurationManager; BaseItem.LibraryManager = Resolve(); BaseItem.ProviderManager = Resolve(); BaseItem.LocalizationManager = Resolve(); @@ -818,13 +806,12 @@ namespace Emby.Server.Implementations /// private void FindParts() { - if (!ServerConfigurationManager.Configuration.IsPortAuthorized) + if (!ConfigurationManager.Configuration.IsPortAuthorized) { - ServerConfigurationManager.Configuration.IsPortAuthorized = true; + ConfigurationManager.Configuration.IsPortAuthorized = true; ConfigurationManager.SaveConfiguration(); } - ConfigurationManager.AddParts(GetExports()); _pluginManager.CreatePlugins(); _urlPrefixes = GetUrlPrefixes().ToArray(); @@ -928,7 +915,7 @@ namespace Emby.Server.Implementations protected void OnConfigurationUpdated(object sender, EventArgs e) { var requiresRestart = false; - var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration(); + var networkConfiguration = ConfigurationManager.GetNetworkConfiguration(); // Don't do anything if these haven't been set yet if (HttpPort != 0 && HttpsPort != 0) @@ -937,10 +924,10 @@ namespace Emby.Server.Implementations if (networkConfiguration.HttpServerPortNumber != HttpPort || networkConfiguration.HttpsPortNumber != HttpsPort) { - if (ServerConfigurationManager.Configuration.IsPortAuthorized) + if (ConfigurationManager.Configuration.IsPortAuthorized) { - ServerConfigurationManager.Configuration.IsPortAuthorized = false; - ServerConfigurationManager.SaveConfiguration(); + ConfigurationManager.Configuration.IsPortAuthorized = false; + ConfigurationManager.SaveConfiguration(); requiresRestart = true; } @@ -1156,7 +1143,7 @@ namespace Emby.Server.Implementations } /// - public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.GetNetworkConfiguration().EnableHttps; + public bool ListenWithHttps => Certificate != null && ConfigurationManager.GetNetworkConfiguration().EnableHttps; /// public string GetSmartApiUrl(IPAddress ipAddress, int? port = null) @@ -1240,14 +1227,14 @@ namespace Emby.Server.Implementations Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp), Host = host, Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort), - Path = ServerConfigurationManager.GetNetworkConfiguration().BaseUrl + Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl }.ToString().TrimEnd('/'); } public string FriendlyName => - string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName) + string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName) ? Environment.MachineName - : ServerConfigurationManager.Configuration.ServerName; + : ConfigurationManager.Configuration.ServerName; /// /// Shuts down. diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs index 305660ae65..cf938ab8cd 100644 --- a/Jellyfin.Server/Migrations/MigrationRunner.cs +++ b/Jellyfin.Server/Migrations/MigrationRunner.cs @@ -40,15 +40,15 @@ namespace Jellyfin.Server.Migrations .Select(m => ActivatorUtilities.CreateInstance(host.ServiceProvider, m)) .OfType() .ToArray(); - var migrationOptions = ((IConfigurationManager)host.ServerConfigurationManager).GetConfiguration(MigrationsListStore.StoreKey); + var migrationOptions = ((IConfigurationManager)host.ConfigurationManager).GetConfiguration(MigrationsListStore.StoreKey); - if (!host.ServerConfigurationManager.Configuration.IsStartupWizardCompleted && migrationOptions.Applied.Count == 0) + if (!host.ConfigurationManager.Configuration.IsStartupWizardCompleted && migrationOptions.Applied.Count == 0) { // If startup wizard is not finished, this is a fresh install. // Don't run any migrations, just mark all of them as applied. logger.LogInformation("Marking all known migrations as applied because this is a fresh install"); migrationOptions.Applied.AddRange(migrations.Where(m => !m.PerformOnNewInstall).Select(m => (m.Id, m.Name))); - host.ServerConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions); + host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions); } var appliedMigrationIds = migrationOptions.Applied.Select(m => m.Id).ToHashSet(); @@ -77,7 +77,7 @@ namespace Jellyfin.Server.Migrations // Mark the migration as completed logger.LogInformation("Migration '{Name}' applied successfully", migrationRoutine.Name); migrationOptions.Applied.Add((migrationRoutine.Id, migrationRoutine.Name)); - host.ServerConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions); + host.ConfigurationManager.SaveConfiguration(MigrationsListStore.StoreKey, migrationOptions); logger.LogDebug("Migration '{Name}' marked as applied in configuration.", migrationRoutine.Name); } } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 4f203b7a9d..464e024190 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -173,7 +173,7 @@ namespace Jellyfin.Server // If hosting the web client, validate the client content path if (startupConfig.HostWebClient()) { - string? webContentPath = appHost.ServerConfigurationManager.ApplicationPaths.WebPath; + string? webContentPath = appHost.ConfigurationManager.ApplicationPaths.WebPath; if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0) { throw new InvalidOperationException( diff --git a/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs new file mode 100644 index 0000000000..884f9e7735 --- /dev/null +++ b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs @@ -0,0 +1,15 @@ +#pragma warning disable CS1591 + +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Configuration; + +namespace MediaBrowser.Controller.Library +{ + public static class MetadataConfigurationExtensions + { + public static MetadataConfiguration GetMetadataConfiguration(this IConfigurationManager config) + { + return config.GetConfiguration("metadata"); + } + } +} diff --git a/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs b/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs index f16304db01..a6be6c0d3c 100644 --- a/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs +++ b/MediaBrowser.Controller/Library/MetadataConfigurationStore.cs @@ -14,18 +14,10 @@ namespace MediaBrowser.Controller.Library { new ConfigurationStore { - Key = "metadata", - ConfigurationType = typeof(MetadataConfiguration) + Key = "metadata", + ConfigurationType = typeof(MetadataConfiguration) } }; } } - - public static class MetadataConfigurationExtensions - { - public static MetadataConfiguration GetMetadataConfiguration(this IConfigurationManager config) - { - return config.GetConfiguration("metadata"); - } - } } From 10d358c8da4f5e323c81a5880625737e025d2ba0 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 12 Apr 2021 10:28:24 +0100 Subject: [PATCH 1453/1930] Update tests/Jellyfin.Networking.Tests/NetworkParseTests.cs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Odd Stråbø --- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index b6bbfc5e12..63182974eb 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -383,7 +383,8 @@ namespace Jellyfin.Networking.Tests // User on external network, no binding - so result is the 1st external. [InlineData("jellyfin.org", "", false, "eth11")] // Dns failure - should skip the test. - [InlineData("ospoakdposkd.abc", "", false, "eth11")] + // https://en.wikipedia.org/wiki/.test + [InlineData("invalid.domain.test", "", false, "eth11")] // User assumed to be internal, no binding - so result is the 1st internal. [InlineData("", "", false, "eth16")] public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result) From cc59abd54e7be6a58187bfb3d01dbe0ec7ea9a1d Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Mon, 12 Apr 2021 07:50:24 -0600 Subject: [PATCH 1454/1930] Mark cropWhitespace parameter as obsolete (#5751) --- Jellyfin.Api/Controllers/ImageController.cs | 45 +++++++-------------- 1 file changed, 14 insertions(+), 31 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 55c2fe735e..36facf75a4 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -524,7 +524,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, [FromQuery] string? tag, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] ImageFormat? format, [FromQuery] bool? addPlayedIndicator, [FromQuery] double? percentPlayed, @@ -555,7 +555,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -610,7 +609,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, [FromQuery] string? tag, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] ImageFormat? format, [FromQuery] bool? addPlayedIndicator, [FromQuery] double? percentPlayed, @@ -640,7 +639,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -694,7 +692,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, [FromRoute, Required] string tag, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromRoute, Required] ImageFormat format, [FromQuery] bool? addPlayedIndicator, [FromRoute, Required] double percentPlayed, @@ -725,7 +723,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -782,7 +779,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -810,7 +807,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -867,7 +863,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -895,7 +891,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -953,7 +948,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -980,7 +975,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1037,7 +1031,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1065,7 +1059,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1123,7 +1116,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1150,7 +1143,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1207,7 +1199,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1235,7 +1227,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1293,7 +1284,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1320,7 +1311,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1377,7 +1367,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1405,7 +1395,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1463,7 +1452,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1490,7 +1479,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1547,7 +1535,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1592,7 +1580,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1651,7 +1638,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? quality, [FromQuery] int? fillWidth, [FromQuery] int? fillHeight, - [FromQuery] bool? cropWhitespace, + [FromQuery, ParameterObsolete] bool? cropWhitespace, [FromQuery] bool? addPlayedIndicator, [FromQuery] int? blur, [FromQuery] string? backgroundColor, @@ -1695,7 +1682,6 @@ namespace Jellyfin.Api.Controllers quality, fillWidth, fillHeight, - cropWhitespace, addPlayedIndicator, blur, backgroundColor, @@ -1781,7 +1767,6 @@ namespace Jellyfin.Api.Controllers int? quality, int? fillWidth, int? fillHeight, - bool? cropWhitespace, // TODO: Remove bool? addPlayedIndicator, int? blur, string? backgroundColor, @@ -1823,8 +1808,6 @@ namespace Jellyfin.Api.Controllers } } - cropWhitespace ??= imageType == ImageType.Logo || imageType == ImageType.Art; - var outputFormats = GetOutputFormats(format); TimeSpan? cacheDuration = null; From dc4714fe4098eed42114adc3455f4a2982cc18d6 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Mon, 12 Apr 2021 19:54:32 +0200 Subject: [PATCH 1455/1930] fix webp compatibility testing (#5787) --- Jellyfin.Api/Controllers/ImageController.cs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index 36facf75a4..8f7500ac69 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -1859,17 +1859,15 @@ namespace Jellyfin.Api.Controllers private ImageFormat[] GetClientSupportedFormats() { - var acceptTypes = Request.Headers[HeaderNames.Accept]; - var supportedFormats = new List(); - if (acceptTypes.Count > 0) + var supportedFormats = Request.Headers.GetCommaSeparatedValues(HeaderNames.Accept); + for (var i = 0; i < supportedFormats.Length; i++) { - foreach (var type in acceptTypes) + // Remove charsets etc. (anything after semi-colon) + var type = supportedFormats[i]; + int index = type.IndexOf(';', StringComparison.Ordinal); + if (index != -1) { - int index = type.IndexOf(';', StringComparison.Ordinal); - if (index != -1) - { - supportedFormats.Add(type.Substring(0, index)); - } + supportedFormats[i] = type.Substring(0, index); } } From 8045a488ceccc5c85195be3ef694a418c1c326aa Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 12 Apr 2021 22:01:35 +0200 Subject: [PATCH 1456/1930] Fix possible ArgumentNullException ``` Error Message: System.ArgumentNullException : Value cannot be null. (Parameter 'source') Stack Trace: at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector) at Emby.Server.Implementations.Library.LibraryManager.ResolveItem(ItemResolveArgs args, IItemResolver[] resolvers) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 475 at Emby.Server.Implementations.Library.LibraryManager.ResolvePath(FileSystemMetadata fileInfo, IDirectoryService directoryService, IItemResolver[] resolvers, Folder parent, String collectionType, LibraryOptions libraryOptions) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 618 at Emby.Server.Implementations.Library.LibraryManager.ResolvePath(FileSystemMetadata fileInfo, Folder parent) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 536 at Emby.Server.Implementations.Library.LibraryManager.GetUserRootFolder() in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 812 at Emby.Server.Implementations.Library.LibraryManager.GetCollectionFolders(BaseItem item) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 2080 at Emby.Server.Implementations.Library.LibraryManager.GetLibraryOptions(BaseItem item) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 2116 at MediaBrowser.Providers.Manager.ProviderManager.SaveMetadata(BaseItem item, ItemUpdateType updateType, IEnumerable`1 savers) in /home/vsts/work/1/s/MediaBrowser.Providers/Manager/ProviderManager.cs:line 672 at MediaBrowser.Providers.Manager.ProviderManager.SaveMetadata(BaseItem item, ItemUpdateType updateType) in /home/vsts/work/1/s/MediaBrowser.Providers/Manager/ProviderManager.cs:line 655 at Emby.Server.Implementations.Library.LibraryManager.RunMetadataSavers(BaseItem item, ItemUpdateType updateReason) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 2017 at Emby.Server.Implementations.Library.LibraryManager.UpdateItemsAsync(IReadOnlyList`1 items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken) in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 1975 at Emby.Server.Implementations.Library.LibraryManager.CreateRootFolder() in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 775 at Emby.Server.Implementations.Library.LibraryManager.get_RootFolder() in /home/vsts/work/1/s/Emby.Server.Implementations/Library/LibraryManager.cs:line 180 at Emby.Server.Implementations.IO.LibraryMonitor.Start() in /home/vsts/work/1/s/Emby.Server.Implementations/IO/LibraryMonitor.cs:line 135 at Emby.Server.Implementations.IO.LibraryMonitorStartup.RunAsync() in /home/vsts/work/1/s/Emby.Server.Implementations/IO/LibraryMonitorStartup.cs:line 26 at Emby.Server.Implementations.ApplicationHost.StartEntryPoints(IEnumerable`1 entryPoints, Boolean isBeforeStartup)+MoveNext() in /home/vsts/work/1/s/Emby.Server.Implementations/ApplicationHost.cs:line 518 at System.Threading.Tasks.Task.WhenAll(IEnumerable`1 tasks) at Emby.Server.Implementations.ApplicationHost.RunStartupTasksAsync(CancellationToken cancellationToken) in /home/vsts/work/1/s/Emby.Server.Implementations/ApplicationHost.cs:line 502 at Jellyfin.Server.Integration.Tests.JellyfinApplicationFactory.CreateServer(IWebHostBuilder builder) in /home/vsts/work/1/s/tests/Jellyfin.Server.Integration.Tests/JellyfinApplicationFactory.cs:line 101 at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer() at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient() at Jellyfin.Server.Integration.Tests.Controllers.ActivityLogControllerTests.ActivityLog_GetEntries_Ok() in /home/vsts/work/1/s/tests/Jellyfin.Server.Integration.Tests/Controllers/ActivityLogControllerTests.cs:line 21 --- End of stack trace from previous location --- ``` --- Emby.Server.Implementations/Library/LibraryManager.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 7f29e3e99a..6a9f4174dc 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -196,13 +196,13 @@ namespace Emby.Server.Implementations.Library /// Gets or sets the postscan tasks. /// /// The postscan tasks. - private ILibraryPostScanTask[] PostscanTasks { get; set; } + private ILibraryPostScanTask[] PostscanTasks { get; set; } = Array.Empty(); /// /// Gets or sets the intro providers. /// /// The intro providers. - private IIntroProvider[] IntroProviders { get; set; } + private IIntroProvider[] IntroProviders { get; set; } = Array.Empty(); /// /// Gets or sets the list of entity resolution ignore rules. @@ -214,15 +214,15 @@ namespace Emby.Server.Implementations.Library /// Gets or sets the list of currently registered entity resolvers. /// /// The entity resolvers enumerable. - private IItemResolver[] EntityResolvers { get; set; } + private IItemResolver[] EntityResolvers { get; set; } = Array.Empty(); - private IMultiItemResolver[] MultiItemResolvers { get; set; } + private IMultiItemResolver[] MultiItemResolvers { get; set; } = Array.Empty(); /// /// Gets or sets the comparers. /// /// The comparers. - private IBaseItemComparer[] Comparers { get; set; } + private IBaseItemComparer[] Comparers { get; set; } = Array.Empty(); public bool IsScanRunning { get; private set; } From fe54e9ae9de932d2130f15d90df40da9dbc048fe Mon Sep 17 00:00:00 2001 From: Rich Lander Date: Mon, 12 Apr 2021 17:16:26 -0700 Subject: [PATCH 1457/1930] Remove coupling to distro - The substring `-buster-slim` isn't useful/correct. - .NET 6 (from my team) is based exclusively on bullseye. - If you update just `DOTNET_VERSION` to `6.0`, `docker build` will fail. - If the goal is to force using `buster` throughout the Dockerfile, then making `DOTNET_VERSION` configurable isn't correct. - Context: https://github.com/dotnet/dotnet-docker/blob/main/src/runtime-deps/6.0/bullseye-slim/amd64/Dockerfile#L1 Just saw this as a drive by look at your code. Is intended as helpful context. --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index cafee737a1..ebe5eb00c6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine- && npm ci --no-audit \ && mv dist /dist -FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim as builder +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder WORKDIR /repo COPY . . ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 From 63355af5186756df0538fdf56e99c045864f9ff1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Apr 2021 13:09:10 +0000 Subject: [PATCH 1458/1930] Bump BlurHashSharp.SkiaSharp from 1.1.1 to 1.2.0 Bumps [BlurHashSharp.SkiaSharp](https://github.com/Bond-009/BlurHashSharp) from 1.1.1 to 1.2.0. - [Release notes](https://github.com/Bond-009/BlurHashSharp/releases) - [Commits](https://github.com/Bond-009/BlurHashSharp/commits/v1.2.0) Signed-off-by: dependabot[bot] --- Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj index 5f9c4d6792..ee43c2159a 100644 --- a/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj +++ b/Jellyfin.Drawing.Skia/Jellyfin.Drawing.Skia.csproj @@ -21,7 +21,7 @@ - + From f1c4b541c1d3ef960921a9480022467a940adae0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Apr 2021 13:09:28 +0000 Subject: [PATCH 1459/1930] Bump TMDbLib from 1.7.3-alpha to 1.8.1 Bumps [TMDbLib](https://github.com/LordMike/TMDbLib) from 1.7.3-alpha to 1.8.1. - [Release notes](https://github.com/LordMike/TMDbLib/releases) - [Commits](https://github.com/LordMike/TMDbLib/compare/v1.7.3-alpha...v1.8.1) Signed-off-by: dependabot[bot] --- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 152ea664a1..de7860b2e1 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -22,7 +22,7 @@ - + From b11718a01d7341f37840893398f158e6cbcd5f9b Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 13 Apr 2021 07:12:49 -0600 Subject: [PATCH 1460/1930] Properly redirect healthcheck endpoint if using BaseUrl --- .../BaseUrlRedirectionMiddleware.cs | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs index c23da2fd63..4dda900b05 100644 --- a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs +++ b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs @@ -45,16 +45,27 @@ namespace Jellyfin.Server.Middleware var localPath = httpContext.Request.Path.ToString(); var baseUrlPrefix = serverConfigurationManager.GetNetworkConfiguration().BaseUrl; - if (string.Equals(localPath, baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase) - || string.Equals(localPath, baseUrlPrefix, StringComparison.OrdinalIgnoreCase) - || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase) - || string.IsNullOrEmpty(localPath) - || !localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(baseUrlPrefix)) { - // Always redirect back to the default path if the base prefix is invalid or missing - _logger.LogDebug("Normalizing an URL at {LocalPath}", localPath); - httpContext.Response.Redirect(baseUrlPrefix + "/" + _configuration[ConfigurationExtensions.DefaultRedirectKey]); - return; + if (!localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase) + && localPath.EndsWith("/health", StringComparison.OrdinalIgnoreCase)) + { + _logger.LogDebug("Redirecting /health check"); + httpContext.Response.Redirect(baseUrlPrefix + "/health"); + return; + } + + if (string.Equals(localPath, baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase) + || string.Equals(localPath, baseUrlPrefix, StringComparison.OrdinalIgnoreCase) + || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase) + || string.IsNullOrEmpty(localPath) + || !localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase)) + { + // Always redirect back to the default path if the base prefix is invalid or missing + _logger.LogDebug("Normalizing an URL at {LocalPath}", localPath); + httpContext.Response.Redirect(baseUrlPrefix + "/" + _configuration[ConfigurationExtensions.DefaultRedirectKey]); + return; + } } await _next(httpContext).ConfigureAwait(false); From 723b6abcb392b1a65e46db91aa35f7e13de0c2a8 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 13 Apr 2021 15:37:11 +0200 Subject: [PATCH 1461/1930] Optimize the way items are grouped into collections --- .../Collections/CollectionManager.cs | 66 ++++++++++++------- MediaBrowser.Controller/Entities/Folder.cs | 4 +- 2 files changed, 43 insertions(+), 27 deletions(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index db532ce5b4..6dbbd55304 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -124,7 +124,7 @@ namespace Emby.Server.Implementations.Collections private IEnumerable GetCollections(User user) { - var folder = GetCollectionsFolder(false).Result; + var folder = GetCollectionsFolder(false).GetAwaiter().GetResult(); return folder == null ? Enumerable.Empty() @@ -319,11 +319,11 @@ namespace Emby.Server.Implementations.Collections { var results = new Dictionary(); - var allBoxsets = GetCollections(user).ToList(); + var allBoxSets = GetCollections(user).ToList(); foreach (var item in items) { - if (!(item is ISupportsBoxSetGrouping)) + if (item is not ISupportsBoxSetGrouping) { results[item.Id] = item; } @@ -331,33 +331,49 @@ namespace Emby.Server.Implementations.Collections { var itemId = item.Id; - var currentBoxSets = allBoxsets - .Where(i => i.ContainsLinkedChildByItemId(itemId)) - .ToList(); - - if (currentBoxSets.Count > 0) + var itemIsInBoxSet = false; + foreach (var boxSet in allBoxSets) { - foreach (var boxset in currentBoxSets) + if (!boxSet.ContainsLinkedChildByItemId(itemId)) { - results[boxset.Id] = boxset; + continue; + } + + itemIsInBoxSet = true; + + if (results.ContainsKey(boxSet.Id)) + { + continue; + } + + results[boxSet.Id] = boxSet; + } + + // skip any item that is in a box set + if (itemIsInBoxSet) + { + continue; + } + + var alreadyInResults = false; + // this is kind of a performance hack because only Video has alternate versions that should be in a box set? + if (item is Video video) + { + foreach (var childId in video.GetLocalAlternateVersionIds()) + { + if (!results.ContainsKey(childId)) + { + continue; + } + + alreadyInResults = true; + break; } } - else - { - var alreadyInResults = false; - foreach (var child in item.GetMediaSources(true)) - { - if (Guid.TryParse(child.Id, out var id) && results.ContainsKey(id)) - { - alreadyInResults = true; - break; - } - } - if (!alreadyInResults) - { - results[item.Id] = item; - } + if (!alreadyInResults) + { + results[item.Id] = item; } } } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index cac5026f70..485733abbc 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1434,9 +1434,9 @@ namespace MediaBrowser.Controller.Entities var linkedChildren = LinkedChildren; foreach (var i in linkedChildren) { - if (i.ItemId.HasValue && i.ItemId.Value == itemId) + if (i.ItemId.HasValue) { - return true; + return i.ItemId.Value == itemId; } var child = GetLinkedChild(i); From 2b948aead910f12ce89da9099d6cefce2810cf8a Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 13 Apr 2021 19:53:09 +0200 Subject: [PATCH 1462/1930] Fix possible ArgumentNullException ``` System.ArgumentNullException: Value cannot be null. (Parameter 'source') at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate) at MediaBrowser.Providers.Manager.ProviderManager.GetImages(BaseItem item, IRemoteImageProvider provider, IReadOnlyCollection`1 preferredLanguages, CancellationToken cancellationToken, Nullable`1 type) in /home/bond/dev/jellyfin/MediaBrowser.Providers/Manager/ProviderManager.cs:line 280 ``` --- .../Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs index a96fc8ed63..326c116b3b 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesImageProvider.cs @@ -54,7 +54,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV if (string.IsNullOrEmpty(tmdbId)) { - return null; + return Enumerable.Empty(); } var language = item.GetPreferredMetadataLanguage(); From 27202ae8aa2bd92d69a92328e8e762acddb64add Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Apr 2021 17:11:34 +0000 Subject: [PATCH 1463/1930] Bump AutoFixture from 4.15.0 to 4.16.0 Bumps [AutoFixture](https://github.com/AutoFixture/AutoFixture) from 4.15.0 to 4.16.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.15.0...v4.16.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index f288561b74..1306783c94 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index ee59dad5a8..38de05ad07 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 8d4d9e3d23..d7e56ff135 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 4a5cf1feee..51d6333b73 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -10,7 +10,7 @@ - + From d459f625d53d3469f2334c1978ed2779fb0a433a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Apr 2021 17:11:49 +0000 Subject: [PATCH 1464/1930] Bump Newtonsoft.Json from 12.0.3 to 13.0.1 Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 12.0.3 to 13.0.1. - [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases) - [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/12.0.3...13.0.1) Signed-off-by: dependabot[bot] --- MediaBrowser.Providers/MediaBrowser.Providers.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index de7860b2e1..cdb07a15da 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -19,7 +19,7 @@ - + From 3d0a42da9e52f53acd797e8f93f6f76fa0ef3f06 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 13 Apr 2021 20:09:50 +0200 Subject: [PATCH 1465/1930] Remove throttle in refresh code --- .../Manager/ProviderManager.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index b4b0b826f4..82ee59da90 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -1074,17 +1074,16 @@ namespace MediaBrowser.Providers.Manager try { var item = libraryManager.GetItemById(refreshItem.Item1); - if (item != null) + if (item == null) { - // Try to throttle this a little bit. - await Task.Delay(100, cancellationToken).ConfigureAwait(false); - - var task = item is MusicArtist artist - ? RefreshArtist(artist, refreshItem.Item2, cancellationToken) - : RefreshItem(item, refreshItem.Item2, cancellationToken); - - await task.ConfigureAwait(false); + continue; } + + var task = item is MusicArtist artist + ? RefreshArtist(artist, refreshItem.Item2, cancellationToken) + : RefreshItem(item, refreshItem.Item2, cancellationToken); + + await task.ConfigureAwait(false); } catch (OperationCanceledException) { From d44b2e2ee5ecb06016b8b88eb03fc6dc28a04ee9 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 13 Apr 2021 20:12:50 +0200 Subject: [PATCH 1466/1930] fixes --- .../Collections/CollectionManager.cs | 9 ++------- MediaBrowser.Controller/Entities/Folder.cs | 7 ++++++- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 6dbbd55304..81758d9a76 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -341,12 +341,7 @@ namespace Emby.Server.Implementations.Collections itemIsInBoxSet = true; - if (results.ContainsKey(boxSet.Id)) - { - continue; - } - - results[boxSet.Id] = boxSet; + results.TryAdd(boxSet.Id, boxSet); } // skip any item that is in a box set @@ -373,7 +368,7 @@ namespace Emby.Server.Implementations.Collections if (!alreadyInResults) { - results[item.Id] = item; + results[itemId] = item; } } } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 485733abbc..bd1fbb4731 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1436,7 +1436,12 @@ namespace MediaBrowser.Controller.Entities { if (i.ItemId.HasValue) { - return i.ItemId.Value == itemId; + if (i.ItemId.Value == itemId) + { + return true; + } + + continue; } var child = GetLinkedChild(i); From 0b774eac12a882fbdc1ed402f36aaf6e4341e2c2 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 14 Apr 2021 10:26:05 +0100 Subject: [PATCH 1467/1930] Enables the ability to bind to loopback address. (#5773) --- Jellyfin.Networking/Manager/NetworkManager.cs | 70 +++++++++++-------- MediaBrowser.Common/Net/NetworkExtensions.cs | 2 +- .../NetworkParseTests.cs | 10 +-- 3 files changed, 48 insertions(+), 34 deletions(-) diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 2f5a5b6e33..73e8b2cd72 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -647,6 +647,16 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses.AddItem(address, false); _interfaceNames[parts[2]] = Math.Abs(index); } + + if (IsIP4Enabled) + { + _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); + } + + if (IsIP6Enabled) + { + _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + } } InitialiseLAN(config); @@ -978,8 +988,8 @@ namespace Jellyfin.Networking.Manager } // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses); - _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses); + _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses); + _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses); _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } @@ -1153,36 +1163,40 @@ namespace Jellyfin.Networking.Manager } #pragma warning restore CA1031 // Do not catch general exception types } - - _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); - - // If for some reason we don't have an interface info, resolve our DNS name. - if (_interfaceAddresses.Count == 0) - { - _logger.LogError("No interfaces information available. Resolving DNS name."); - IPHost host = new IPHost(Dns.GetHostName()); - foreach (var a in host.GetAddresses()) - { - _interfaceAddresses.AddItem(a); - } - - if (_interfaceAddresses.Count == 0) - { - _logger.LogWarning("No interfaces information available. Using loopback."); - // Last ditch attempt - use loopback address. - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback, false); - if (IsIP6Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback, false); - } - } - } } - catch (NetworkInformationException ex) + catch (Exception ex) { _logger.LogError(ex, "Error in InitialiseInterfaces."); } + + // If for some reason we don't have an interface info, resolve our DNS name. + if (_interfaceAddresses.Count == 0) + { + _logger.LogError("No interfaces information available. Resolving DNS name."); + IPHost host = new IPHost(Dns.GetHostName()); + foreach (var a in host.GetAddresses()) + { + _interfaceAddresses.AddItem(a); + } + + if (_interfaceAddresses.Count == 0) + { + _logger.LogWarning("No interfaces information available. Using loopback."); + } + } + + if (IsIP4Enabled) + { + _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); + } + + if (IsIP6Enabled) + { + _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + } + + _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); + _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 93cfb4817b..264bfacb49 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -232,7 +232,7 @@ namespace MediaBrowser.Common.Net /// The . /// Collection to compare with. /// A collection containing all the matches. - public static Collection Union(this Collection source, Collection target) + public static Collection ThatAreContainedInNetworks(this Collection source, Collection target) { if (source.Count == 0) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 2d33569980..9b0da2b3c4 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -34,10 +34,10 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] // eth16 only [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] - // All interfaces excluded. - [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] + // All interfaces excluded. (including loopbacks) + [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[127.0.0.1/8,::1/128]")] // vEthernet1 and vEthernet212 should be excluded. - [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24]")] + [InlineData("192.168.1.200/24,-20,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.200/24", "[200.200.200.200/24,127.0.0.1/8,::1/128]")] // Overlapping interface, [InlineData("192.168.1.110/24,-20,br0|192.168.1.10/24,-16,br0|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.110/24,192.168.1.10/24]")] public void IgnoreVirtualInterfaces(string interfaces, string lan, string value) @@ -241,7 +241,7 @@ namespace Jellyfin.Networking.Tests Collection nc1 = nm.CreateIPCollection(settings.Split(','), false); Collection nc2 = nm.CreateIPCollection(compare.Split(','), false); - Assert.Equal(nc1.Union(nc2).AsString(), result); + Assert.Equal(nc1.ThatAreContainedInNetworks(nc2).AsString(), result); } [Theory] @@ -350,7 +350,7 @@ namespace Jellyfin.Networking.Tests // Test included, IP6. Collection ncSource = nm.CreateIPCollection(source.Split(',')); Collection ncDest = nm.CreateIPCollection(dest.Split(',')); - Collection ncResult = ncSource.Union(ncDest); + Collection ncResult = ncSource.ThatAreContainedInNetworks(ncDest); Collection resultCollection = nm.CreateIPCollection(result.Split(',')); Assert.True(ncResult.Compare(resultCollection)); } From 55700e0d1cc83557f5d5da3d5250bb3702215a04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Tue, 9 Mar 2021 21:13:27 +0100 Subject: [PATCH 1468/1930] Add workflows for rebase and project automation --- .github/dependabot.yml | 8 +++- .github/workflows/automation.yml | 66 +++++++++++++++++++++++++++ .github/workflows/merge-conflicts.yml | 17 +++++++ .github/workflows/rebase.yml | 27 +++++++++++ 4 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/automation.yml create mode 100644 .github/workflows/merge-conflicts.yml create mode 100644 .github/workflows/rebase.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0874cae2e3..70bcd49737 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -6,4 +6,10 @@ updates: interval: weekly time: '12:00' open-pull-requests-limit: 10 - + +- package-ecosystem: github-actions + directory: '/' + schedule: + interval: weekly + time: '12:00' + open-pull-requests-limit: 10 diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml new file mode 100644 index 0000000000..db34693cc7 --- /dev/null +++ b/.github/workflows/automation.yml @@ -0,0 +1,66 @@ +name: Automation + +on: + pull_request: + issues: + issue_comment: + +jobs: + main: + runs-on: ubuntu-latest + steps: + - name: Does PR has the stable backport label? + uses: Dreamcodeio/does-pr-has-label@v1.2 + id: checkLabel + with: + label: stable backport + + - name: Remove from 'Current Release' project + uses: alex-page/github-project-automation-plus@v0.5.1 + if: (github.event.pull_request || github.event.issue.pull_request) && !steps.checkLabel.outputs.hasLabel + continue-on-error: true + with: + project: Current Release + action: delete + repo-token: ${{ secrets.GH_TOKEN }} + + - name: Add to 'Release Next' project + uses: alex-page/github-project-automation-plus@v0.5.1 + if: (github.event.pull_request || github.event.issue.pull_request) && github.event.action == 'opened' + continue-on-error: true + with: + project: Release Next + column: In progress + repo-token: ${{ secrets.GH_TOKEN }} + + - name: Add to 'Current Release' project + uses: alex-page/github-project-automation-plus@v0.5.1 + if: (github.event.pull_request || github.event.issue.pull_request) && steps.checkLabel.outputs.hasLabel + continue-on-error: true + with: + project: Current Release + column: In progress + repo-token: ${{ secrets.GH_TOKEN }} + + - name: Check number of comments from the team member + if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' + id: member_comments + run: echo "::set-output name=number::$(curl -s ${{ github.event.issue.comments_url }} | jq '.[] | select(.author_association == "MEMBER") | .author_association' | wc -l)" + + - name: Move issue to needs triage + uses: alex-page/github-project-automation-plus@v0.5.1 + if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' && steps.member_comments.outputs.number <= 1 + continue-on-error: true + with: + project: Issue Triage for Main Repo + column: Needs triage + repo-token: ${{ secrets.GH_TOKEN }} + + - name: Add issue to triage project + uses: alex-page/github-project-automation-plus@v0.5.1 + if: github.event.issue.pull_request == '' && github.event.action == 'opened' + continue-on-error: true + with: + project: Issue Triage for Main Repo + column: Pending response + repo-token: ${{ secrets.GH_TOKEN }} diff --git a/.github/workflows/merge-conflicts.yml b/.github/workflows/merge-conflicts.yml new file mode 100644 index 0000000000..3740ce7a8a --- /dev/null +++ b/.github/workflows/merge-conflicts.yml @@ -0,0 +1,17 @@ +name: 'Merge Conflicts' + +on: + push: + branches: + - master + pull_request_target: + types: + - synchronize +jobs: + triage: + runs-on: ubuntu-latest + steps: + - uses: eps1lon/actions-label-merge-conflict@v2.0.0 + with: + dirtyLabel: 'merge conflict' + repoToken: ${{ secrets.GH_TOKEN }} diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml new file mode 100644 index 0000000000..3172ec0d9f --- /dev/null +++ b/.github/workflows/rebase.yml @@ -0,0 +1,27 @@ +name: Automatic Rebase +on: + issue_comment: + +jobs: + rebase: + name: Rebase + if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '@jellyfin-bot rebase') && github.event.comment.author_association == 'MEMBER' + runs-on: ubuntu-latest + steps: + - name: Notify as seen + uses: peter-evans/create-or-update-comment@v1.4.5 + with: + token: ${{ secrets.GH_TOKEN }} + comment-id: ${{ github.event.comment.id }} + reactions: '+1' + + - name: Checkout the latest code + uses: actions/checkout@v2 + with: + token: ${{ secrets.GH_TOKEN }} + fetch-depth: 0 + + - name: Automatic Rebase + uses: cirrus-actions/rebase@1.4 + env: + GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} From 78791a932f4a83834c1fb58e28a94cce6c8f349c Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 14 Apr 2021 06:44:11 -0600 Subject: [PATCH 1469/1930] Simplify baseUrl check --- Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs index 4dda900b05..3abf579e25 100644 --- a/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs +++ b/Jellyfin.Server/Middleware/BaseUrlRedirectionMiddleware.cs @@ -47,7 +47,9 @@ namespace Jellyfin.Server.Middleware if (!string.IsNullOrEmpty(baseUrlPrefix)) { - if (!localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase) + var startsWithBaseUrl = localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase); + + if (!startsWithBaseUrl && localPath.EndsWith("/health", StringComparison.OrdinalIgnoreCase)) { _logger.LogDebug("Redirecting /health check"); @@ -59,7 +61,7 @@ namespace Jellyfin.Server.Middleware || string.Equals(localPath, baseUrlPrefix, StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(localPath) - || !localPath.StartsWith(baseUrlPrefix, StringComparison.OrdinalIgnoreCase)) + || !startsWithBaseUrl) { // Always redirect back to the default path if the base prefix is invalid or missing _logger.LogDebug("Normalizing an URL at {LocalPath}", localPath); From 1d4c8dcde3669b21cec2324ed535cfdd8e5737a5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 14 Apr 2021 12:51:54 +0000 Subject: [PATCH 1470/1930] Bump eps1lon/actions-label-merge-conflict from v2.0.0 to v2.0.1 Bumps [eps1lon/actions-label-merge-conflict](https://github.com/eps1lon/actions-label-merge-conflict) from v2.0.0 to v2.0.1. - [Release notes](https://github.com/eps1lon/actions-label-merge-conflict/releases) - [Changelog](https://github.com/eps1lon/actions-label-merge-conflict/blob/main/CHANGELOG.md) - [Commits](https://github.com/eps1lon/actions-label-merge-conflict/compare/v2.0.0...b8bf8341285ec9a4567d4318ba474fee998a6919) Signed-off-by: dependabot[bot] --- .github/workflows/merge-conflicts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/merge-conflicts.yml b/.github/workflows/merge-conflicts.yml index 3740ce7a8a..ce808617a1 100644 --- a/.github/workflows/merge-conflicts.yml +++ b/.github/workflows/merge-conflicts.yml @@ -11,7 +11,7 @@ jobs: triage: runs-on: ubuntu-latest steps: - - uses: eps1lon/actions-label-merge-conflict@v2.0.0 + - uses: eps1lon/actions-label-merge-conflict@v2.0.1 with: dirtyLabel: 'merge conflict' repoToken: ${{ secrets.GH_TOKEN }} From b63f615fd4f92f40394d04c9ae764b35aadc000d Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Thu, 15 Apr 2021 07:39:59 -0600 Subject: [PATCH 1471/1930] Enable nullability for ServerDiscoveryInfo (#5804) --- Emby.Server.Implementations/Udp/UdpServer.cs | 7 +--- .../ApiClient/ServerDiscoveryInfo.cs | 41 ++++++++++++------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index d01184e0b6..db5265e79d 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -53,12 +53,7 @@ namespace Emby.Server.Implementations.Udp if (!string.IsNullOrEmpty(localUrl)) { - var response = new ServerDiscoveryInfo - { - Address = localUrl, - Id = _appHost.SystemId, - Name = _appHost.FriendlyName - }; + var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName); try { diff --git a/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs b/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs index fcc90a1f7a..f9f4745864 100644 --- a/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs +++ b/MediaBrowser.Model/ApiClient/ServerDiscoveryInfo.cs @@ -1,32 +1,43 @@ -#nullable disable -#pragma warning disable CS1591 - namespace MediaBrowser.Model.ApiClient { + /// + /// The server discovery info model. + /// public class ServerDiscoveryInfo { /// - /// Gets or sets the address. + /// Initializes a new instance of the class. /// - /// The address. - public string Address { get; set; } + /// The server address. + /// The server id. + /// The server name. + /// The endpoint address. + public ServerDiscoveryInfo(string address, string id, string name, string? endpointAddress = null) + { + Address = address; + Id = id; + Name = name; + EndpointAddress = endpointAddress; + } /// - /// Gets or sets the server identifier. + /// Gets the address. /// - /// The server identifier. - public string Id { get; set; } + public string Address { get; } /// - /// Gets or sets the name. + /// Gets the server identifier. /// - /// The name. - public string Name { get; set; } + public string Id { get; } /// - /// Gets or sets the endpoint address. + /// Gets the name. /// - /// The endpoint address. - public string EndpointAddress { get; set; } + public string Name { get; } + + /// + /// Gets the endpoint address. + /// + public string? EndpointAddress { get; } } } From 3199d1c902f62b1a2697a8361bf810c3766b7f0b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Thu, 15 Apr 2021 18:36:47 +0100 Subject: [PATCH 1472/1930] Fix: PlayTo using external ip not internal --- Emby.Dlna/PlayTo/PlayToManager.cs | 2 +- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 +- MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs | 2 ++ RSSDP/DeviceAvailableEventArgs.cs | 2 +- RSSDP/SsdpDeviceLocator.cs | 26 +++++++++++------------ 5 files changed, 18 insertions(+), 16 deletions(-) diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index a6793a7081..e9cab17f0d 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -183,7 +183,7 @@ namespace Emby.Dlna.PlayTo _sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName); - string serverAddress = _appHost.GetSmartApiUrl(info.LocalIpAddress); + string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress); controller = new PlayToController( sessionInfo, diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 8c7d961f3e..70223cbdbc 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -104,7 +104,7 @@ namespace Emby.Dlna.Ssdp { Location = e.DiscoveredDevice.DescriptionLocation, Headers = headers, - LocalIpAddress = e.LocalIpAddress + RemoteIpAddress = e.RemoteIpAddress }); DeviceDiscoveredInternal?.Invoke(this, args); diff --git a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs index d71013f019..987a3a908f 100644 --- a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs +++ b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs @@ -16,5 +16,7 @@ namespace MediaBrowser.Model.Dlna public IPAddress LocalIpAddress { get; set; } public int LocalPort { get; set; } + + public IPAddress RemoteIpAddress { get; set; } } } diff --git a/RSSDP/DeviceAvailableEventArgs.cs b/RSSDP/DeviceAvailableEventArgs.cs index b7d22a7df5..04b14c4dca 100644 --- a/RSSDP/DeviceAvailableEventArgs.cs +++ b/RSSDP/DeviceAvailableEventArgs.cs @@ -8,7 +8,7 @@ namespace Rssdp /// public sealed class DeviceAvailableEventArgs : EventArgs { - public IPAddress LocalIpAddress { get; set; } + public IPAddress RemoteIpAddress { get; set; } private readonly DiscoveredSsdpDevice _DiscoveredDevice; diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index bfad6de97a..eb99788f08 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -208,7 +208,7 @@ namespace Rssdp.Infrastructure /// Raises the event. /// /// - protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress) + protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) { if (this.IsDisposed) { @@ -220,7 +220,7 @@ namespace Rssdp.Infrastructure { handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) { - LocalIpAddress = localIpAddress + RemoteIpAddress = IpAddress }); } } @@ -286,7 +286,7 @@ namespace Rssdp.Infrastructure } } - private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress localIpAddress) + private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IpAddress) { bool isNewDevice = false; lock (_Devices) @@ -304,17 +304,17 @@ namespace Rssdp.Infrastructure } } - DeviceFound(device, isNewDevice, localIpAddress); + DeviceFound(device, isNewDevice, IpAddress); } - private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress) + private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) { if (!NotificationTypeMatchesFilter(device)) { return; } - OnDeviceAvailable(device, isNewDevice, localIpAddress); + OnDeviceAvailable(device, isNewDevice, IpAddress); } private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device) @@ -347,7 +347,7 @@ namespace Rssdp.Infrastructure return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); } - private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress localIpAddress) + private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress) { if (!message.IsSuccessStatusCode) { @@ -367,11 +367,11 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, localIpAddress); + AddOrUpdateDiscoveredDevice(device, IpAddress); } } - private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress localIpAddress) + private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IpAddress) { if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) { @@ -381,7 +381,7 @@ namespace Rssdp.Infrastructure var notificationType = GetFirstHeaderStringValue("NTS", message); if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0) { - ProcessAliveNotification(message, localIpAddress); + ProcessAliveNotification(message, IpAddress); } else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0) { @@ -389,7 +389,7 @@ namespace Rssdp.Infrastructure } } - private void ProcessAliveNotification(HttpRequestMessage message, IPAddress localIpAddress) + private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress) { var location = GetFirstHeaderUriValue("Location", message); if (location != null) @@ -404,7 +404,7 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, localIpAddress); + AddOrUpdateDiscoveredDevice(device, IpAddress); } } @@ -630,7 +630,7 @@ namespace Rssdp.Infrastructure private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e) { - ProcessNotificationMessage(e.Message, e.LocalIpAddress); + ProcessNotificationMessage(e.Message, e.ReceivedFrom.Address); } } } From d7855500c2c16a0b4b7fb7ed72e59ecd6ab0c514 Mon Sep 17 00:00:00 2001 From: Jack Date: Thu, 15 Apr 2021 14:44:21 -0400 Subject: [PATCH 1473/1930] Add NextUpCutoffDate to NextUpQuery --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 5 ++++- MediaBrowser.Model/Querying/NextUpQuery.cs | 6 ++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index d3f6fa34d8..b1b905fc7f 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations.TV return i.Item1 != DateTime.MinValue; } - if (alwaysEnableFirstEpisode || i.Item1 != DateTime.MinValue) + if (alwaysEnableFirstEpisode || (i.Item1 != DateTime.MinValue && i.Item1.Date > request.NextUpDateCutoff)) { anyFound = true; return true; diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index e1c67f8307..59802e2a51 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -65,6 +65,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The max number of images to return, per image type. /// Optional. The image types to include in the output. /// Optional. Include user data. + /// Starting date of shows to show in Next Up section. /// Whether to enable the total records count. Defaults to true. /// Whether to disable sending the first episode in a series as next up. /// A with the next up episodes. @@ -81,6 +82,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, + [FromQuery] DateTime nextUpDateCutoff, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool disableFirstEpisode = false) { @@ -97,7 +99,8 @@ namespace Jellyfin.Api.Controllers StartIndex = startIndex, UserId = userId ?? Guid.Empty, EnableTotalRecordCount = enableTotalRecordCount, - DisableFirstEpisode = disableFirstEpisode + DisableFirstEpisode = disableFirstEpisode, + NextUpDateCutoff = nextUpDateCutoff }, options); diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index 0555afc00d..8a3cb96e1b 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -13,6 +13,7 @@ namespace MediaBrowser.Model.Querying EnableImageTypes = Array.Empty(); EnableTotalRecordCount = true; DisableFirstEpisode = false; + NextUpDateCutoff = new DateTime(0001, 01, 01); } /// @@ -75,5 +76,10 @@ namespace MediaBrowser.Model.Querying /// Gets or sets a value indicating whether do disable sending first episode as next up. /// public bool DisableFirstEpisode { get; set; } + + /// + /// Gets or sets a value indicating the oldest date for a show to appear in Next Up. + /// + public DateTime NextUpDateCutoff { get; set; } } } From 198cc6e76af180d0ea3216a928096c4335099fd7 Mon Sep 17 00:00:00 2001 From: Jack Date: Fri, 16 Apr 2021 13:57:22 -0400 Subject: [PATCH 1474/1930] Some code cleanup. Allow NextUpDateCutoff to be null --- Emby.Server.Implementations/TV/TVSeriesManager.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 2 +- MediaBrowser.Model/Querying/NextUpQuery.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index b1b905fc7f..0ab9c15767 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -156,7 +156,7 @@ namespace Emby.Server.Implementations.TV return i.Item1 != DateTime.MinValue; } - if (alwaysEnableFirstEpisode || (i.Item1 != DateTime.MinValue && i.Item1.Date > request.NextUpDateCutoff)) + if (alwaysEnableFirstEpisode || (i.Item1 != DateTime.MinValue && (request.NextUpDateCutoff is null || i.Item1.Date > request.NextUpDateCutoff))) { anyFound = true; return true; diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 59802e2a51..5e90e37f39 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -82,7 +82,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] int? imageTypeLimit, [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes, [FromQuery] bool? enableUserData, - [FromQuery] DateTime nextUpDateCutoff, + [FromQuery] DateTime? nextUpDateCutoff, [FromQuery] bool enableTotalRecordCount = true, [FromQuery] bool disableFirstEpisode = false) { diff --git a/MediaBrowser.Model/Querying/NextUpQuery.cs b/MediaBrowser.Model/Querying/NextUpQuery.cs index 8a3cb96e1b..c5b39001a8 100644 --- a/MediaBrowser.Model/Querying/NextUpQuery.cs +++ b/MediaBrowser.Model/Querying/NextUpQuery.cs @@ -13,7 +13,7 @@ namespace MediaBrowser.Model.Querying EnableImageTypes = Array.Empty(); EnableTotalRecordCount = true; DisableFirstEpisode = false; - NextUpDateCutoff = new DateTime(0001, 01, 01); + NextUpDateCutoff = null; } /// @@ -80,6 +80,6 @@ namespace MediaBrowser.Model.Querying /// /// Gets or sets a value indicating the oldest date for a show to appear in Next Up. /// - public DateTime NextUpDateCutoff { get; set; } + public DateTime? NextUpDateCutoff { get; set; } } } From bb6fddde9ac48905b876717806754a052bf0ad24 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 17 Apr 2021 11:19:09 +0100 Subject: [PATCH 1475/1930] Group Methods --- Emby.Server.Implementations/Playlists/PlaylistManager.cs | 2 +- Jellyfin.Api/Helpers/StreamingHelpers.cs | 4 ++-- Jellyfin.Networking/Manager/NetworkManager.cs | 2 +- .../Migrations/Routines/CreateUserLoggingConfigFile.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs | 2 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index 932f721ab4..2d1a559f16 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -215,7 +215,7 @@ namespace Emby.Server.Implementations.Playlists // Create a list of the new linked children to add to the playlist var childrenToAdd = newItems - .Select(i => LinkedChild.Create(i)) + .Select(LinkedChild.Create) .ToList(); // Log duplicates that have been ignored, if any diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index e2306aa272..404cb3a460 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -121,14 +121,14 @@ namespace Jellyfin.Api.Helpers if (!string.IsNullOrWhiteSpace(streamingRequest.AudioCodec)) { state.SupportedAudioCodecs = streamingRequest.AudioCodec.Split(',', StringSplitOptions.RemoveEmptyEntries); - state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => mediaEncoder.CanEncodeToAudioCodec(i)) + state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(mediaEncoder.CanEncodeToAudioCodec) ?? state.SupportedAudioCodecs.FirstOrDefault(); } if (!string.IsNullOrWhiteSpace(streamingRequest.SubtitleCodec)) { state.SupportedSubtitleCodecs = streamingRequest.SubtitleCodec.Split(',', StringSplitOptions.RemoveEmptyEntries); - state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => mediaEncoder.CanEncodeToSubtitleCodec(i)) + state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(mediaEncoder.CanEncodeToSubtitleCodec) ?? state.SupportedSubtitleCodecs.FirstOrDefault(); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 73e8b2cd72..4078fd1269 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1067,7 +1067,7 @@ namespace Jellyfin.Networking.Manager } // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i))); + _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork)); } _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); diff --git a/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs index 6821630db7..ee4f8b0bab 100644 --- a/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs +++ b/Jellyfin.Server/Migrations/Routines/CreateUserLoggingConfigFile.cs @@ -75,7 +75,7 @@ namespace Jellyfin.Server.Migrations.Routines { var existingConfigJson = JToken.Parse(File.ReadAllText(oldConfigPath)); return _defaultConfigHistory - .Select(historicalConfigText => JToken.Parse(historicalConfigText)) + .Select(JToken.Parse) .Any(historicalConfigJson => JToken.DeepEquals(existingConfigJson, historicalConfigJson)); } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 53d45261e6..1b69c66469 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -2324,7 +2324,7 @@ namespace MediaBrowser.Controller.Entities .Where(i => i.IsLocalFile) .Select(i => System.IO.Path.GetDirectoryName(i.Path)) .Distinct(StringComparer.OrdinalIgnoreCase) - .SelectMany(i => directoryService.GetFilePaths(i)) + .SelectMany(directoryService.GetFilePaths) .ToList(); var deletedImages = ImageInfos diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index a87104cd67..ee2e5fcdee 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.MediaEncoding.Probing .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec)) .ToList(); - info.MediaAttachments = internalStreams.Select(s => GetMediaAttachment(s)) + info.MediaAttachments = internalStreams.Select(GetMediaAttachment) .Where(i => i != null) .ToList(); diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 398d47d5f5..f4c69fe8f5 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -297,7 +297,7 @@ namespace MediaBrowser.Model.Dlna int? inputAudioSampleRate = audioStream?.SampleRate; int? inputAudioBitDepth = audioStream?.BitDepth; - if (directPlayMethods.Count() > 0) + if (directPlayMethods.Any()) { string audioCodec = audioStream?.Codec; From bc1cc2d04ae0e823becf59964e5bdc5a74ae7741 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 17 Apr 2021 11:37:55 +0100 Subject: [PATCH 1476/1930] Remove unused using directives --- Emby.Dlna/ContentDirectory/ControlHandler.cs | 2 -- Emby.Dlna/Main/DlnaEntryPoint.cs | 1 - .../MediaReceiverRegistrarXmlBuilder.cs | 1 - Emby.Dlna/PlayTo/SsdpHttpClient.cs | 1 - .../AppBase/ConfigurationHelper.cs | 1 - Emby.Server.Implementations/Channels/ChannelManager.cs | 1 - .../Collections/CollectionManager.cs | 3 --- Emby.Server.Implementations/ConfigurationOptions.cs | 1 - .../HttpServer/Security/AuthService.cs | 1 - Emby.Server.Implementations/IStartupOptions.cs | 1 - Emby.Server.Implementations/Images/ArtistImageProvider.cs | 8 -------- .../Images/DynamicImageProvider.cs | 1 - Emby.Server.Implementations/Library/PathExtensions.cs | 2 -- Emby.Server.Implementations/Library/SearchEngine.cs | 1 - Emby.Server.Implementations/Library/UserDataManager.cs | 2 +- Emby.Server.Implementations/Library/UserViewManager.cs | 1 - Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 1 - .../LiveTv/EmbyTV/ItemDataProvider.cs | 2 -- .../LiveTv/EmbyTV/SeriesTimerManager.cs | 1 - .../LiveTv/Listings/XmlTvListingsProvider.cs | 1 - .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 3 --- .../LiveTv/TunerHosts/M3uParser.cs | 1 - .../Localization/LocalizationManager.cs | 1 - .../MediaEncoder/EncodingManager.cs | 1 - .../QuickConnect/QuickConnectManager.cs | 1 - .../ScheduledTasks/ScheduledTaskWorker.cs | 1 - .../ScheduledTasks/Tasks/ChapterImagesTask.cs | 2 +- .../ScheduledTasks/Tasks/PeopleValidationTask.cs | 2 +- .../ScheduledTasks/Tasks/PluginUpdateTask.cs | 1 - .../ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs | 2 +- Jellyfin.Api/Controllers/PluginsController.cs | 1 - Jellyfin.Api/Extensions/DtoExtensions.cs | 1 - Jellyfin.Api/Helpers/AudioHelper.cs | 3 +-- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 1 - Jellyfin.Data/Entities/HomeSection.cs | 3 +-- Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs | 1 - Jellyfin.Networking/Configuration/NetworkConfiguration.cs | 1 - .../Configuration/NetworkConfigurationExtensions.cs | 1 - Jellyfin.Server/Filters/ParameterObsoleteFilter.cs | 1 - Jellyfin.Server/Formatters/CssOutputFormatter.cs | 3 +-- .../Middleware/IpBasedAccessValidationMiddleware.cs | 2 -- Jellyfin.Server/Middleware/LanFilteringMiddleware.cs | 3 --- .../Migrations/Routines/DisableTranscodingThrottling.cs | 1 - Jellyfin.Server/Program.cs | 2 -- Jellyfin.Server/StartupOptions.cs | 3 --- MediaBrowser.Common/Cryptography/PasswordHash.cs | 1 - MediaBrowser.Common/Net/INetworkManager.cs | 1 - .../BaseItemManager/BaseItemManager.cs | 1 - .../BaseItemManager/IBaseItemManager.cs | 1 - MediaBrowser.Controller/Drawing/ImageHelper.cs | 3 --- MediaBrowser.Controller/Entities/Folder.cs | 1 - .../Events/Updates/PluginUninstalledEventArgs.cs | 1 - MediaBrowser.Controller/IServerApplicationHost.cs | 3 --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 2 -- MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs | 1 - MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs | 1 - MediaBrowser.Controller/MediaEncoding/JobLogger.cs | 1 - .../MediaEncoding/MediaEncoderHelpers.cs | 5 ----- MediaBrowser.Controller/Playlists/Playlist.cs | 1 - MediaBrowser.Controller/Providers/IRemoteImageProvider.cs | 1 - .../Providers/IRemoteSearchProvider.cs | 1 - MediaBrowser.Controller/Subtitles/ISubtitleManager.cs | 1 - MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 1 - MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs | 1 - MediaBrowser.Model/Dto/NameIdPair.cs | 2 -- MediaBrowser.Model/LiveTv/TunerHostInfo.cs | 3 --- MediaBrowser.Model/Notifications/NotificationOptions.cs | 2 -- MediaBrowser.Providers/Manager/ProviderManager.cs | 1 - .../Plugins/AudioDb/AlbumImageProvider.cs | 1 - MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs | 1 - .../Plugins/AudioDb/ArtistImageProvider.cs | 1 - MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs | 1 - MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs | 2 -- .../Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 4 ++-- .../Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs | 1 - .../Json/JsonNullableGuidConverterTests.cs | 1 - .../Jellyfin.Model.Tests/Extensions/StringHelperTests.cs | 1 - .../AudioBook/AudioBookListResolverTests.cs | 1 - .../AudioBook/AudioBookResolverTests.cs | 1 - .../Subtitles/SubtitleParserTests.cs | 1 - tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs | 1 - .../IO/ManagedFileSystemTests.cs | 1 - .../Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs | 2 -- tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs | 1 - tests/Jellyfin.Server.Tests/ParseNetworkTests.cs | 1 - .../Parsers/MusicArtistNfoParserTests.cs | 1 - 86 files changed, 9 insertions(+), 125 deletions(-) diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 713f950990..90ba601b4a 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -7,7 +6,6 @@ using System.Linq; using System.Text; using System.Threading; using System.Xml; -using Emby.Dlna.Configuration; using Emby.Dlna.Didl; using Emby.Dlna.Service; using Jellyfin.Data.Entities; diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index d3e9a41ec4..bdfe430cf3 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Sockets; -using System.Threading; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; diff --git a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs index 37840cd096..f3789a791c 100644 --- a/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs +++ b/Emby.Dlna/MediaReceiverRegistrar/MediaReceiverRegistrarXmlBuilder.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Emby.Dlna.Common; using Emby.Dlna.Service; -using MediaBrowser.Model.Dlna; namespace Emby.Dlna.MediaReceiverRegistrar { diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index e750f5bbc3..d9f1ce4907 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -2,7 +2,6 @@ using System; using System.Globalization; -using System.IO; using System.Net.Http; using System.Net.Mime; using System.Text; diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 3f70763830..29bac66340 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -3,7 +3,6 @@ using System; using System.IO; using System.Linq; -using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Serialization; namespace Emby.Server.Implementations.AppBase diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 87ebe960ab..7324b0ee9f 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index db532ce5b4..e984afdbab 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; using System.Threading; @@ -8,11 +7,9 @@ using System.Threading.Tasks; using Jellyfin.Data.Entities; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Collections; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; diff --git a/Emby.Server.Implementations/ConfigurationOptions.cs b/Emby.Server.Implementations/ConfigurationOptions.cs index cd9dbb1bda..01dc728c1c 100644 --- a/Emby.Server.Implementations/ConfigurationOptions.cs +++ b/Emby.Server.Implementations/ConfigurationOptions.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using Emby.Server.Implementations.HttpServer; using static MediaBrowser.Controller.Extensions.ConfigurationExtensions; namespace Emby.Server.Implementations diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs index 4a0fc8239e..9afabf5272 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthService.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthService.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 -using System; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.Net; diff --git a/Emby.Server.Implementations/IStartupOptions.cs b/Emby.Server.Implementations/IStartupOptions.cs index 0b823ff063..f719dc5f89 100644 --- a/Emby.Server.Implementations/IStartupOptions.cs +++ b/Emby.Server.Implementations/IStartupOptions.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 #nullable enable -using System; namespace Emby.Server.Implementations { diff --git a/Emby.Server.Implementations/Images/ArtistImageProvider.cs b/Emby.Server.Implementations/Images/ArtistImageProvider.cs index afa4ec7b1b..e96b64595c 100644 --- a/Emby.Server.Implementations/Images/ArtistImageProvider.cs +++ b/Emby.Server.Implementations/Images/ArtistImageProvider.cs @@ -2,20 +2,12 @@ using System; using System.Collections.Generic; -using System.Linq; -using Emby.Server.Implementations.Images; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; -using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Playlists; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Querying; namespace Emby.Server.Implementations.Images { diff --git a/Emby.Server.Implementations/Images/DynamicImageProvider.cs b/Emby.Server.Implementations/Images/DynamicImageProvider.cs index 462eb03a80..50c5314820 100644 --- a/Emby.Server.Implementations/Images/DynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/DynamicImageProvider.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using Emby.Server.Implementations.Images; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Dto; diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 6eaecff0f5..770cf6bb02 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -2,8 +2,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Text.RegularExpressions; using MediaBrowser.Common.Providers; namespace Emby.Server.Implementations.Library diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index 94602582b7..bcdf854ca3 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -12,7 +12,6 @@ using MediaBrowser.Controller.Extensions; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Querying; using MediaBrowser.Model.Search; -using Microsoft.Extensions.Logging; using Genre = MediaBrowser.Controller.Entities.Genre; using Person = MediaBrowser.Controller.Entities.Person; diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index d16275b192..e8caea1964 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -13,8 +13,8 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using Book = MediaBrowser.Controller.Entities.Book; using AudioBook = MediaBrowser.Controller.Entities.AudioBook; +using Book = MediaBrowser.Controller.Entities.Book; namespace Emby.Server.Implementations.Library { diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index b6b7ea9495..ac041bcf6c 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Threading; using Jellyfin.Data.Entities; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 91a21db60a..c9d9cc49af 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -17,7 +17,6 @@ using Jellyfin.Data.Enums; using Jellyfin.Data.Events; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.Net; using MediaBrowser.Common.Progress; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index c20b080883..1cac9cb963 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -4,9 +4,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Text.Json; -using System.Threading.Tasks; using MediaBrowser.Common.Json; using Microsoft.Extensions.Logging; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs index da707fec63..b1259de232 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/SeriesTimerManager.cs @@ -2,7 +2,6 @@ using System; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.LiveTv.EmbyTV diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 76c8757370..6824aa4423 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Threading; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 68173a0ef7..1dcc786874 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -8,10 +8,8 @@ using System.Linq; using System.Net; using System.Net.Http; using System.Text.Json; -using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; using MediaBrowser.Common.Net; @@ -19,7 +17,6 @@ using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 2af635492e..cc30a516d6 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 98de848bca..2fdc2b4d91 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -11,7 +11,6 @@ using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Serialization; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.Localization diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index a9dab91383..031b5d2e72 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -15,7 +15,6 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.MediaInfo; using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.MediaEncoder diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs index 7bed06de36..22739a0081 100644 --- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs +++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs @@ -3,7 +3,6 @@ using System.Collections.Concurrent; using System.Globalization; using System.Linq; using System.Security.Cryptography; -using MediaBrowser.Common; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; using MediaBrowser.Controller.Authentication; diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 3cc2cefb99..9c0e927058 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs index 649305fd56..2312c85d97 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs @@ -12,9 +12,9 @@ using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; using MediaBrowser.Model.IO; using MediaBrowser.Model.Tasks; -using MediaBrowser.Model.Globalization; namespace Emby.Server.Implementations.ScheduledTasks { diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs index c384cf4bbe..57d294a408 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PeopleValidationTask.cs @@ -5,8 +5,8 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks { diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs index a69380cbb7..11a5fb79f4 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/PluginUpdateTask.cs @@ -9,7 +9,6 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Updates; using MediaBrowser.Model.Globalization; -using MediaBrowser.Model.Net; using MediaBrowser.Model.Tasks; using Microsoft.Extensions.Logging; diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs index e470adcf48..51b620404b 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/RefreshMediaLibraryTask.cs @@ -6,8 +6,8 @@ using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.Library; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Tasks; namespace Emby.Server.Implementations.ScheduledTasks { diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index 24285bfb98..adec86a102 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -12,7 +12,6 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Json; using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Updates; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Net; using MediaBrowser.Model.Plugins; using Microsoft.AspNetCore.Authorization; diff --git a/Jellyfin.Api/Extensions/DtoExtensions.cs b/Jellyfin.Api/Extensions/DtoExtensions.cs index e0c744325f..06173315aa 100644 --- a/Jellyfin.Api/Extensions/DtoExtensions.cs +++ b/Jellyfin.Api/Extensions/DtoExtensions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using Jellyfin.Api.Helpers; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Dto; diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs index 21ec2d32f9..9c35d1ec10 100644 --- a/Jellyfin.Api/Helpers/AudioHelper.cs +++ b/Jellyfin.Api/Helpers/AudioHelper.cs @@ -1,5 +1,4 @@ -using System; -using System.Net.Http; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Jellyfin.Api.Models.StreamingDtos; diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 751b48682d..1bb504ad12 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; -using System.Net.Mime; using System.Security.Claims; using System.Text; using System.Threading; diff --git a/Jellyfin.Data/Entities/HomeSection.cs b/Jellyfin.Data/Entities/HomeSection.cs index 5adc52491c..d03d0f7a86 100644 --- a/Jellyfin.Data/Entities/HomeSection.cs +++ b/Jellyfin.Data/Entities/HomeSection.cs @@ -1,5 +1,4 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Enums; namespace Jellyfin.Data.Entities diff --git a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs index 730deccaed..cc04d033aa 100644 --- a/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs +++ b/Jellyfin.Data/Entities/Libraries/SeriesMetadata.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; using Jellyfin.Data.Interfaces; namespace Jellyfin.Data.Entities.Libraries diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 91bf0015fd..faf814c060 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -1,7 +1,6 @@ #pragma warning disable CA1819 // Properties should not return arrays using System; -using MediaBrowser.Model.Configuration; namespace Jellyfin.Networking.Configuration { diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs index e77b17ba92..8cbe398b07 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -1,4 +1,3 @@ -using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; namespace Jellyfin.Networking.Configuration diff --git a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs index e54044d0e9..b9ce221f5c 100644 --- a/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs +++ b/Jellyfin.Server/Filters/ParameterObsoleteFilter.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using Jellyfin.Api.Attributes; -using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; diff --git a/Jellyfin.Server/Formatters/CssOutputFormatter.cs b/Jellyfin.Server/Formatters/CssOutputFormatter.cs index e8dd48e4e6..cfc9d1ad3b 100644 --- a/Jellyfin.Server/Formatters/CssOutputFormatter.cs +++ b/Jellyfin.Server/Formatters/CssOutputFormatter.cs @@ -1,5 +1,4 @@ -using System; -using System.Text; +using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Formatters; diff --git a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs index 7d92bd7d31..0afcd61a05 100644 --- a/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Server/Middleware/IpBasedAccessValidationMiddleware.cs @@ -1,9 +1,7 @@ using System.Net; using System.Threading.Tasks; -using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; namespace Jellyfin.Server.Middleware diff --git a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs index 8065054a1e..67bf24d2a5 100644 --- a/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Server/Middleware/LanFilteringMiddleware.cs @@ -1,9 +1,6 @@ -using System; -using System.Linq; using System.Net; using System.Threading.Tasks; using Jellyfin.Networking.Configuration; -using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using Microsoft.AspNetCore.Http; diff --git a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs index bf0225e988..378e88e25b 100644 --- a/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs +++ b/Jellyfin.Server/Migrations/Routines/DisableTranscodingThrottling.cs @@ -1,6 +1,5 @@ using System; using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.Configuration; using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Migrations.Routines diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 464e024190..c10b2ddb3a 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -12,12 +12,10 @@ using System.Threading.Tasks; using CommandLine; using Emby.Server.Implementations; using Emby.Server.Implementations.IO; -using Jellyfin.Api.Controllers; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; diff --git a/Jellyfin.Server/StartupOptions.cs b/Jellyfin.Server/StartupOptions.cs index 6d8210527c..a1cecc8c63 100644 --- a/Jellyfin.Server/StartupOptions.cs +++ b/Jellyfin.Server/StartupOptions.cs @@ -1,10 +1,7 @@ -using System; using System.Collections.Generic; using CommandLine; using Emby.Server.Implementations; -using Emby.Server.Implementations.EntryPoints; using Emby.Server.Implementations.Udp; -using Emby.Server.Implementations.Updates; using MediaBrowser.Controller.Extensions; namespace Jellyfin.Server diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index f2ecc4741b..ec21d05803 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Text; namespace MediaBrowser.Common.Cryptography diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 012824f652..185df5b773 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net; using System.Net.NetworkInformation; -using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; namespace MediaBrowser.Common.Net diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 31dd954028..a233c358e4 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Threading; -using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs index e1f5d05a60..8a87364270 100644 --- a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Configuration; diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 181f8e905f..596fcbc8cf 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -1,10 +1,7 @@ #pragma warning disable CS1591 #nullable enable -using System; -using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Drawing; -using MediaBrowser.Model.Entities; namespace MediaBrowser.Controller.Drawing { diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index cac5026f70..bdca5c0ee7 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; using System.Text.Json.Serialization; diff --git a/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs index a111e6d829..0f27be9bb7 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginUninstalledEventArgs.cs @@ -1,5 +1,4 @@ using Jellyfin.Data.Events; -using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Plugins; namespace MediaBrowser.Controller.Events.Updates diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 20bfa697e5..6a65a8e47a 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -3,10 +3,7 @@ using System; using System.Collections.Generic; using System.Net; -using System.Threading; -using System.Threading.Tasks; using MediaBrowser.Common; -using MediaBrowser.Common.Plugins; using MediaBrowser.Model.System; using Microsoft.AspNetCore.Http; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 92b9a8c7eb..1379efacbd 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -10,8 +10,6 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading; using Jellyfin.Data.Enums; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Extensions; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index dacd6dea6c..d47a689f47 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -9,7 +9,6 @@ using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Net; using MediaBrowser.Model.Session; diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 5cbb579902..05dd1a69b1 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index cc8820f393..227c5f2587 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -3,7 +3,6 @@ using System; using System.Globalization; using System.IO; -using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs index 281d503721..89e01c08b6 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs @@ -1,10 +1,5 @@ #pragma warning disable CS1591 -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.MediaEncoding { diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index 977b14cb08..a5b7363fb6 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -14,7 +14,6 @@ using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; -using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; namespace MediaBrowser.Controller.Playlists diff --git a/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs b/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs index ee8f5b860a..de1631dcf4 100644 --- a/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs +++ b/MediaBrowser.Controller/Providers/IRemoteImageProvider.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; diff --git a/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs b/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs index 9592baa7c1..e401ed211c 100644 --- a/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs +++ b/MediaBrowser.Controller/Providers/IRemoteSearchProvider.cs @@ -3,7 +3,6 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Net; namespace MediaBrowser.Controller.Providers { diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs index feb26bc101..6d63286ef5 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 205933ae20..36bf77c841 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -16,7 +16,6 @@ using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.MediaEncoding.Probing; -using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; diff --git a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs index 8a7c032c54..7b7744163c 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Text.Json.Serialization; -using MediaBrowser.Common.Json.Converters; namespace MediaBrowser.MediaEncoding.Probing { diff --git a/MediaBrowser.Model/Dto/NameIdPair.cs b/MediaBrowser.Model/Dto/NameIdPair.cs index 7f18b45028..31516947f0 100644 --- a/MediaBrowser.Model/Dto/NameIdPair.cs +++ b/MediaBrowser.Model/Dto/NameIdPair.cs @@ -1,8 +1,6 @@ #nullable disable #pragma warning disable CS1591 -using System; - namespace MediaBrowser.Model.Dto { public class NameIdPair diff --git a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs index 7d4bbb2d07..05576a0f8d 100644 --- a/MediaBrowser.Model/LiveTv/TunerHostInfo.cs +++ b/MediaBrowser.Model/LiveTv/TunerHostInfo.cs @@ -1,9 +1,6 @@ #nullable disable #pragma warning disable CS1591 -using System; -using MediaBrowser.Model.Dto; - namespace MediaBrowser.Model.LiveTv { public class TunerHostInfo diff --git a/MediaBrowser.Model/Notifications/NotificationOptions.cs b/MediaBrowser.Model/Notifications/NotificationOptions.cs index 94bb5d6e35..12e093b219 100644 --- a/MediaBrowser.Model/Notifications/NotificationOptions.cs +++ b/MediaBrowser.Model/Notifications/NotificationOptions.cs @@ -5,8 +5,6 @@ using System; using System.Linq; using Jellyfin.Data.Entities; using Jellyfin.Data.Enums; -using MediaBrowser.Model.Extensions; -using MediaBrowser.Model.Users; namespace MediaBrowser.Model.Notifications { diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index b4b0b826f4..3bb2c6f0b0 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -25,7 +25,6 @@ using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; -using MediaBrowser.Model.Net; using MediaBrowser.Model.Providers; using Microsoft.Extensions.Logging; using Priority_Queue; diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs index 2adb119087..85a28747f5 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumImageProvider.cs @@ -14,7 +14,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.AudioDb { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs index 00feeec1f9..25bb3f9ce3 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/AlbumProvider.cs @@ -19,7 +19,6 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Music; namespace MediaBrowser.Providers.Plugins.AudioDb diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs index b8095ff04c..db8536cc92 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistImageProvider.cs @@ -14,7 +14,6 @@ using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; namespace MediaBrowser.Providers.Plugins.AudioDb { diff --git a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs index 59ecbc0171..cbb61fa353 100644 --- a/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs +++ b/MediaBrowser.Providers/Plugins/AudioDb/ArtistProvider.cs @@ -18,7 +18,6 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Model.Providers; -using MediaBrowser.Model.Serialization; using MediaBrowser.Providers.Music; namespace MediaBrowser.Providers.Plugins.AudioDb diff --git a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs index d35805a84b..46d3038905 100644 --- a/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs +++ b/MediaBrowser.Providers/Plugins/Omdb/OmdbProvider.cs @@ -6,9 +6,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; -using System.Text; using System.Text.Json; -using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common; diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index 833d1ae389..d22c1b50aa 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -7,8 +7,6 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using TMDbLib.Objects.Find; -using TMDbLib.Objects.Search; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -16,6 +14,8 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; +using TMDbLib.Objects.Find; +using TMDbLib.Objects.Search; namespace MediaBrowser.Providers.Plugins.Tmdb.Movies { diff --git a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs index 1e1cde9572..dbfad3c2ff 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonGuidConverterTests.cs @@ -1,5 +1,4 @@ using System; -using System.Globalization; using System.Text.Json; using MediaBrowser.Common.Json.Converters; using Xunit; diff --git a/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs index 22bc7afb96..cb3b66c4c5 100644 --- a/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs +++ b/tests/Jellyfin.Common.Tests/Json/JsonNullableGuidConverterTests.cs @@ -1,5 +1,4 @@ using System; -using System.Globalization; using System.Text.Json; using MediaBrowser.Common.Json.Converters; using Xunit; diff --git a/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs b/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs index 51633e157c..5864a05094 100644 --- a/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs +++ b/tests/Jellyfin.Model.Tests/Extensions/StringHelperTests.cs @@ -1,4 +1,3 @@ -using System; using MediaBrowser.Model.Extensions; using Xunit; diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs index e5768b6209..d9e77dd2e0 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookListResolverTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using Emby.Naming.AudioBook; using Emby.Naming.Common; diff --git a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs index ad63adadc3..53b35c2d6c 100644 --- a/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/AudioBook/AudioBookResolverTests.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using Emby.Naming.AudioBook; using Emby.Naming.Common; diff --git a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs index f3abacb4f9..2446660f32 100644 --- a/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/Subtitles/SubtitleParserTests.cs @@ -1,4 +1,3 @@ -using System; using Emby.Naming.Common; using Emby.Naming.Subtitles; using Xunit; diff --git a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs index d34f65409f..2f173b0ce0 100644 --- a/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/ExtraTests.cs @@ -1,4 +1,3 @@ -using System; using Emby.Naming.Common; using Emby.Naming.Video; using MediaBrowser.Model.Entities; diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 5a535ac51f..614a689759 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; diff --git a/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs index 3cbd638f90..0ade345a1a 100644 --- a/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs +++ b/tests/Jellyfin.Server.Integration.Tests/OpenApiSpecTests.cs @@ -1,8 +1,6 @@ using System.IO; using System.Reflection; -using System.Text.Json; using System.Threading.Tasks; -using MediaBrowser.Model.Branding; using Xunit; using Xunit.Abstractions; diff --git a/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs index 4e5d0fcb63..0a463cfa39 100644 --- a/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs +++ b/tests/Jellyfin.Server.Integration.Tests/TestAppHost.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Reflection; using Emby.Server.Implementations; -using Jellyfin.Server; using MediaBrowser.Controller; using MediaBrowser.Model.IO; using Microsoft.Extensions.Configuration; diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index 0b714e80a2..146b16cf94 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using System.Text; using Jellyfin.Networking.Configuration; diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs index 3d8e13e966..8ca3dd96e3 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MusicArtistNfoParserTests.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Threading; using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.Entities.Audio; From e841922ffd9211cfeee5cca1bda4c139cbda9379 Mon Sep 17 00:00:00 2001 From: Stephen Moore Date: Sat, 17 Apr 2021 17:21:40 +0100 Subject: [PATCH 1477/1930] Fix ArgumentOutOfRangeException scanning AudioBooks AudioResolver.ResolveMultipleAudio method can attempt to access the first item in a List without checking if the list is empty which throws an ArgumentOutOfRangeException and stops the 'Scan Library' process. --- .../Library/Resolvers/Audio/AudioResolver.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 90b6a8a7db..4ad84579d8 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -201,6 +201,11 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio continue; } + if (resolvedItem.Files.Count == 0) + { + continue; + } + var firstMedia = resolvedItem.Files[0]; var libraryItem = new T From 351b987982559b518de7654e85bb076b32ae0d10 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 18 Apr 2021 12:34:33 +0200 Subject: [PATCH 1478/1930] Add Person to TypedBaseItems if it's new --- .../Manager/MetadataService.cs | 63 ++++++++++--------- 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 437b43ecaf..f12586665f 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -223,13 +223,13 @@ namespace MediaBrowser.Providers.Manager var baseItem = result.Item; LibraryManager.UpdatePeople(baseItem, result.People); - await SavePeopleMetadataAsync(result.People, libraryOptions, cancellationToken).ConfigureAwait(false); + await SavePeopleMetadataAsync(result.People, cancellationToken).ConfigureAwait(false); } await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false); } - private async Task SavePeopleMetadataAsync(List people, LibraryOptions libraryOptions, CancellationToken cancellationToken) + private async Task SavePeopleMetadataAsync(IEnumerable people, CancellationToken cancellationToken) { var personsToSave = new List(); @@ -237,39 +237,44 @@ namespace MediaBrowser.Providers.Manager { cancellationToken.ThrowIfCancellationRequested(); - if (person.ProviderIds.Count > 0 || !string.IsNullOrWhiteSpace(person.ImageUrl)) + var itemUpdateType = ItemUpdateType.MetadataDownload; + var saveEntity = false; + var personEntity = LibraryManager.GetPerson(person.Name); + + // if PresentationUniqueKey is empty it's likely a new item. + if (string.IsNullOrEmpty(personEntity.PresentationUniqueKey)) { - var itemUpdateType = ItemUpdateType.MetadataDownload; - var saveEntity = false; - var personEntity = LibraryManager.GetPerson(person.Name); - foreach (var id in person.ProviderIds) - { - if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) - { - personEntity.SetProviderId(id.Key, id.Value); - saveEntity = true; - } - } + personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey(); + saveEntity = true; + } - if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) + foreach (var id in person.ProviderIds) + { + if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) { - personEntity.SetImage( - new ItemImageInfo - { - Path = person.ImageUrl, - Type = ImageType.Primary - }, - 0); - + personEntity.SetProviderId(id.Key, id.Value); saveEntity = true; - itemUpdateType = ItemUpdateType.ImageUpdate; } + } - if (saveEntity) - { - personsToSave.Add(personEntity); - await LibraryManager.RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); - } + if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) + { + personEntity.SetImage( + new ItemImageInfo + { + Path = person.ImageUrl, + Type = ImageType.Primary + }, + 0); + + saveEntity = true; + itemUpdateType = ItemUpdateType.ImageUpdate; + } + + if (saveEntity) + { + personsToSave.Add(personEntity); + await LibraryManager.RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); } } From 8933389753cc95413576b2fcfdf2ccb160464ad3 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 19 Apr 2021 10:49:52 +0200 Subject: [PATCH 1479/1930] Respect user settings for transcode and remux --- .../Library/MediaSourceManager.cs | 12 +++++++++--- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 2 +- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index b2943020c5..d0b85f07d4 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -199,10 +199,15 @@ namespace Emby.Server.Implementations.Library { source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding); } + else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase)) + { + source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding); + source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing); + } } } - return SortMediaSources(list).Where(i => i.Type != MediaSourceType.Placeholder).ToList(); + return SortMediaSources(list); } public MediaProtocol GetPathProtocol(string path) @@ -436,7 +441,7 @@ namespace Emby.Server.Implementations.Library } } - private static IEnumerable SortMediaSources(IEnumerable sources) + private static List SortMediaSources(IEnumerable sources) { return sources.OrderBy(i => { @@ -451,8 +456,9 @@ namespace Emby.Server.Implementations.Library { var stream = i.VideoStream; - return stream == null || stream.Width == null ? 0 : stream.Width.Value; + return stream?.Width ?? 0; }) + .Where(i => i.Type != MediaSourceType.Placeholder) .ToList(); } diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index f07271821d..295cfaf089 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -309,7 +309,7 @@ namespace Jellyfin.Api.Helpers { if (!user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding) && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding) - && !user.HasPermission(PermissionKind.EnablePlaybackRemuxing)) + && user.HasPermission(PermissionKind.EnablePlaybackRemuxing)) { options.ForceDirectStream = true; } From a9ca3c8b0165d949f63cf3a16a99b62b72a6606d Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 19 Apr 2021 11:38:27 +0200 Subject: [PATCH 1480/1930] Fix notification disabled users list --- MediaBrowser.Model/Notifications/NotificationOptions.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Model/Notifications/NotificationOptions.cs b/MediaBrowser.Model/Notifications/NotificationOptions.cs index 12e093b219..09beb2ef72 100644 --- a/MediaBrowser.Model/Notifications/NotificationOptions.cs +++ b/MediaBrowser.Model/Notifications/NotificationOptions.cs @@ -93,16 +93,17 @@ namespace MediaBrowser.Model.Notifications { NotificationOption opt = GetOptions(notificationType); - return opt == null || - !opt.DisabledServices.Contains(service, StringComparer.OrdinalIgnoreCase); + return opt == null + || !opt.DisabledServices.Contains(service, StringComparer.OrdinalIgnoreCase); } public bool IsEnabledToMonitorUser(string type, Guid userId) { NotificationOption opt = GetOptions(type); - return opt != null && opt.Enabled && - !opt.DisabledMonitorUsers.Contains(userId.ToString(string.Empty), StringComparer.OrdinalIgnoreCase); + return opt != null + && opt.Enabled + && !opt.DisabledMonitorUsers.Contains(userId.ToString("N"), StringComparer.OrdinalIgnoreCase); } public bool IsEnabledToSendToUser(string type, string userId, User user) From 90b941b3f6646d34f831a2921bc5919bfe9871c0 Mon Sep 17 00:00:00 2001 From: Mohamed Akram Date: Mon, 19 Apr 2021 14:59:24 +0400 Subject: [PATCH 1481/1930] Add review changes --- .../Plugins/Tmdb/TmdbClientManager.cs | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 3aa673274f..69f9649375 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -145,16 +145,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// A comma-separated list of image languages. /// The cancellation token. /// The TMDb tv show episode group information or null if not found. - public async Task GetSeriesGroupAsync(int tvShowId, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken) + private async Task GetSeriesGroupAsync(int tvShowId, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken) { - var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}"; - if (_memoryCache.TryGetValue(key, out TvGroupCollection group)) - { - return group; - } - - await EnsureClientConfigAsync().ConfigureAwait(false); - TvGroupType? groupType = displayOrder == "absolute" ? TvGroupType.Absolute : displayOrder == "dvd" ? TvGroupType.DVD : @@ -165,8 +157,16 @@ namespace MediaBrowser.Providers.Plugins.Tmdb return null; } - var series = await GetSeriesAsync(tvShowId, language, imageLanguages, cancellationToken); - var episodeGroupId = series.EpisodeGroups.Results.Find(g => g.Type == groupType)?.Id; + var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}"; + if (_memoryCache.TryGetValue(key, out TvGroupCollection group)) + { + return group; + } + + await EnsureClientConfigAsync().ConfigureAwait(false); + + var series = await GetSeriesAsync(tvShowId, language, imageLanguages, cancellationToken).ConfigureAwait(false); + var episodeGroupId = series?.EpisodeGroups.Results.Find(g => g.Type == groupType)?.Id; if (episodeGroupId == null) { @@ -246,6 +246,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb if (group != null) { var season = group.Groups.Find(s => s.Order == seasonNumber); + // Episode order starts at 0 var ep = season?.Episodes.Find(e => e.Order == episodeNumber - 1); if (ep != null) { From c68f6163774e4d6534a5a68d2c0f6b7435240ed3 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 19 Apr 2021 12:36:30 +0100 Subject: [PATCH 1482/1930] Flip fields --- Emby.Dlna/DlnaManager.cs | 2 +- tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 120 +++++++++++++++++++++ 2 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 tests/Jellyfin.Dlna.Tests/ProfileTester.cs diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 9ab3240388..88b0e11951 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -107,7 +107,7 @@ namespace Emby.Dlna } var profile = GetProfiles() - .FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification)); + .FirstOrDefault(i => i.Identification != null && IsMatch(i.Identification, deviceInfo)); if (profile != null) { diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs new file mode 100644 index 0000000000..83638c7c44 --- /dev/null +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Emby.Dlna.PlayTo; +using MediaBrowser.Model.Dlna; +using Xunit; + +namespace Jellyfin.Dlna.Tests +{ + public class ProfileTester + { + private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) + { + if (!string.IsNullOrEmpty(profileInfo.FriendlyName)) + { + if (deviceInfo.FriendlyName == null || !IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.Manufacturer)) + { + if (deviceInfo.Manufacturer == null || !IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl)) + { + if (deviceInfo.ManufacturerUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.ModelDescription)) + { + if (deviceInfo.ModelDescription == null || !IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.ModelName)) + { + if (deviceInfo.ModelName == null || !IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.ModelNumber)) + { + if (deviceInfo.ModelNumber == null || !IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.ModelUrl)) + { + if (deviceInfo.ModelUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) + { + return false; + } + } + + if (!string.IsNullOrEmpty(profileInfo.SerialNumber)) + { + if (deviceInfo.SerialNumber == null || !IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) + { + return false; + } + } + + return true; + } + + private bool IsRegexOrSubstringMatch(string input, string pattern) + { + return input.Contains(pattern, StringComparison.OrdinalIgnoreCase) || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + [Fact] + public void Test_Profile_Matches() + { + var source = new DeviceInfo() + { + Name = "HelloWorld" + }; + + var dest = new DeviceProfile() + { + Name = "Test Subject 1", + FriendlyName = "HelloWorld", + Manufacturer = "LG Electronics", + ManufacturerUrl = "http://www.lge.com", + ModelDescription = "LG WebOSTV DMRplus", + ModelName = "LG TV", + ModelNumber = "1.0", + Identification = new DeviceIdentification() + { + FriendlyName = "HelloWorld", + Manufacturer = "LG Electronics", + ManufacturerUrl = "http://www.lge.com", + ModelDescription = "LG WebOSTV DMRplus", + ModelName = "LG TV", + ModelNumber = "1.0", + } + }; + + Assert.True(IsMatch(dest.Identification, source.ToDeviceIdentification())); + } + } +} From 586e1fc58a52d343714958af713d102300ccfde0 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 19 Apr 2021 13:51:55 +0200 Subject: [PATCH 1483/1930] use IF NOT EXISTS in migration --- Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs index 2521d99527..6343c422d5 100644 --- a/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs +++ b/Jellyfin.Server/Migrations/Routines/AddPeopleQueryIndex.cs @@ -41,9 +41,9 @@ namespace Jellyfin.Server.Migrations.Routines var databasePath = Path.Join(_serverApplicationPaths.DataPath, DbFilename); using var connection = SQLite3.Open(databasePath, ConnectionFlags.ReadWrite, null); _logger.LogInformation("Creating index idx_TypedBaseItemsUserDataKeyType"); - connection.Execute("CREATE INDEX idx_TypedBaseItemsUserDataKeyType ON TypedBaseItems(UserDataKey, Type);"); + connection.Execute("CREATE INDEX IF NOT EXISTS idx_TypedBaseItemsUserDataKeyType ON TypedBaseItems(UserDataKey, Type);"); _logger.LogInformation("Creating index idx_PeopleNameListOrder"); - connection.Execute("CREATE INDEX idx_PeopleNameListOrder ON People(Name, ListOrder);"); + connection.Execute("CREATE INDEX IF NOT EXISTS idx_PeopleNameListOrder ON People(Name, ListOrder);"); } } -} \ No newline at end of file +} From 442bc8671bfd870641c67c54d1e365cc371bc3a1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 19 Apr 2021 12:08:51 +0000 Subject: [PATCH 1484/1930] Bump AutoFixture.AutoMoq from 4.15.0 to 4.16.0 Bumps [AutoFixture.AutoMoq](https://github.com/AutoFixture/AutoFixture) from 4.15.0 to 4.16.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.15.0...v4.16.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 1306783c94..00c40466ea 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 38de05ad07..486899f4f0 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -23,7 +23,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index d7e56ff135..437175f95d 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -10,7 +10,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 51d6333b73..e8fa55d9bc 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -11,7 +11,7 @@ - + From 64071873a0a68dd12a4a4995c7d9e4713763aab3 Mon Sep 17 00:00:00 2001 From: Mohamed Akram Date: Mon, 19 Apr 2021 16:51:44 +0400 Subject: [PATCH 1485/1930] Use StringComparison.Ordinal --- MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 69f9649375..05e5d3ced7 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -148,8 +148,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb private async Task GetSeriesGroupAsync(int tvShowId, string displayOrder, string language, string imageLanguages, CancellationToken cancellationToken) { TvGroupType? groupType = - displayOrder == "absolute" ? TvGroupType.Absolute : - displayOrder == "dvd" ? TvGroupType.DVD : + string.Equals(displayOrder, "absolute", StringComparison.Ordinal) ? TvGroupType.Absolute : + string.Equals(displayOrder, "dvd", StringComparison.Ordinal) ? TvGroupType.DVD : null; if (groupType == null) From 95b733ad4cbbe35b638de51e0b84d2794d28c34d Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 19 Apr 2021 14:07:14 +0100 Subject: [PATCH 1486/1930] reworked code --- Emby.Dlna/DlnaManager.cs | 112 +++++++++-------- tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 138 +++++++++------------ 2 files changed, 116 insertions(+), 134 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 88b0e11951..4a50136cf7 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -106,19 +106,28 @@ namespace Emby.Dlna throw new ArgumentNullException(nameof(deviceInfo)); } - var profile = GetProfiles() - .FirstOrDefault(i => i.Identification != null && IsMatch(i.Identification, deviceInfo)); + try + { + var profile = GetProfiles() + .FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification)); - if (profile != null) - { - _logger.LogDebug("Found matching device profile: {0}", profile.Name); + if (profile != null) + { + _logger.LogDebug("Found matching device profile: {0}", profile.Name); + } + else + { + LogUnmatchedProfile(deviceInfo); + } + + return profile; } - else + catch (ArgumentException ex) { - LogUnmatchedProfile(deviceInfo); + _logger.LogError(ex, "Error in profile comparison."); } - return profile; + return null; } private void LogUnmatchedProfile(DeviceIdentification profile) @@ -138,85 +147,82 @@ namespace Emby.Dlna _logger.LogInformation(builder.ToString()); } - private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) + /// + /// Attempts to match a device with a profile. + /// Rules: + /// - If the profile field has no value, the field matches irregardless of its contents. + /// - the profile field can be an exact match, or a reg exp. + /// + /// The of the device. + /// The of the profile. + /// True if they match. + public static bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) { - if (!string.IsNullOrEmpty(profileInfo.FriendlyName)) + if (!IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) { - if (deviceInfo.FriendlyName == null || !IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.Manufacturer)) + if (!IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) { - if (deviceInfo.Manufacturer == null || !IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl)) + if (!IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) { - if (deviceInfo.ManufacturerUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.ModelDescription)) + if (!IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) { - if (deviceInfo.ModelDescription == null || !IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.ModelName)) + if (!IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)) { - if (deviceInfo.ModelName == null || !IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.ModelNumber)) + if (!IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) { - if (deviceInfo.ModelNumber == null || !IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.ModelUrl)) + if (!IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) { - if (deviceInfo.ModelUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) - { - return false; - } + return false; } - if (!string.IsNullOrEmpty(profileInfo.SerialNumber)) + if (!IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) { - if (deviceInfo.SerialNumber == null || !IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) - { - return false; - } + return false; } return true; } - private bool IsRegexOrSubstringMatch(string input, string pattern) + public static bool IsRegexOrSubstringMatch(string input, string pattern) { + if (string.IsNullOrEmpty(pattern)) + { + // In profile identification: An empty pattern matches anything. + return true; + } + + if (string.IsNullOrEmpty(input)) + { + // The profile contains a value, and the device doesn't. + return false; + } + try { - return input.Contains(pattern, StringComparison.OrdinalIgnoreCase) || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) + || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } catch (ArgumentException ex) { - _logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern); - return false; + throw new ArgumentException("Error evaluating regex pattern " + pattern, ex); } } diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs index 83638c7c44..cc7cf92e70 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Emby.Dlna; using Emby.Dlna.PlayTo; using MediaBrowser.Model.Dlna; using Xunit; @@ -12,92 +13,23 @@ namespace Jellyfin.Dlna.Tests { public class ProfileTester { - private bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) - { - if (!string.IsNullOrEmpty(profileInfo.FriendlyName)) - { - if (deviceInfo.FriendlyName == null || !IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.Manufacturer)) - { - if (deviceInfo.Manufacturer == null || !IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl)) - { - if (deviceInfo.ManufacturerUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.ModelDescription)) - { - if (deviceInfo.ModelDescription == null || !IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.ModelName)) - { - if (deviceInfo.ModelName == null || !IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.ModelNumber)) - { - if (deviceInfo.ModelNumber == null || !IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.ModelUrl)) - { - if (deviceInfo.ModelUrl == null || !IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) - { - return false; - } - } - - if (!string.IsNullOrEmpty(profileInfo.SerialNumber)) - { - if (deviceInfo.SerialNumber == null || !IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) - { - return false; - } - } - - return true; - } - - private bool IsRegexOrSubstringMatch(string input, string pattern) - { - return input.Contains(pattern, StringComparison.OrdinalIgnoreCase) || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - [Fact] public void Test_Profile_Matches() { - var source = new DeviceInfo() + var device = new DeviceInfo() { - Name = "HelloWorld" + Name = "My Device", + Manufacturer = "LG Electronics", + ManufacturerUrl = "http://www.lge.com", + ModelDescription = "LG WebOSTV DMRplus", + ModelName = "LG TV", + ModelNumber = "1.0", }; - var dest = new DeviceProfile() + var profile = new DeviceProfile() { - Name = "Test Subject 1", - FriendlyName = "HelloWorld", + Name = "Test Profile", + FriendlyName = "My Device", Manufacturer = "LG Electronics", ManufacturerUrl = "http://www.lge.com", ModelDescription = "LG WebOSTV DMRplus", @@ -105,7 +37,7 @@ namespace Jellyfin.Dlna.Tests ModelNumber = "1.0", Identification = new DeviceIdentification() { - FriendlyName = "HelloWorld", + FriendlyName = "My Device", Manufacturer = "LG Electronics", ManufacturerUrl = "http://www.lge.com", ModelDescription = "LG WebOSTV DMRplus", @@ -114,7 +46,51 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.True(IsMatch(dest.Identification, source.ToDeviceIdentification())); + Assert.True(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile.Identification)); + + var profile2 = new DeviceProfile() + { + Name = "Test Profile", + FriendlyName = "My Device", + Identification = new DeviceIdentification() + { + FriendlyName = "My Device", + } + }; + + Assert.True(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile2.Identification)); + } + + [Fact] + public void Test_Profile_NoMatch() + { + var device = new DeviceInfo() + { + Name = "My Device", + Manufacturer = "JVC" + }; + + var profile = new DeviceProfile() + { + Name = "Test Profile", + FriendlyName = "My Device", + Manufacturer = "LG Electronics", + ManufacturerUrl = "http://www.lge.com", + ModelDescription = "LG WebOSTV DMRplus", + ModelName = "LG TV", + ModelNumber = "1.0", + Identification = new DeviceIdentification() + { + FriendlyName = "My Device", + Manufacturer = "LG Electronics", + ManufacturerUrl = "http://www.lge.com", + ModelDescription = "LG WebOSTV DMRplus", + ModelName = "LG TV", + ModelNumber = "1.0", + } + }; + + Assert.False(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile.Identification)); } } } From dc628d1e1c18f169e5c3fc9da3e257967149ca0d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 19 Apr 2021 13:07:31 +0000 Subject: [PATCH 1487/1930] Bump AutoFixture.Xunit2 from 4.15.0 to 4.16.0 Bumps [AutoFixture.Xunit2](https://github.com/AutoFixture/AutoFixture) from 4.15.0 to 4.16.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.15.0...v4.16.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 00c40466ea..050d4c040c 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 437175f95d..0de92249a9 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index e8fa55d9bc..9e60dbcd9f 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -12,7 +12,7 @@ - + From 4449217f8ff736e98a50fc686331c5240f6fe33c Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 19 Apr 2021 14:24:58 +0100 Subject: [PATCH 1488/1930] simplified isMatch --- Emby.Dlna/DlnaManager.cs | 49 +++++++--------------------------------- 1 file changed, 8 insertions(+), 41 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 4a50136cf7..374e04210d 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -158,47 +158,14 @@ namespace Emby.Dlna /// True if they match. public static bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) { - if (!IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) - { - return false; - } - - if (!IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) - { - return false; - } - - return true; + return IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName) + && IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer) + && IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl) + && IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription) + && IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName) + && IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber) + && IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl) + && IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber); } public static bool IsRegexOrSubstringMatch(string input, string pattern) From 500c2e5224f0b242cdcbeb0da9176f4e856185e6 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 19 Apr 2021 22:37:24 +0200 Subject: [PATCH 1489/1930] Switch from HttpClientHandler to SocketsHttpHandler SocketsHttpHandler is the default for .Net Core 2.1 and newer Set RequestHeaderEncoding to UTF-8 by default --- Jellyfin.Server/Startup.cs | 14 ++++++++++++-- .../Net/DefaultHttpClientHandler.cs | 19 ------------------- 2 files changed, 12 insertions(+), 21 deletions(-) delete mode 100644 MediaBrowser.Common/Net/DefaultHttpClientHandler.cs diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index e56e61092b..f751398843 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -1,5 +1,9 @@ +using System; +using System.Net; +using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; +using System.Text; using Jellyfin.Networking.Configuration; using Jellyfin.Server.Extensions; using Jellyfin.Server.Implementations; @@ -67,6 +71,12 @@ namespace Jellyfin.Server var acceptJsonHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json, 1.0); var acceptXmlHeader = new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Xml, 0.9); var acceptAnyHeader = new MediaTypeWithQualityHeaderValue("*/*", 0.8); + Func defaultHttpClientHandlerDelegate = (_) => new SocketsHttpHandler() + { + AutomaticDecompression = DecompressionMethods.All, + RequestHeaderEncodingSelector = (_, _) => Encoding.UTF8 + }; + services .AddHttpClient(NamedClient.Default, c => { @@ -75,7 +85,7 @@ namespace Jellyfin.Server c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader); c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) - .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); + .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate); services.AddHttpClient(NamedClient.MusicBrainz, c => { @@ -84,7 +94,7 @@ namespace Jellyfin.Server c.DefaultRequestHeaders.Accept.Add(acceptXmlHeader); c.DefaultRequestHeaders.Accept.Add(acceptAnyHeader); }) - .ConfigurePrimaryHttpMessageHandler(x => new DefaultHttpClientHandler()); + .ConfigurePrimaryHttpMessageHandler(defaultHttpClientHandlerDelegate); services.AddHealthChecks() .AddDbContextCheck(); diff --git a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs b/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs deleted file mode 100644 index f1c5f24772..0000000000 --- a/MediaBrowser.Common/Net/DefaultHttpClientHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Net; -using System.Net.Http; - -namespace MediaBrowser.Common.Net -{ - /// - /// Default http client handler. - /// - public class DefaultHttpClientHandler : HttpClientHandler - { - /// - /// Initializes a new instance of the class. - /// - public DefaultHttpClientHandler() - { - AutomaticDecompression = DecompressionMethods.All; - } - } -} From dcd6ab769bb2bb1d45d1dae993e53ff2b7c1177b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Mon, 19 Apr 2021 23:52:58 +0200 Subject: [PATCH 1490/1930] ProviderManager: fix discard and 2 warnings --- MediaBrowser.Providers/Manager/ProviderManager.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 3bb2c6f0b0..f078f9cefc 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -1021,26 +1021,26 @@ namespace MediaBrowser.Providers.Manager // TODO: Need to hunt down the conditions for this happening _activeRefreshes.AddOrUpdate( id, - (_) => throw new Exception( + (_) => throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Cannot update refresh progress of item '{0}' ({1}) because a refresh for this item is not running", item.GetType().Name, item.Id.ToString("N", CultureInfo.InvariantCulture))), - (_, __) => progress); + (_, _) => progress); RefreshProgress?.Invoke(this, new GenericEventArgs>(new Tuple(item, progress))); } /// - public void QueueRefresh(Guid id, MetadataRefreshOptions options, RefreshPriority priority) + public void QueueRefresh(Guid itemId, MetadataRefreshOptions options, RefreshPriority priority) { if (_disposed) { return; } - _refreshQueue.Enqueue(new Tuple(id, options), (int)priority); + _refreshQueue.Enqueue(new Tuple(itemId, options), (int)priority); lock (_refreshQueueLock) { From 06b8cf42d1d1edc424eaccb487590bc6a695ccba Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 20 Apr 2021 08:59:15 +0200 Subject: [PATCH 1491/1930] Fix TMDb Person Provider --- .../Tmdb/People/TmdbPersonImageProvider.cs | 53 +++++++++---------- .../Plugins/Tmdb/People/TmdbPersonProvider.cs | 18 +++---- 2 files changed, 32 insertions(+), 39 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index 3f57c4bc4c..0ea3f14a6f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -49,37 +49,36 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) { var person = (Person)item; - var personTmdbId = Convert.ToInt32(person.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture); - if (personTmdbId > 0) + if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { - var personResult = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false); - if (personResult?.Images?.Profiles == null) - { - return Enumerable.Empty(); - } - - var remoteImages = new List(); - var language = item.GetPreferredMetadataLanguage(); - - for (var i = 0; i < personResult.Images.Profiles.Count; i++) - { - var image = personResult.Images.Profiles[i]; - remoteImages.Add(new RemoteImageInfo - { - ProviderName = Name, - Type = ImageType.Primary, - Width = image.Width, - Height = image.Height, - Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language), - Url = _tmdbClientManager.GetProfileUrl(image.FilePath) - }); - } - - return remoteImages.OrderByLanguageDescending(language); + return Enumerable.Empty(); } - return Enumerable.Empty(); + var personResult = await _tmdbClientManager.GetPersonAsync(Convert.ToInt32(personTmdbId), cancellationToken).ConfigureAwait(false); + if (personResult?.Images?.Profiles == null) + { + return Enumerable.Empty(); + } + + var remoteImages = new RemoteImageInfo[personResult.Images.Profiles.Count]; + var language = item.GetPreferredMetadataLanguage(); + + for (var i = 0; i < personResult.Images.Profiles.Count; i++) + { + var image = personResult.Images.Profiles[i]; + remoteImages[i] = new RemoteImageInfo + { + ProviderName = Name, + Type = ImageType.Primary, + Width = image.Width, + Height = image.Height, + Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language), + Url = _tmdbClientManager.GetProfileUrl(image.FilePath) + }; + } + + return remoteImages.OrderByLanguageDescending(language); } public Task GetImageResponse(string url, CancellationToken cancellationToken) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs index 4384c203e5..cf6a362755 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs @@ -30,11 +30,9 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People public async Task> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken) { - var personTmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture); - - if (personTmdbId <= 0) + if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { - var personResult = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false); + var personResult = await _tmdbClientManager.GetPersonAsync(Convert.ToInt32(personTmdbId), cancellationToken).ConfigureAwait(false); if (personResult != null) { @@ -51,19 +49,15 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People } result.SetProviderId(MetadataProvider.Tmdb, personResult.Id.ToString(CultureInfo.InvariantCulture)); - result.SetProviderId(MetadataProvider.Imdb, personResult.ExternalIds.ImdbId); + if (!string.IsNullOrEmpty(personResult.ExternalIds.ImdbId)) + { + result.SetProviderId(MetadataProvider.Imdb, personResult.ExternalIds.ImdbId); + } return new[] { result }; } } - // TODO why? Because of the old rate limit? - if (searchInfo.IsAutomated) - { - // Don't hammer moviedb searching by name - return Enumerable.Empty(); - } - var personSearchResult = await _tmdbClientManager.SearchPersonAsync(searchInfo.Name, cancellationToken).ConfigureAwait(false); var remoteSearchResults = new List(); From 092c610fbf8268d5ff4518c2a6882764b89183d1 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 20 Apr 2021 08:26:41 +0100 Subject: [PATCH 1492/1930] Update Emby.Dlna/DlnaManager.cs Co-authored-by: Claus Vium --- Emby.Dlna/DlnaManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 374e04210d..82dc30fb51 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -113,7 +113,7 @@ namespace Emby.Dlna if (profile != null) { - _logger.LogDebug("Found matching device profile: {0}", profile.Name); + _logger.LogDebug("Found matching device profile: {ProfileName}", profile.Name); } else { From cbb855e65fd56d44b6e5714dd6843bb1d9dee1b8 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 20 Apr 2021 13:24:15 +0200 Subject: [PATCH 1493/1930] Check for empty string when migrating displaypreferences --- .../Migrations/Routines/MigrateDisplayPreferencesDb.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 07829c6969..5dc8c90d44 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -126,13 +126,13 @@ namespace Jellyfin.Server.Migrations.Routines ShowSidebar = dto.ShowSidebar, ScrollDirection = dto.ScrollDirection, ChromecastVersion = chromecastVersion, - SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) + SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && !string.IsNullOrEmpty(length) ? int.Parse(length, CultureInfo.InvariantCulture) : 30000, - SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) + SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && !string.IsNullOrEmpty(length) ? int.Parse(length, CultureInfo.InvariantCulture) : 10000, - EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled) + EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled) && !string.IsNullOrEmpty(enabled) ? bool.Parse(enabled) : true, DashboardTheme = dto.CustomPrefs.TryGetValue("dashboardtheme", out var theme) ? theme : string.Empty, From c0ea56a10dd085eaa363ec02122a119b07ecc0f8 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 20 Apr 2021 13:35:08 +0200 Subject: [PATCH 1494/1930] use int.Parse --- .../Plugins/Tmdb/People/TmdbPersonImageProvider.cs | 2 +- .../Plugins/Tmdb/People/TmdbPersonProvider.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index 0ea3f14a6f..bf42ceadef 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People return Enumerable.Empty(); } - var personResult = await _tmdbClientManager.GetPersonAsync(Convert.ToInt32(personTmdbId), cancellationToken).ConfigureAwait(false); + var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); if (personResult?.Images?.Profiles == null) { return Enumerable.Empty(); diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs index cf6a362755..1757c82678 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People { if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { - var personResult = await _tmdbClientManager.GetPersonAsync(Convert.ToInt32(personTmdbId), cancellationToken).ConfigureAwait(false); + var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); if (personResult != null) { From 4d7c1fbdca44eb6e892b104b765b86e146ac9765 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 20 Apr 2021 13:43:05 +0200 Subject: [PATCH 1495/1930] use int.Parse --- .../Migrations/Routines/MigrateDisplayPreferencesDb.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs index 5dc8c90d44..e25d291226 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateDisplayPreferencesDb.cs @@ -126,11 +126,11 @@ namespace Jellyfin.Server.Migrations.Routines ShowSidebar = dto.ShowSidebar, ScrollDirection = dto.ScrollDirection, ChromecastVersion = chromecastVersion, - SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && !string.IsNullOrEmpty(length) - ? int.Parse(length, CultureInfo.InvariantCulture) + SkipForwardLength = dto.CustomPrefs.TryGetValue("skipForwardLength", out var length) && int.TryParse(length, out var skipForwardLength) + ? skipForwardLength : 30000, - SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && !string.IsNullOrEmpty(length) - ? int.Parse(length, CultureInfo.InvariantCulture) + SkipBackwardLength = dto.CustomPrefs.TryGetValue("skipBackLength", out length) && !string.IsNullOrEmpty(length) && int.TryParse(length, out var skipBackwardLength) + ? skipBackwardLength : 10000, EnableNextVideoInfoOverlay = dto.CustomPrefs.TryGetValue("enableNextVideoInfoOverlay", out var enabled) && !string.IsNullOrEmpty(enabled) ? bool.Parse(enabled) From a99caa0daae7c47afdf7d0cf5cf182976211ffa2 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 20 Apr 2021 18:04:16 +0100 Subject: [PATCH 1496/1930] Changed testing --- Emby.Dlna/DlnaManager.cs | 15 +++------- .../Jellyfin.Dlna.Tests.csproj | 1 + tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 29 +++++++++++++------ 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 82dc30fb51..e80f1aaeed 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -156,7 +156,7 @@ namespace Emby.Dlna /// The of the device. /// The of the profile. /// True if they match. - public static bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) + public bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) { return IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName) && IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer) @@ -168,7 +168,7 @@ namespace Emby.Dlna && IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber); } - public static bool IsRegexOrSubstringMatch(string input, string pattern) + private bool IsRegexOrSubstringMatch(string input, string pattern) { if (string.IsNullOrEmpty(pattern)) { @@ -182,15 +182,8 @@ namespace Emby.Dlna return false; } - try - { - return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) - || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - } - catch (ArgumentException ex) - { - throw new ArgumentException("Error evaluating regex pattern " + pattern, ex); - } + return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) + || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } public DeviceProfile GetProfile(IHeaderDictionary headers) diff --git a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj index 850db1c75b..a1255a8586 100644 --- a/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj +++ b/tests/Jellyfin.Dlna.Tests/Jellyfin.Dlna.Tests.csproj @@ -9,6 +9,7 @@ + diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs index cc7cf92e70..3676cc9ef7 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -1,18 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using Emby.Dlna; using Emby.Dlna.PlayTo; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller; using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging; +using Moq; using Xunit; namespace Jellyfin.Dlna.Tests { public class ProfileTester { + private DlnaManager GetManager() + { + var xmlSerializer = new Mock(); + var fileSystem = new Mock(); + var appPaths = new Mock(); + var loggerFactory = new Mock(); + var appHost = new Mock(); + + return new DlnaManager(xmlSerializer.Object, fileSystem.Object, appPaths.Object, loggerFactory.Object, appHost.Object); + } + [Fact] public void Test_Profile_Matches() { @@ -46,7 +57,7 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.True(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile.Identification)); + Assert.True(GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification)); var profile2 = new DeviceProfile() { @@ -58,7 +69,7 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.True(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile2.Identification)); + Assert.True(GetManager().IsMatch(device.ToDeviceIdentification(), profile2.Identification)); } [Fact] @@ -90,7 +101,7 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.False(DlnaManager.IsMatch(device.ToDeviceIdentification(), profile.Identification)); + Assert.False(GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification)); } } } From 7848ea148438baf8929e1c2939e6979cb84aad1a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 20 Apr 2021 18:08:19 +0100 Subject: [PATCH 1497/1930] missed one. --- Emby.Dlna/DlnaManager.cs | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index e80f1aaeed..7f8dba35fb 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -106,28 +106,19 @@ namespace Emby.Dlna throw new ArgumentNullException(nameof(deviceInfo)); } - try + var profile = GetProfiles() + .FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification)); + + if (profile != null) { - var profile = GetProfiles() - .FirstOrDefault(i => i.Identification != null && IsMatch(deviceInfo, i.Identification)); - - if (profile != null) - { - _logger.LogDebug("Found matching device profile: {ProfileName}", profile.Name); - } - else - { - LogUnmatchedProfile(deviceInfo); - } - - return profile; + _logger.LogDebug("Found matching device profile: {ProfileName}", profile.Name); } - catch (ArgumentException ex) + else { - _logger.LogError(ex, "Error in profile comparison."); + LogUnmatchedProfile(deviceInfo); } - return null; + return profile; } private void LogUnmatchedProfile(DeviceIdentification profile) From 41246909dcbf71a85140b5354e5f76e33ea4801e Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 20 Apr 2021 18:14:23 +0100 Subject: [PATCH 1498/1930] fixed merge --- Emby.Dlna/DlnaManager.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 8aed4a50fa..a554a4d5b7 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -173,8 +173,16 @@ namespace Emby.Dlna return false; } - return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) + try + { + return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + catch (ArgumentException ex) + { + _logger.LogError(ex, "Error evaluating regex pattern {Pattern}", pattern); + return false; + } } public DeviceProfile GetProfile(IHeaderDictionary headers) From 522d5a71582fa4b610c75b0029812a9c10619002 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 20 Apr 2021 18:17:48 +0100 Subject: [PATCH 1499/1930] Fixed indent --- Emby.Dlna/DlnaManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index a554a4d5b7..57a6c20598 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -176,7 +176,7 @@ namespace Emby.Dlna try { return input.Equals(pattern, StringComparison.OrdinalIgnoreCase) - || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + || Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } catch (ArgumentException ex) { From 63e9b1ae2d8ea159427fb304d8d8503f7003e085 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 20 Apr 2021 22:59:51 +0200 Subject: [PATCH 1500/1930] DeepCopy: Throw ArgumentNullException if one of the args is null --- .../Entities/BaseItemExtensions.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs index c65477d39a..157ed83328 100644 --- a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs +++ b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs @@ -1,5 +1,7 @@ +#nullable enable #pragma warning disable CS1591 +using System; using System.Linq; using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; @@ -64,9 +66,19 @@ namespace MediaBrowser.Controller.Entities /// The source object. /// The destination object. public static void DeepCopy(this T source, TU dest) - where T : BaseItem - where TU : BaseItem + where T : BaseItem + where TU : BaseItem { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (dest == null) + { + throw new ArgumentNullException(nameof(dest)); + } + var destProps = typeof(TU).GetProperties().Where(x => x.CanWrite).ToList(); foreach (var sourceProp in typeof(T).GetProperties()) @@ -99,8 +111,8 @@ namespace MediaBrowser.Controller.Entities /// /// The source object. public static TU DeepCopy(this T source) - where T : BaseItem - where TU : BaseItem, new() + where T : BaseItem + where TU : BaseItem, new() { var dest = new TU(); source.DeepCopy(dest); From 499bac51854cf880beb4add835babf8abd8eb738 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 20 Apr 2021 23:03:36 +0200 Subject: [PATCH 1501/1930] EncodingHelper: Fix circular dependency --- .../ApplicationHost.cs | 3 +-- .../Controllers/DynamicHlsController.cs | 24 +++++------------ .../Controllers/VideoHlsController.cs | 24 +++++------------ Jellyfin.Api/Controllers/VideosController.cs | 25 +++++------------ Jellyfin.Api/Helpers/AudioHelper.cs | 25 +++++------------ Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 27 ++++++------------- Jellyfin.Api/Helpers/StreamingHelpers.cs | 9 ++----- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 8 +++--- .../MediaEncoding/EncodingHelper.cs | 8 +----- .../Encoder/MediaEncoder.cs | 3 --- 10 files changed, 42 insertions(+), 114 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 0512adf106..1ed74210dc 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -610,9 +610,8 @@ namespace Emby.Server.Implementations // TODO: Refactor to eliminate the circular dependency here so that Lazy isn't required ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService)); - // TODO: Refactor to eliminate the circular dependency here so that Lazy isn't required - ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService)); ServiceCollection.AddSingleton(); + ServiceCollection.AddSingleton(); // TODO: Refactor to eliminate the circular dependencies here so that Lazy isn't required ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService)); diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index c4e75fe859..b4154b361e 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -52,8 +52,6 @@ namespace Jellyfin.Api.Controllers private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; private readonly IFileSystem _fileSystem; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private readonly IDeviceManager _deviceManager; private readonly TranscodingJobHelper _transcodingJobHelper; private readonly ILogger _logger; @@ -72,12 +70,11 @@ namespace Jellyfin.Api.Controllers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. /// Instance of the class. /// Instance of the interface. /// Instance of . + /// Instance of . public DynamicHlsController( ILibraryManager libraryManager, IUserManager userManager, @@ -87,15 +84,12 @@ namespace Jellyfin.Api.Controllers IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, ILogger logger, - DynamicHlsHelper dynamicHlsHelper) + DynamicHlsHelper dynamicHlsHelper, + EncodingHelper encodingHelper) { - _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); - _libraryManager = libraryManager; _userManager = userManager; _dlnaManager = dlnaManager; @@ -104,12 +98,12 @@ namespace Jellyfin.Api.Controllers _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; _fileSystem = fileSystem; - _subtitleEncoder = subtitleEncoder; - _configuration = configuration; _deviceManager = deviceManager; _transcodingJobHelper = transcodingJobHelper; _logger = logger; _dynamicHlsHelper = dynamicHlsHelper; + _encodingHelper = encodingHelper; + _encodingOptions = serverConfigurationManager.GetEncodingOptions(); } @@ -1126,9 +1120,7 @@ namespace Jellyfin.Api.Controllers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, @@ -1211,9 +1203,7 @@ namespace Jellyfin.Api.Controllers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, diff --git a/Jellyfin.Api/Controllers/VideoHlsController.cs b/Jellyfin.Api/Controllers/VideoHlsController.cs index e95410d024..308334b237 100644 --- a/Jellyfin.Api/Controllers/VideoHlsController.cs +++ b/Jellyfin.Api/Controllers/VideoHlsController.cs @@ -48,9 +48,6 @@ namespace Jellyfin.Api.Controllers private readonly IMediaSourceManager _mediaSourceManager; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; - private readonly IFileSystem _fileSystem; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private readonly IDeviceManager _deviceManager; private readonly TranscodingJobHelper _transcodingJobHelper; private readonly ILogger _logger; @@ -60,9 +57,6 @@ namespace Jellyfin.Api.Controllers /// Initializes a new instance of the class. /// /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. @@ -72,11 +66,9 @@ namespace Jellyfin.Api.Controllers /// Instance of the interface. /// The singleton. /// Instance of the . + /// Instance of . public VideoHlsController( IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, IDlnaManager dlnaManager, IUserManager userManger, IAuthorizationContext authorizationContext, @@ -85,10 +77,9 @@ namespace Jellyfin.Api.Controllers IServerConfigurationManager serverConfigurationManager, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, - ILogger logger) + ILogger logger, + EncodingHelper encodingHelper) { - _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); - _dlnaManager = dlnaManager; _authContext = authorizationContext; _userManager = userManger; @@ -96,12 +87,11 @@ namespace Jellyfin.Api.Controllers _mediaSourceManager = mediaSourceManager; _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; - _fileSystem = fileSystem; - _subtitleEncoder = subtitleEncoder; - _configuration = configuration; _deviceManager = deviceManager; _transcodingJobHelper = transcodingJobHelper; _logger = logger; + _encodingHelper = encodingHelper; + _encodingOptions = serverConfigurationManager.GetEncodingOptions(); } @@ -285,9 +275,7 @@ namespace Jellyfin.Api.Controllers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 699ca53278..8dbb6aaa58 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -49,12 +49,10 @@ namespace Jellyfin.Api.Controllers private readonly IMediaSourceManager _mediaSourceManager; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; - private readonly IFileSystem _fileSystem; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private readonly IDeviceManager _deviceManager; private readonly TranscodingJobHelper _transcodingJobHelper; private readonly IHttpClientFactory _httpClientFactory; + private readonly EncodingHelper _encodingHelper; private readonly TranscodingJobType _transcodingJobType = TranscodingJobType.Progressive; @@ -69,12 +67,10 @@ namespace Jellyfin.Api.Controllers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. /// Instance of the class. /// Instance of the interface. + /// Instance of . public VideosController( ILibraryManager libraryManager, IUserManager userManager, @@ -84,12 +80,10 @@ namespace Jellyfin.Api.Controllers IMediaSourceManager mediaSourceManager, IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, - IHttpClientFactory httpClientFactory) + IHttpClientFactory httpClientFactory, + EncodingHelper encodingHelper) { _libraryManager = libraryManager; _userManager = userManager; @@ -99,12 +93,10 @@ namespace Jellyfin.Api.Controllers _mediaSourceManager = mediaSourceManager; _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; - _fileSystem = fileSystem; - _subtitleEncoder = subtitleEncoder; - _configuration = configuration; _deviceManager = deviceManager; _transcodingJobHelper = transcodingJobHelper; _httpClientFactory = httpClientFactory; + _encodingHelper = encodingHelper; } /// @@ -444,9 +436,7 @@ namespace Jellyfin.Api.Controllers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, @@ -515,8 +505,7 @@ namespace Jellyfin.Api.Controllers // Need to start ffmpeg (because media can't be returned directly) var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); - var encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); - var ffmpegCommandLineArguments = encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast"); + var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast"); return await FileStreamResponseHelpers.GetTranscodedFile( state, isHeadRequest, diff --git a/Jellyfin.Api/Helpers/AudioHelper.cs b/Jellyfin.Api/Helpers/AudioHelper.cs index 9c35d1ec10..cf35ee23aa 100644 --- a/Jellyfin.Api/Helpers/AudioHelper.cs +++ b/Jellyfin.Api/Helpers/AudioHelper.cs @@ -32,13 +32,11 @@ namespace Jellyfin.Api.Helpers private readonly IMediaSourceManager _mediaSourceManager; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; - private readonly IFileSystem _fileSystem; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private readonly IDeviceManager _deviceManager; private readonly TranscodingJobHelper _transcodingJobHelper; private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpContextAccessor _httpContextAccessor; + private readonly EncodingHelper _encodingHelper; /// /// Initializes a new instance of the class. @@ -50,13 +48,11 @@ namespace Jellyfin.Api.Helpers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. /// Instance of . /// Instance of the interface. /// Instance of the interface. + /// Instance of . public AudioHelper( IDlnaManager dlnaManager, IAuthorizationContext authContext, @@ -65,13 +61,11 @@ namespace Jellyfin.Api.Helpers IMediaSourceManager mediaSourceManager, IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, IHttpClientFactory httpClientFactory, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor, + EncodingHelper encodingHelper) { _dlnaManager = dlnaManager; _authContext = authContext; @@ -80,13 +74,11 @@ namespace Jellyfin.Api.Helpers _mediaSourceManager = mediaSourceManager; _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; - _fileSystem = fileSystem; - _subtitleEncoder = subtitleEncoder; - _configuration = configuration; _deviceManager = deviceManager; _transcodingJobHelper = transcodingJobHelper; _httpClientFactory = httpClientFactory; _httpContextAccessor = httpContextAccessor; + _encodingHelper = encodingHelper; } /// @@ -116,9 +108,7 @@ namespace Jellyfin.Api.Helpers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, @@ -187,8 +177,7 @@ namespace Jellyfin.Api.Helpers // Need to start ffmpeg (because media can't be returned directly) var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); - var encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); - var ffmpegCommandLineArguments = encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath); + var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath); return await FileStreamResponseHelpers.GetTranscodedFile( state, isHeadRequest, diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 1bb504ad12..fcada0e77c 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -40,14 +40,12 @@ namespace Jellyfin.Api.Helpers private readonly IMediaSourceManager _mediaSourceManager; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; - private readonly IFileSystem _fileSystem; - private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private readonly IDeviceManager _deviceManager; private readonly TranscodingJobHelper _transcodingJobHelper; private readonly INetworkManager _networkManager; private readonly ILogger _logger; private readonly IHttpContextAccessor _httpContextAccessor; + private readonly EncodingHelper _encodingHelper; /// /// Initializes a new instance of the class. @@ -59,14 +57,12 @@ namespace Jellyfin.Api.Helpers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. /// Instance of . /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. + /// Instance of . public DynamicHlsHelper( ILibraryManager libraryManager, IUserManager userManager, @@ -75,14 +71,12 @@ namespace Jellyfin.Api.Helpers IMediaSourceManager mediaSourceManager, IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, INetworkManager networkManager, ILogger logger, - IHttpContextAccessor httpContextAccessor) + IHttpContextAccessor httpContextAccessor, + EncodingHelper encodingHelper) { _libraryManager = libraryManager; _userManager = userManager; @@ -91,14 +85,12 @@ namespace Jellyfin.Api.Helpers _mediaSourceManager = mediaSourceManager; _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; - _fileSystem = fileSystem; - _subtitleEncoder = subtitleEncoder; - _configuration = configuration; _deviceManager = deviceManager; _transcodingJobHelper = transcodingJobHelper; _networkManager = networkManager; _logger = logger; _httpContextAccessor = httpContextAccessor; + _encodingHelper = encodingHelper; } /// @@ -144,9 +136,7 @@ namespace Jellyfin.Api.Helpers _libraryManager, _serverConfigurationManager, _mediaEncoder, - _fileSystem, - _subtitleEncoder, - _configuration, + _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, @@ -227,9 +217,8 @@ namespace Jellyfin.Api.Helpers var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(',', requestedVideoProfiles), "main"); sdrVideoUrl += "&AllowVideoStreamCopy=false"; - EncodingHelper encodingHelper = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration); - var sdrOutputVideoBitrate = encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec) ?? 0; - var sdrOutputAudioBitrate = encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream) ?? 0; + var sdrOutputVideoBitrate = _encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec) ?? 0; + var sdrOutputAudioBitrate = _encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream) ?? 0; var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate; AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup); diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index e2306aa272..bab901c15f 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -41,9 +41,7 @@ namespace Jellyfin.Api.Helpers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. + /// Instance of . /// Instance of the interface. /// Instance of the interface. /// Initialized . @@ -59,16 +57,13 @@ namespace Jellyfin.Api.Helpers ILibraryManager libraryManager, IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, + EncodingHelper encodingHelper, IDlnaManager dlnaManager, IDeviceManager deviceManager, TranscodingJobHelper transcodingJobHelper, TranscodingJobType transcodingJobType, CancellationToken cancellationToken) { - EncodingHelper encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); // Parse the DLNA time seek header if (!streamingRequest.StartTimeTicks.HasValue) { diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 240d132b15..0879cbd18f 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -62,8 +62,7 @@ namespace Jellyfin.Api.Helpers /// Instance of the interface. /// Instance of the interface. /// Instance of the interface. - /// Instance of the interface. - /// Instance of the interface. + /// Instance of . /// Instance of the interface. public TranscodingJobHelper( ILogger logger, @@ -73,8 +72,7 @@ namespace Jellyfin.Api.Helpers IServerConfigurationManager serverConfigurationManager, ISessionManager sessionManager, IAuthorizationContext authorizationContext, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration, + EncodingHelper encodingHelper, ILoggerFactory loggerFactory) { _logger = logger; @@ -84,8 +82,8 @@ namespace Jellyfin.Api.Helpers _serverConfigurationManager = serverConfigurationManager; _sessionManager = sessionManager; _authorizationContext = authorizationContext; + _encodingHelper = encodingHelper; _loggerFactory = loggerFactory; - _encodingHelper = new EncodingHelper(mediaEncoder, fileSystem, subtitleEncoder, configuration); DeleteEncodedMediaCache(); diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 1379efacbd..2b53647758 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -25,9 +25,7 @@ namespace MediaBrowser.Controller.MediaEncoding private static readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IMediaEncoder _mediaEncoder; - private readonly IFileSystem _fileSystem; private readonly ISubtitleEncoder _subtitleEncoder; - private readonly IConfiguration _configuration; private static readonly string[] _videoProfiles = new[] { @@ -42,14 +40,10 @@ namespace MediaBrowser.Controller.MediaEncoding public EncodingHelper( IMediaEncoder mediaEncoder, - IFileSystem fileSystem, - ISubtitleEncoder subtitleEncoder, - IConfiguration configuration) + ISubtitleEncoder subtitleEncoder) { _mediaEncoder = mediaEncoder; - _fileSystem = fileSystem; _subtitleEncoder = subtitleEncoder; - _configuration = configuration; } public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 36bf77c841..62c0c0bb1f 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -52,7 +52,6 @@ namespace MediaBrowser.MediaEncoding.Encoder private readonly IServerConfigurationManager _configurationManager; private readonly IFileSystem _fileSystem; private readonly ILocalizationManager _localization; - private readonly Lazy _encodingHelperFactory; private readonly string _startupOptionFFmpegPath; private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(2, 2); @@ -76,14 +75,12 @@ namespace MediaBrowser.MediaEncoding.Encoder IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILocalizationManager localization, - Lazy encodingHelperFactory, IConfiguration config) { _logger = logger; _configurationManager = configurationManager; _fileSystem = fileSystem; _localization = localization; - _encodingHelperFactory = encodingHelperFactory; _startupOptionFFmpegPath = config.GetValue(Controller.Extensions.ConfigurationExtensions.FfmpegPathKey) ?? string.Empty; _jsonSerializerOptions = JsonDefaults.Options; } From dcd96909cdade6b8889ae29054af2927a416c0fe Mon Sep 17 00:00:00 2001 From: artiume Date: Tue, 20 Apr 2021 19:28:18 -0400 Subject: [PATCH 1502/1930] Fix Audiobook Resume https://github.com/jellyfin/jellyfin/issues/5703 --- Emby.Server.Implementations/Library/UserDataManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index e8caea1964..78dc95b628 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -251,7 +251,7 @@ namespace Emby.Server.Implementations.Library var minIn = TimeSpan.FromTicks(positionTicks).TotalMinutes; var minOut = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; - if (minIn > _config.Configuration.MinAudiobookResume) + if (minIn < _config.Configuration.MinAudiobookResume) { // ignore progress during the beginning positionTicks = 0; From 96348ed744d95d0484c34a03b7a218d5153fae65 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 21 Apr 2021 08:33:29 +0200 Subject: [PATCH 1503/1930] Add tvrage and imdb ids for episodes --- .../Plugins/Tmdb/TV/TmdbEpisodeProvider.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs index b455e56349..1b6d558a0f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs @@ -121,9 +121,20 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV CommunityRating = Convert.ToSingle(episodeResult.VoteAverage) }; - if (!string.IsNullOrEmpty(episodeResult.ExternalIds?.TvdbId)) + var externalIds = episodeResult.ExternalIds; + if (!string.IsNullOrEmpty(externalIds?.TvdbId)) { - item.SetProviderId(MetadataProvider.Tvdb, episodeResult.ExternalIds.TvdbId); + item.SetProviderId(MetadataProvider.Tvdb, externalIds.TvdbId); + } + + if (!string.IsNullOrWhiteSpace(externalIds?.ImdbId)) + { + item.SetProviderId(MetadataProvider.Imdb, externalIds.ImdbId); + } + + if (!string.IsNullOrEmpty(externalIds?.TvrageId)) + { + item.SetProviderId(MetadataProvider.TvRage, externalIds.TvrageId); } if (episodeResult.Videos?.Results != null) From 2559ceffab778933a6122d2989cfa4d58f699839 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 21 Apr 2021 10:09:05 +0100 Subject: [PATCH 1504/1930] Update tests/Jellyfin.Dlna.Tests/ProfileTester.cs Co-authored-by: Claus Vium --- tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs index 3676cc9ef7..74868bc0e5 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -11,7 +11,7 @@ using Xunit; namespace Jellyfin.Dlna.Tests { - public class ProfileTester + public class DlnaManagerTests { private DlnaManager GetManager() { From 740e5ec167fc8a147cfaca2904220baee6ccc509 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 21 Apr 2021 10:09:14 +0100 Subject: [PATCH 1505/1930] Update tests/Jellyfin.Dlna.Tests/ProfileTester.cs Co-authored-by: Claus Vium --- tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs index 74868bc0e5..2f27a0534a 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -73,7 +73,7 @@ namespace Jellyfin.Dlna.Tests } [Fact] - public void Test_Profile_NoMatch() + public void IsMatch_GivenNamesAndManufacturersDoNotMatch_ReturnsFalse() { var device = new DeviceInfo() { From 39eb5da44f8e931aa6a89f9bb3d0785ca5e84465 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 21 Apr 2021 10:09:21 +0100 Subject: [PATCH 1506/1930] Update tests/Jellyfin.Dlna.Tests/ProfileTester.cs Co-authored-by: Claus Vium --- tests/Jellyfin.Dlna.Tests/ProfileTester.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs index 2f27a0534a..004933ca95 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/ProfileTester.cs @@ -25,7 +25,7 @@ namespace Jellyfin.Dlna.Tests } [Fact] - public void Test_Profile_Matches() + public void IsMatch_GivenMatchingName_ReturnsTrue() { var device = new DeviceInfo() { From 53e1b302cc08181c7909719df0cd837fd4b182f4 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 21 Apr 2021 10:18:29 +0100 Subject: [PATCH 1507/1930] Changes as requested --- Emby.Dlna/DlnaManager.cs | 14 ++++----- .../{ProfileTester.cs => DlnaManagerTests.cs} | 31 ++++++++++++++++--- 2 files changed, 34 insertions(+), 11 deletions(-) rename tests/Jellyfin.Dlna.Tests/{ProfileTester.cs => DlnaManagerTests.cs} (78%) diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 57a6c20598..5f2be07cf3 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -150,13 +150,13 @@ namespace Emby.Dlna public bool IsMatch(DeviceIdentification deviceInfo, DeviceIdentification profileInfo) { return IsRegexOrSubstringMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName) - && IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer) - && IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl) - && IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription) - && IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName) - && IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber) - && IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl) - && IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber); + && IsRegexOrSubstringMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer) + && IsRegexOrSubstringMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl) + && IsRegexOrSubstringMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription) + && IsRegexOrSubstringMatch(deviceInfo.ModelName, profileInfo.ModelName) + && IsRegexOrSubstringMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber) + && IsRegexOrSubstringMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl) + && IsRegexOrSubstringMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber); } private bool IsRegexOrSubstringMatch(string input, string pattern) diff --git a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs similarity index 78% rename from tests/Jellyfin.Dlna.Tests/ProfileTester.cs rename to tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs index 004933ca95..087d43a779 100644 --- a/tests/Jellyfin.Dlna.Tests/ProfileTester.cs +++ b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs @@ -46,7 +46,7 @@ namespace Jellyfin.Dlna.Tests ModelDescription = "LG WebOSTV DMRplus", ModelName = "LG TV", ModelNumber = "1.0", - Identification = new DeviceIdentification() + Identification = new () { FriendlyName = "My Device", Manufacturer = "LG Electronics", @@ -69,7 +69,8 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.True(GetManager().IsMatch(device.ToDeviceIdentification(), profile2.Identification)); + var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile2.Identification); + Assert.True(deviceMatch); } [Fact] @@ -90,7 +91,7 @@ namespace Jellyfin.Dlna.Tests ModelDescription = "LG WebOSTV DMRplus", ModelName = "LG TV", ModelNumber = "1.0", - Identification = new DeviceIdentification() + Identification = new () { FriendlyName = "My Device", Manufacturer = "LG Electronics", @@ -101,7 +102,29 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.False(GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification)); + var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification); + + Assert.False(deviceMatch); + } + + [Fact] + public void IsMatch_GivenNamesAndRegExMatch_ReturnsTrue() + { + var device = new DeviceInfo() + { + Name = "My Device" + }; + + var profile = new DeviceProfile() + { + Name = "Test Profile", + FriendlyName = "My .*", + Identification = new () + }; + + var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification); + + Assert.True(deviceMatch); } } } From 20e19ae9b3a89e4c9aac00f2352eb6e3ec52230a Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 21 Apr 2021 12:08:02 +0100 Subject: [PATCH 1508/1930] Moved Assert --- tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs index 087d43a779..668bd8f878 100644 --- a/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs +++ b/tests/Jellyfin.Dlna.Tests/DlnaManagerTests.cs @@ -57,8 +57,6 @@ namespace Jellyfin.Dlna.Tests } }; - Assert.True(GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification)); - var profile2 = new DeviceProfile() { Name = "Test Profile", @@ -70,7 +68,10 @@ namespace Jellyfin.Dlna.Tests }; var deviceMatch = GetManager().IsMatch(device.ToDeviceIdentification(), profile2.Identification); + var deviceMatch2 = GetManager().IsMatch(device.ToDeviceIdentification(), profile.Identification); + Assert.True(deviceMatch); + Assert.True(deviceMatch2); } [Fact] From 005ae80b31c8f354f83390a7b587f058e6792702 Mon Sep 17 00:00:00 2001 From: artiume Date: Wed, 21 Apr 2021 07:11:14 -0400 Subject: [PATCH 1509/1930] Update var names --- Emby.Server.Implementations/Library/UserDataManager.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 78dc95b628..827e3c64b3 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -248,15 +248,15 @@ namespace Emby.Server.Implementations.Library } else if (positionTicks > 0 && hasRuntime && item is AudioBook) { - var minIn = TimeSpan.FromTicks(positionTicks).TotalMinutes; - var minOut = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; + var playbackPositionInMinutes = TimeSpan.FromTicks(positionTicks).TotalMinutes; + var remainingTimeInMinutes = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; - if (minIn < _config.Configuration.MinAudiobookResume) + if (playbackPositionInMinutes < _config.Configuration.MinAudiobookResume) { // ignore progress during the beginning positionTicks = 0; } - else if (minOut < _config.Configuration.MaxAudiobookResume || positionTicks >= runtimeTicks) + else if (remainingTimeInMinutes < _config.Configuration.MaxAudiobookResume || positionTicks >= runtimeTicks) { // mark as completed close to the end positionTicks = 0; From aa992efd312dc4478202d484151fb3b4d46ecbc8 Mon Sep 17 00:00:00 2001 From: Bond-009 Date: Wed, 21 Apr 2021 16:15:31 +0200 Subject: [PATCH 1510/1930] Update MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs --- MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs index 1b6d558a0f..8ab2b19f91 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbEpisodeProvider.cs @@ -127,7 +127,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV item.SetProviderId(MetadataProvider.Tvdb, externalIds.TvdbId); } - if (!string.IsNullOrWhiteSpace(externalIds?.ImdbId)) + if (!string.IsNullOrEmpty(externalIds?.ImdbId)) { item.SetProviderId(MetadataProvider.Imdb, externalIds.ImdbId); } From 831e768ee7ae8e750202ff54395edade2761a90e Mon Sep 17 00:00:00 2001 From: artiume Date: Wed, 21 Apr 2021 13:15:03 -0400 Subject: [PATCH 1511/1930] Request more logs --- .github/ISSUE_TEMPLATE/bug_report.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index d67e1c98bf..12f1f5ed53 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -33,7 +33,13 @@ assignees: '' **Expected behavior** -**Logs** +**Server Logs** + + +**FFmpeg Logs** + + +**Browser Console Logs** **Screenshots** From f46195899e176912676511f277e31fea41d8ab27 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 21 Apr 2021 22:25:08 +0200 Subject: [PATCH 1512/1930] Improve perf of db save and query --- Jellyfin.Api/Controllers/MoviesController.cs | 9 +++++---- Jellyfin.Api/Controllers/SuggestionsController.cs | 2 +- Jellyfin.Api/Controllers/TvShowsController.cs | 2 +- MediaBrowser.Controller/Entities/TV/Episode.cs | 10 +++++++++- MediaBrowser.Controller/Entities/TV/Season.cs | 11 ++++++++++- MediaBrowser.Controller/Entities/TV/Series.cs | 14 ++++++-------- .../Entities/UserViewBuilder.cs | 10 ++++------ MediaBrowser.Controller/Playlists/Playlist.cs | 4 ++-- 8 files changed, 38 insertions(+), 24 deletions(-) diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index 4d788ad7d3..d0a2358ae2 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -89,7 +89,7 @@ namespace Jellyfin.Api.Controllers // nameof(LiveTvProgram) }, // IsMovie = true - OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.Random }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(), + OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.Random, SortOrder.Descending) }, Limit = 7, ParentId = parentIdGuid, Recursive = true, @@ -110,7 +110,7 @@ namespace Jellyfin.Api.Controllers { IncludeItemTypes = itemTypes.ToArray(), IsMovie = true, - OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(), + OrderBy = new[] { (ItemSortBy.Random, SortOrder.Descending) }, Limit = 10, IsFavoriteOrLiked = true, ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(), @@ -120,7 +120,7 @@ namespace Jellyfin.Api.Controllers DtoOptions = dtoOptions }); - var mostRecentMovies = recentlyPlayedMovies.Take(6).ToList(); + var mostRecentMovies = recentlyPlayedMovies.GetRange(0, Math.Min(recentlyPlayedMovies.Count, 6)); // Get recently played directors var recentDirectors = GetDirectors(mostRecentMovies) .ToList(); @@ -191,7 +191,8 @@ namespace Jellyfin.Api.Controllers foreach (var name in names) { - var items = _libraryManager.GetItemList(new InternalItemsQuery(user) + var items = _libraryManager.GetItemList( + new InternalItemsQuery(user) { Person = name, // Account for duplicates by imdb id, since the database doesn't support this yet diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index a55f13e66e..a811a29c31 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -69,7 +69,7 @@ namespace Jellyfin.Api.Controllers var dtoOptions = new DtoOptions().AddClientFields(Request); var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user) { - OrderBy = new[] { ItemSortBy.Random }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(), + OrderBy = new[] { (ItemSortBy.Random, SortOrder.Descending) }, MediaTypes = mediaType, IncludeItemTypes = type, IsVirtualItem = false, diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index e1c67f8307..59400db2a0 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -155,7 +155,7 @@ namespace Jellyfin.Api.Controllers var itemsResult = _libraryManager.GetItemList(new InternalItemsQuery(user) { IncludeItemTypes = new[] { nameof(Episode) }, - OrderBy = new[] { ItemSortBy.PremiereDate, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(), + OrderBy = new[] { (ItemSortBy.PremiereDate, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) }, MinPremiereDate = minPremiereDate, StartIndex = startIndex, Limit = limit, diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index dc12fbbead..70663ef478 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -99,7 +99,15 @@ namespace MediaBrowser.Controller.Entities.TV take--; } - list.InsertRange(0, seriesUserDataKeys.Take(take).Select(i => i + ParentIndexNumber.Value.ToString("000") + IndexNumber.Value.ToString("000"))); + var newList = seriesUserDataKeys.GetRange(0, take); + var suffix = ParentIndexNumber.Value.ToString("000", CultureInfo.InvariantCulture) + IndexNumber.Value.ToString("000", CultureInfo.InvariantCulture); + for (int i = 0; i < take; i++) + { + newList[i] = newList[i] + suffix; + } + + newList.AddRange(list); + list = newList; } return list; diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index 93bdd6e706..5b8168d3d6 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text.Json.Serialization; using Jellyfin.Data.Entities; @@ -56,7 +57,15 @@ namespace MediaBrowser.Controller.Entities.TV var series = Series; if (series != null) { - list.InsertRange(0, series.GetUserDataKeys().Select(i => i + (IndexNumber ?? 0).ToString("000"))); + var newList = series.GetUserDataKeys(); + var suffix = (IndexNumber ?? 0).ToString("000", CultureInfo.InvariantCulture); + for (int i = 0; i < newList.Count; i++) + { + newList[i] = newList[i] + suffix; + } + + newList.AddRange(list); + list = newList; } return list; diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index a410c1b66f..9f9a2ad50f 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -169,14 +169,12 @@ namespace MediaBrowser.Controller.Entities.TV { var list = base.GetUserDataKeys(); - var key = this.GetProviderId(MetadataProvider.Imdb); - if (!string.IsNullOrEmpty(key)) + if (this.TryGetProviderId(MetadataProvider.Imdb, out var key)) { list.Insert(0, key); } - key = this.GetProviderId(MetadataProvider.Tvdb); - if (!string.IsNullOrEmpty(key)) + if (this.TryGetProviderId(MetadataProvider.Tvdb, out key)) { list.Insert(0, key); } @@ -208,7 +206,7 @@ namespace MediaBrowser.Controller.Entities.TV query.AncestorWithPresentationUniqueKey = null; query.SeriesPresentationUniqueKey = seriesKey; query.IncludeItemTypes = new[] { nameof(Season) }; - query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(); + query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }; if (user != null && !user.DisplayMissingEpisodes) { @@ -228,7 +226,7 @@ namespace MediaBrowser.Controller.Entities.TV query.SeriesPresentationUniqueKey = seriesKey; if (query.OrderBy.Count == 0) { - query.OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(); + query.OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }; } if (query.IncludeItemTypes.Length == 0) @@ -254,7 +252,7 @@ namespace MediaBrowser.Controller.Entities.TV AncestorWithPresentationUniqueKey = null, SeriesPresentationUniqueKey = seriesKey, IncludeItemTypes = new[] { nameof(Episode), nameof(Season) }, - OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(), + OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }, DtoOptions = options }; @@ -365,7 +363,7 @@ namespace MediaBrowser.Controller.Entities.TV AncestorWithPresentationUniqueKey = queryFromSeries ? null : seriesKey, SeriesPresentationUniqueKey = queryFromSeries ? seriesKey : null, IncludeItemTypes = new[] { nameof(Episode) }, - OrderBy = new[] { ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(), + OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }, DtoOptions = options }; if (user != null) diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 4e33a6bbde..78a64d8c95 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -217,8 +217,7 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetMovieLatest(Folder parent, User user, InternalItemsQuery query) { - query.OrderBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(); - + query.OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) }; query.Recursive = true; query.Parent = parent; query.SetUser(user); @@ -230,7 +229,7 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetMovieResume(Folder parent, User user, InternalItemsQuery query) { - query.OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(); + query.OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) }; query.IsResumable = true; query.Recursive = true; query.Parent = parent; @@ -327,8 +326,7 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetTvLatest(Folder parent, User user, InternalItemsQuery query) { - query.OrderBy = new[] { ItemSortBy.DateCreated, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(); - + query.OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) }; query.Recursive = true; query.Parent = parent; query.SetUser(user); @@ -356,7 +354,7 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetTvResume(Folder parent, User user, InternalItemsQuery query) { - query.OrderBy = new[] { ItemSortBy.DatePlayed, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Descending)).ToArray(); + query.OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending) }; query.IsResumable = true; query.Recursive = true; query.Parent = parent; diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index a5b7363fb6..c9c168c4c6 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -163,7 +163,7 @@ namespace MediaBrowser.Controller.Playlists Recursive = true, IncludeItemTypes = new[] { nameof(Audio) }, GenreIds = new[] { musicGenre.Id }, - OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(), + OrderBy = new[] { (ItemSortBy.AlbumArtist, SortOrder.Ascending), (ItemSortBy.Album, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) }, DtoOptions = options }); } @@ -175,7 +175,7 @@ namespace MediaBrowser.Controller.Playlists Recursive = true, IncludeItemTypes = new[] { nameof(Audio) }, ArtistIds = new[] { musicArtist.Id }, - OrderBy = new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }.Select(i => new ValueTuple(i, SortOrder.Ascending)).ToArray(), + OrderBy = new[] { (ItemSortBy.AlbumArtist, SortOrder.Ascending), (ItemSortBy.Album, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) }, DtoOptions = options }); } From b0914f9f2c16b538241b74dd22a7bb896fd56b4b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 22 Apr 2021 01:20:55 +0200 Subject: [PATCH 1513/1930] Remove unused/duplicate services --- Emby.Server.Implementations/ApplicationHost.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1ed74210dc..703f8d20da 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -607,9 +607,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); - // TODO: Refactor to eliminate the circular dependency here so that Lazy isn't required - ServiceCollection.AddTransient(provider => new Lazy(provider.GetRequiredService)); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); @@ -676,8 +673,6 @@ namespace Emby.Server.Implementations ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); - ServiceCollection.AddSingleton(); ServiceCollection.AddSingleton(); From b323044139fd7a0b63a717101f7ccb7f03f3f125 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 22 Apr 2021 01:23:24 +0200 Subject: [PATCH 1514/1930] Reduce string allocations/fs lookups in resolve code --- .../Library/LibraryManager.cs | 1 - .../Library/ResolverHelper.cs | 58 +++++-------------- .../Entities/AggregateFolder.cs | 3 +- .../Entities/CollectionFolder.cs | 1 - .../Library/ItemResolveArgs.cs | 6 +- .../Library/EpisodeResolverTest.cs | 11 +++- 6 files changed, 29 insertions(+), 51 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 6a9f4174dc..d869c7e394 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -558,7 +558,6 @@ namespace Emby.Server.Implementations.Library var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, directoryService) { Parent = parent, - Path = fullPath, FileInfo = fileInfo, CollectionType = collectionType, LibraryOptions = libraryOptions diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs index 4e4cac75bf..8be80d726c 100644 --- a/Emby.Server.Implementations/Library/ResolverHelper.cs +++ b/Emby.Server.Implementations/Library/ResolverHelper.cs @@ -1,3 +1,5 @@ +#nullable enable + using System; using System.IO; using System.Linq; @@ -21,8 +23,8 @@ namespace Emby.Server.Implementations.Library /// The file system. /// The library manager. /// The directory service. - /// Item must have a path - public static void SetInitialItemValues(BaseItem item, Folder parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService) + /// Item must have a path. + public static void SetInitialItemValues(BaseItem item, Folder? parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService) { // This version of the below method has no ItemResolveArgs, so we have to require the path already being set if (string.IsNullOrEmpty(item.Path)) @@ -43,9 +45,9 @@ namespace Emby.Server.Implementations.Library // Make sure DateCreated and DateModified have values var fileInfo = directoryService.GetFile(item.Path); - SetDateCreated(item, fileSystem, fileInfo); + SetDateCreated(item, fileInfo); - EnsureName(item, item.Path, fileInfo); + EnsureName(item, fileInfo); } /// @@ -72,9 +74,9 @@ namespace Emby.Server.Implementations.Library item.Id = libraryManager.GetNewItemId(item.Path, item.GetType()); // Make sure the item has a name - EnsureName(item, item.Path, args.FileInfo); + EnsureName(item, args.FileInfo); - item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 || + item.IsLocked = item.Path.Contains("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) || item.GetParents().Any(i => i.IsLocked); // Make sure DateCreated and DateModified have values @@ -84,28 +86,15 @@ namespace Emby.Server.Implementations.Library /// /// Ensures the name. /// - private static void EnsureName(BaseItem item, string fullPath, FileSystemMetadata fileInfo) + private static void EnsureName(BaseItem item, FileSystemMetadata fileInfo) { // If the subclass didn't supply a name, add it here - if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(fullPath)) + if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(item.Path)) { - var fileName = fileInfo == null ? Path.GetFileName(fullPath) : fileInfo.Name; - - item.Name = GetDisplayName(fileName, fileInfo != null && fileInfo.IsDirectory); + item.Name = fileInfo.IsDirectory ? fileInfo.Name : Path.GetFileNameWithoutExtension(fileInfo.Name); } } - /// - /// Gets the display name. - /// - /// The path. - /// if set to true [is directory]. - /// System.String. - private static string GetDisplayName(string path, bool isDirectory) - { - return isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path); - } - /// /// Ensures DateCreated and DateModified have values. /// @@ -114,21 +103,6 @@ namespace Emby.Server.Implementations.Library /// The args. private static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args) { - if (fileSystem == null) - { - throw new ArgumentNullException(nameof(fileSystem)); - } - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } - // See if a different path came out of the resolver than what went in if (!fileSystem.AreEqual(args.Path, item.Path)) { @@ -136,7 +110,7 @@ namespace Emby.Server.Implementations.Library if (childData != null) { - SetDateCreated(item, fileSystem, childData); + SetDateCreated(item, childData); } else { @@ -144,17 +118,17 @@ namespace Emby.Server.Implementations.Library if (fileData.Exists) { - SetDateCreated(item, fileSystem, fileData); + SetDateCreated(item, fileData); } } } else { - SetDateCreated(item, fileSystem, args.FileInfo); + SetDateCreated(item, args.FileInfo); } } - private static void SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemMetadata info) + private static void SetDateCreated(BaseItem item, FileSystemMetadata? info) { var config = BaseItem.ConfigurationManager.GetMetadataConfiguration(); @@ -163,7 +137,7 @@ namespace Emby.Server.Implementations.Library // directoryService.getFile may return null if (info != null) { - var dateCreated = fileSystem.GetCreationTimeUtc(info); + var dateCreated = info.CreationTimeUtc; if (dateCreated.Equals(DateTime.MinValue)) { diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 6ebea5f449..6a92200dd1 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -120,8 +120,7 @@ namespace MediaBrowser.Controller.Entities var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService) { - FileInfo = FileSystem.GetDirectoryInfo(path), - Path = path + FileInfo = FileSystem.GetDirectoryInfo(path) }; // Gather child folder and files diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 76b6d39a93..16a2c77e92 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -271,7 +271,6 @@ namespace MediaBrowser.Controller.Entities var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService) { FileInfo = FileSystem.GetDirectoryInfo(path), - Path = path, Parent = GetParent() as Folder, CollectionType = CollectionType }; diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index 12a311dc33..df88422370 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -60,10 +60,10 @@ namespace MediaBrowser.Controller.Library public FileSystemMetadata FileInfo { get; set; } /// - /// Gets or sets the path. + /// Gets the path. /// /// The path. - public string Path { get; set; } + public string Path => FileInfo.FullName; /// /// Gets a value indicating whether this instance is directory. @@ -87,7 +87,7 @@ namespace MediaBrowser.Controller.Library return false; } - var parentDir = System.IO.Path.GetDirectoryName(Path) ?? string.Empty; + var parentDir = FileInfo.DirectoryName ?? string.Empty; return parentDir.Length > _appPaths.RootFolderPath.Length && parentDir.StartsWith(_appPaths.RootFolderPath, StringComparison.OrdinalIgnoreCase); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs index 8765192150..c393742eb3 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/EpisodeResolverTest.cs @@ -6,6 +6,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; using Moq; using Xunit; @@ -28,7 +29,10 @@ namespace Jellyfin.Server.Implementations.Tests.Library { Parent = parent, CollectionType = CollectionType.TvShows, - Path = "All My Children/Season 01/Extras/All My Children S01E01 - Behind The Scenes.mkv" + FileInfo = new FileSystemMetadata() + { + FullName = "All My Children/Season 01/Extras/All My Children S01E01 - Behind The Scenes.mkv" + } }; Assert.Null(episodeResolver.Resolve(itemResolveArgs)); @@ -48,7 +52,10 @@ namespace Jellyfin.Server.Implementations.Tests.Library { Parent = series, CollectionType = CollectionType.TvShows, - Path = "Extras/Extras S01E01.mkv" + FileInfo = new FileSystemMetadata() + { + FullName = "Extras/Extras S01E01.mkv" + } }; Assert.NotNull(episodeResolver.Resolve(itemResolveArgs)); } From 81209258abeade8614d848f7e7cceeb6bb37a7d7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 22 Apr 2021 03:11:21 +0200 Subject: [PATCH 1515/1930] ManagedFileSystem: Rewrite GetValidFilename and more improvements --- .../IO/ManagedFileSystem.cs | 62 ++++++++++--------- .../IO/ManagedFileSystemTests.cs | 10 +++ 2 files changed, 43 insertions(+), 29 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 3893a15771..0d72cb00f6 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -2,11 +2,10 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; -using System.Text; +using System.Runtime.InteropServices; using MediaBrowser.Common.Configuration; using MediaBrowser.Model.IO; using MediaBrowser.Model.System; @@ -24,7 +23,7 @@ namespace Emby.Server.Implementations.IO private readonly List _shortcutHandlers = new List(); private readonly string _tempPath; - private readonly bool _isEnvironmentCaseInsensitive; + private static readonly bool _isEnvironmentCaseInsensitive = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public ManagedFileSystem( ILogger logger, @@ -32,8 +31,6 @@ namespace Emby.Server.Implementations.IO { Logger = logger; _tempPath = applicationPaths.TempDirectory; - - _isEnvironmentCaseInsensitive = OperatingSystem.Id == OperatingSystemId.Windows; } public virtual void AddShortcutHandler(IShortcutHandler handler) @@ -55,7 +52,7 @@ namespace Emby.Server.Implementations.IO } var extension = Path.GetExtension(filename); - return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); + return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase)); } /// @@ -72,7 +69,7 @@ namespace Emby.Server.Implementations.IO } var extension = Path.GetExtension(filename); - var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase)); + var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase)); return handler?.Resolve(filename); } @@ -303,16 +300,38 @@ namespace Emby.Server.Implementations.IO /// The filename. /// System.String. /// The filename is null. - public virtual string GetValidFilename(string filename) + public string GetValidFilename(string filename) { - var builder = new StringBuilder(filename); + return string.Create( + filename.Length, + filename, + (chars, state) => + { + state.AsSpan().CopyTo(chars); - foreach (var c in Path.GetInvalidFileNameChars()) - { - builder = builder.Replace(c, ' '); - } + var invalid = Path.GetInvalidFileNameChars(); - return builder.ToString(); + var first = state.AsSpan().IndexOfAny(invalid); + if (first == -1) + { + // Fast path for clean strings + return; + } + + chars[first++] = ' '; + + var len = chars.Length; + foreach (var c in invalid) + { + for (int i = first; i < len; i++) + { + if (chars[i] == c) + { + chars[i] = ' '; + } + } + } + }); } /// @@ -684,20 +703,5 @@ namespace Emby.Server.Implementations.IO AttributesToSkip = 0 }; } - - private static void RunProcess(string path, string args, string workingDirectory) - { - using (var process = Process.Start(new ProcessStartInfo - { - Arguments = args, - FileName = path, - CreateNoWindow = true, - WorkingDirectory = workingDirectory, - WindowStyle = ProcessWindowStyle.Normal - })) - { - process.WaitForExit(); - } - } } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs index 614a689759..30e6542f94 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/IO/ManagedFileSystemTests.cs @@ -42,6 +42,16 @@ namespace Jellyfin.Server.Implementations.Tests.IO } } + [Theory] + [InlineData("ValidFileName", "ValidFileName")] + [InlineData("AC/DC", "AC DC")] + [InlineData("Invalid\0", "Invalid ")] + [InlineData("AC/DC\0KD/A", "AC DC KD A")] + public void GetValidFilename_ReturnsValidFilename(string filename, string expectedFileName) + { + Assert.Equal(expectedFileName, _sut.GetValidFilename(filename)); + } + [SkippableFact] public void GetFileInfo_DanglingSymlink_ExistsFalse() { From 5b0dc21c644af074095b760b2e42c516ce07c0d6 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 21 Apr 2021 20:46:15 -0600 Subject: [PATCH 1516/1930] Mark password property as obsolete --- Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs b/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs index 3936274356..41f7b169eb 100644 --- a/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs +++ b/Jellyfin.Api/Models/UserDtos/AuthenticateUserByName.cs @@ -1,4 +1,6 @@ -namespace Jellyfin.Api.Models.UserDtos +using System; + +namespace Jellyfin.Api.Models.UserDtos { /// /// The authenticate user by name request body. @@ -18,6 +20,7 @@ /// /// Gets or sets the sha1-hashed password. /// + [Obsolete("Send password using pw field")] public string? Password { get; set; } } } From 33327aa1a951a1d0717b39f8f71356f09eb7bd6e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 22 Apr 2021 12:31:47 +0200 Subject: [PATCH 1517/1930] Improve fast path of ManagedFileSystem.GetValidFilename | Method | Data | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated | |---------------------------- |-------------- |------------:|----------:|----------:|------------:|-------:|------:|------:|----------:| | GetValidFilenameBench | AC/DCKD/A | 52.29 ns | 0.537 ns | 0.448 ns | 52.35 ns | 0.0255 | - | - | 80 B | | GetValidFilenameOldBench | AC/DCKD/A | 86.68 ns | 1.205 ns | 1.127 ns | 86.33 ns | 0.0587 | - | - | 184 B | | GetValidFilenameWinBench | AC/DCKD/A | 448.55 ns | 1.228 ns | 1.088 ns | 448.33 ns | 0.0505 | - | - | 160 B | | GetValidFilenameOldWinBench | AC/DCKD/A | 865.21 ns | 5.734 ns | 5.083 ns | 866.60 ns | 0.0839 | - | - | 264 B | | GetValidFilenameBench | ValidFileName | 16.00 ns | 0.234 ns | 0.207 ns | 16.02 ns | 0.0102 | - | - | 32 B | | GetValidFilenameOldBench | ValidFileName | 100.66 ns | 1.255 ns | 1.174 ns | 101.21 ns | 0.0587 | - | - | 184 B | | GetValidFilenameWinBench | ValidFileName | 116.60 ns | 1.624 ns | 1.519 ns | 116.88 ns | 0.0356 | - | - | 112 B | | GetValidFilenameOldWinBench | ValidFileName | 1,052.66 ns | 18.077 ns | 33.056 ns | 1,037.25 ns | 0.0839 | - | - | 264 B | --- .../IO/ManagedFileSystem.cs | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 0d72cb00f6..df973f9715 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -302,28 +302,27 @@ namespace Emby.Server.Implementations.IO /// The filename is null. public string GetValidFilename(string filename) { + var invalid = Path.GetInvalidFileNameChars(); + var first = filename.IndexOfAny(invalid); + if (first == -1) + { + // Fast path for clean strings + return filename; + } + return string.Create( filename.Length, - filename, + (filename, invalid, first), (chars, state) => { - state.AsSpan().CopyTo(chars); + state.filename.AsSpan().CopyTo(chars); - var invalid = Path.GetInvalidFileNameChars(); - - var first = state.AsSpan().IndexOfAny(invalid); - if (first == -1) - { - // Fast path for clean strings - return; - } - - chars[first++] = ' '; + chars[state.first++] = ' '; var len = chars.Length; - foreach (var c in invalid) + foreach (var c in state.invalid) { - for (int i = first; i < len; i++) + for (int i = state.first; i < len; i++) { if (chars[i] == c) { From 856819e58f79bdfce3433a9080e673187a4a77c1 Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 22 Apr 2021 06:49:42 -0600 Subject: [PATCH 1518/1930] Don't use obsolete Password property --- Jellyfin.Api/Controllers/UserController.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index 3c0d2aca16..b13db4baa9 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -177,11 +177,9 @@ namespace Jellyfin.Api.Controllers return StatusCode(StatusCodes.Status403Forbidden, "Only sha1 password is not allowed."); } - // Password should always be null AuthenticateUserByName request = new AuthenticateUserByName { Username = user.Username, - Password = null, Pw = pw }; return await AuthenticateUserByName(request).ConfigureAwait(false); @@ -208,7 +206,6 @@ namespace Jellyfin.Api.Controllers DeviceId = auth.DeviceId, DeviceName = auth.Device, Password = request.Pw, - PasswordSha1 = request.Password, RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(), Username = request.Username }).ConfigureAwait(false); From 940c30081ef8b9290d9f3c24b5529b2e593f924c Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 22 Apr 2021 06:49:54 -0600 Subject: [PATCH 1519/1930] Mark PasswordSha1 as obsolete --- Emby.Server.Implementations/Session/SessionManager.cs | 2 +- MediaBrowser.Controller/Session/AuthenticationRequest.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 10e28c33a5..6f21ec31e5 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1485,7 +1485,7 @@ namespace Emby.Server.Implementations.Session user = await _userManager.AuthenticateUser( request.Username, request.Password, - request.PasswordSha1, + null, request.RemoteEndPoint, true).ConfigureAwait(false); } diff --git a/MediaBrowser.Controller/Session/AuthenticationRequest.cs b/MediaBrowser.Controller/Session/AuthenticationRequest.cs index cc321fd22e..8c3ac58f2b 100644 --- a/MediaBrowser.Controller/Session/AuthenticationRequest.cs +++ b/MediaBrowser.Controller/Session/AuthenticationRequest.cs @@ -12,6 +12,7 @@ namespace MediaBrowser.Controller.Session public string Password { get; set; } + [Obsolete("Send full password in Password field")] public string PasswordSha1 { get; set; } public string App { get; set; } From a02e37daa009bebc3c5076b0e407dffe41e84c55 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 22 Apr 2021 15:28:24 +0200 Subject: [PATCH 1520/1930] SqliteItemRepository: remove redundant operations removed: * nameof -> FullName lookup * IndexOf before Replace * Enum.GetNames -> Enum.Parse roundtrip --- .../Data/SqliteItemRepository.cs | 185 +++++++----------- .../Library/LibraryManager.cs | 2 +- .../Persistence/IItemRepository.cs | 3 +- 3 files changed, 68 insertions(+), 122 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 694805ebe9..28e59913c0 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -2116,9 +2116,7 @@ namespace Emby.Server.Implementations.Data || query.IsLiked.HasValue; } - private readonly ItemFields[] _allFields = Enum.GetNames(typeof(ItemFields)) - .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)) - .ToArray(); + private readonly ItemFields[] _allFields = Enum.GetValues(); private string[] GetColumnNamesFromField(ItemFields field) { @@ -2721,87 +2719,22 @@ namespace Emby.Server.Implementations.Data private string FixUnicodeChars(string buffer) { - if (buffer.IndexOf('\u2013', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2013', '-'); // en dash - } - - if (buffer.IndexOf('\u2014', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2014', '-'); // em dash - } - - if (buffer.IndexOf('\u2015', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2015', '-'); // horizontal bar - } - - if (buffer.IndexOf('\u2017', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2017', '_'); // double low line - } - - if (buffer.IndexOf('\u2018', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2018', '\''); // left single quotation mark - } - - if (buffer.IndexOf('\u2019', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2019', '\''); // right single quotation mark - } - - if (buffer.IndexOf('\u201a', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark - } - - if (buffer.IndexOf('\u201b', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark - } - - if (buffer.IndexOf('\u201c', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark - } - - if (buffer.IndexOf('\u201d', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark - } - - if (buffer.IndexOf('\u201e', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark - } - - if (buffer.IndexOf('\u2026', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace("\u2026", "...", StringComparison.Ordinal); // horizontal ellipsis - } - - if (buffer.IndexOf('\u2032', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2032', '\''); // prime - } - - if (buffer.IndexOf('\u2033', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u2033', '\"'); // double prime - } - - if (buffer.IndexOf('\u0060', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u0060', '\''); // grave accent - } - - if (buffer.IndexOf('\u00B4', StringComparison.Ordinal) > -1) - { - buffer = buffer.Replace('\u00B4', '\''); // acute accent - } - - return buffer; + buffer = buffer.Replace('\u2013', '-'); // en dash + buffer = buffer.Replace('\u2014', '-'); // em dash + buffer = buffer.Replace('\u2015', '-'); // horizontal bar + buffer = buffer.Replace('\u2017', '_'); // double low line + buffer = buffer.Replace('\u2018', '\''); // left single quotation mark + buffer = buffer.Replace('\u2019', '\''); // right single quotation mark + buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark + buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark + buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark + buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark + buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark + buffer = buffer.Replace("\u2026", "...", StringComparison.Ordinal); // horizontal ellipsis + buffer = buffer.Replace('\u2032', '\''); // prime + buffer = buffer.Replace('\u2033', '\"'); // double prime + buffer = buffer.Replace('\u0060', '\''); // grave accent + return buffer.Replace('\u00B4', '\''); // acute accent } private void AddItem(List items, BaseItem newItem) @@ -3584,11 +3517,11 @@ namespace Emby.Server.Implementations.Data statement?.TryBind("@IsFolder", query.IsFolder); } - var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray(); + var includeTypes = query.IncludeItemTypes.Select(MapIncludeItemTypes).Where(x => x != null).ToArray(); // Only specify excluded types if no included types are specified if (includeTypes.Length == 0) { - var excludeTypes = query.ExcludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray(); + var excludeTypes = query.ExcludeItemTypes.Select(MapIncludeItemTypes).Where(x => x != null).ToArray(); if (excludeTypes.Length == 1) { whereClauses.Add("type<>@type"); @@ -4532,7 +4465,7 @@ namespace Emby.Server.Implementations.Data whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb")); } - var includedItemByNameTypes = GetItemByNameTypesInQuery(query).SelectMany(MapIncludeItemTypes).ToList(); + var includedItemByNameTypes = GetItemByNameTypesInQuery(query); var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0; var queryTopParentIds = query.TopParentIds; @@ -4790,27 +4723,27 @@ namespace Emby.Server.Implementations.Data if (IsTypeInQuery(nameof(Person), query)) { - list.Add(nameof(Person)); + list.Add(typeof(Person).FullName); } if (IsTypeInQuery(nameof(Genre), query)) { - list.Add(nameof(Genre)); + list.Add(typeof(Genre).FullName); } if (IsTypeInQuery(nameof(MusicGenre), query)) { - list.Add(nameof(MusicGenre)); + list.Add(typeof(MusicGenre).FullName); } if (IsTypeInQuery(nameof(MusicArtist), query)) { - list.Add(nameof(MusicArtist)); + list.Add(typeof(MusicArtist).FullName); } if (IsTypeInQuery(nameof(Studio), query)) { - list.Add(nameof(Studio)); + list.Add(typeof(Studio).FullName); } return list; @@ -4915,15 +4848,10 @@ namespace Emby.Server.Implementations.Data typeof(AggregateFolder) }; - public void UpdateInheritedValues(CancellationToken cancellationToken) - { - UpdateInheritedTags(cancellationToken); - } - - private void UpdateInheritedTags(CancellationToken cancellationToken) + public void UpdateInheritedValues() { string sql = string.Join( - ";", + ';', new string[] { "delete from itemvalues where type = 6", @@ -4946,37 +4874,38 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type } } - private static Dictionary GetTypeMapDictionary() + private static Dictionary GetTypeMapDictionary() { - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var t in _knownTypes) { - dict[t.Name] = new[] { t.FullName }; + dict[t.Name] = t.FullName ; } - dict["Program"] = new[] { typeof(LiveTvProgram).FullName }; - dict["TvChannel"] = new[] { typeof(LiveTvChannel).FullName }; + dict["Program"] = typeof(LiveTvProgram).FullName; + dict["TvChannel"] = typeof(LiveTvChannel).FullName; return dict; } // Not crazy about having this all the way down here, but at least it's in one place - private readonly Dictionary _types = GetTypeMapDictionary(); + private readonly Dictionary _types = GetTypeMapDictionary(); - private string[] MapIncludeItemTypes(string value) + private string MapIncludeItemTypes(string value) { - if (_types.TryGetValue(value, out string[] result)) + if (_types.TryGetValue(value, out string result)) { return result; } if (IsValidType(value)) { - return new[] { value }; + return value; } - return Array.Empty(); + Logger.LogWarning("Unknown item type: {ItemType}", value); + return null; } public void DeleteItem(Guid id) @@ -5279,31 +5208,46 @@ AND Type = @InternalPersonType)"); public List GetStudioNames() { - return GetItemValueNames(new[] { 3 }, new List(), new List()); + return GetItemValueNames(new[] { 3 }, Array.Empty(), Array.Empty()); } public List GetAllArtistNames() { - return GetItemValueNames(new[] { 0, 1 }, new List(), new List()); + return GetItemValueNames(new[] { 0, 1 }, Array.Empty(), Array.Empty()); } public List GetMusicGenreNames() { - return GetItemValueNames(new[] { 2 }, new List { "Audio", "MusicVideo", "MusicAlbum", "MusicArtist" }, new List()); + return GetItemValueNames( + new[] { 2 }, + new string[] + { + typeof(Audio).FullName, + typeof(MusicVideo).FullName, + typeof(MusicAlbum).FullName, + typeof(MusicArtist).FullName + }, + Array.Empty()); } public List GetGenreNames() { - return GetItemValueNames(new[] { 2 }, new List(), new List { "Audio", "MusicVideo", "MusicAlbum", "MusicArtist" }); + return GetItemValueNames( + new[] { 2 }, + Array.Empty(), + new string[] + { + typeof(Audio).FullName, + typeof(MusicVideo).FullName, + typeof(MusicAlbum).FullName, + typeof(MusicArtist).FullName + }); } - private List GetItemValueNames(int[] itemValueTypes, List withItemTypes, List excludeItemTypes) + private List GetItemValueNames(int[] itemValueTypes, IReadOnlyList withItemTypes, IReadOnlyList excludeItemTypes) { CheckDisposed(); - withItemTypes = withItemTypes.SelectMany(MapIncludeItemTypes).ToList(); - excludeItemTypes = excludeItemTypes.SelectMany(MapIncludeItemTypes).ToList(); - var now = DateTime.UtcNow; var typeClause = itemValueTypes.Length == 1 ? @@ -5809,7 +5753,10 @@ AND Type = @InternalPersonType)"); var endIndex = Math.Min(people.Count, startIndex + Limit); for (var i = startIndex; i < endIndex; i++) { - insertText.AppendFormat("(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0}),", i.ToString(CultureInfo.InvariantCulture)); + insertText.AppendFormat( + CultureInfo.InvariantCulture, + "(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0}),", + i.ToString(CultureInfo.InvariantCulture)); } // Remove last comma @@ -6261,7 +6208,7 @@ AND Type = @InternalPersonType)"); CheckDisposed(); if (id == Guid.Empty) { - throw new ArgumentException(nameof(id)); + throw new ArgumentException("Guid can't be empty.", nameof(id)); } if (attachments == null) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 6a9f4174dc..9c5172fb48 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1163,7 +1163,7 @@ namespace Emby.Server.Implementations.Library progress.Report(percent * 100); } - _itemRepository.UpdateInheritedValues(cancellationToken); + _itemRepository.UpdateInheritedValues(); progress.Report(100); } diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs index 45c6805f0e..ed473c7492 100644 --- a/MediaBrowser.Controller/Persistence/IItemRepository.cs +++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs @@ -153,8 +153,7 @@ namespace MediaBrowser.Controller.Persistence /// /// Updates the inherited values. /// - /// The cancellation token. - void UpdateInheritedValues(CancellationToken cancellationToken); + void UpdateInheritedValues(); int GetCount(InternalItemsQuery query); From e4691d45f5ffccded535a683a6c2f76a2c8536cb Mon Sep 17 00:00:00 2001 From: Ian Walton Date: Sat, 24 Apr 2021 10:54:42 -0400 Subject: [PATCH 1521/1930] Leave SyncPlay group on session disconnect. --- .../SyncPlay/SyncPlayManager.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index aee959c53c..315277985c 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -87,7 +87,7 @@ namespace Emby.Server.Implementations.SyncPlay _sessionManager = sessionManager; _libraryManager = libraryManager; _logger = loggerFactory.CreateLogger(); - _sessionManager.SessionControllerConnected += OnSessionControllerConnected; + _sessionManager.SessionEnded += OnSessionEnded; } /// @@ -352,18 +352,18 @@ namespace Emby.Server.Implementations.SyncPlay return; } - _sessionManager.SessionControllerConnected -= OnSessionControllerConnected; + _sessionManager.SessionEnded -= OnSessionEnded; _disposed = true; } - private void OnSessionControllerConnected(object sender, SessionEventArgs e) + private void OnSessionEnded(object sender, SessionEventArgs e) { var session = e.SessionInfo; if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) { - var request = new JoinGroupRequest(group.GroupId); - JoinGroup(session, request, CancellationToken.None); + var leaveGroupRequest = new LeaveGroupRequest(); + LeaveGroup(session, leaveGroupRequest, CancellationToken.None); } } From 77261a844541efdff96088c047908109d6063133 Mon Sep 17 00:00:00 2001 From: cvium Date: Sat, 24 Apr 2021 20:22:23 +0200 Subject: [PATCH 1522/1930] add UpdatePeopleAsync and add people to both tables --- .../Library/LibraryManager.cs | 60 +++++++++++++++++++ .../Library/ILibraryManager.cs | 9 +++ .../Manager/MetadataService.cs | 59 +----------------- 3 files changed, 72 insertions(+), 56 deletions(-) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 6a9f4174dc..7d030418ad 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -2880,6 +2880,12 @@ namespace Emby.Server.Implementations.Library } public void UpdatePeople(BaseItem item, List people) + { + UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult(); + } + + /// + public async Task UpdatePeopleAsync(BaseItem item, List people, CancellationToken cancellationToken) { if (!item.SupportsPeople) { @@ -2887,6 +2893,8 @@ namespace Emby.Server.Implementations.Library } _itemRepository.UpdatePeople(item.Id, people); + + await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false); } public async Task ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex) @@ -2990,6 +2998,58 @@ namespace Emby.Server.Implementations.Library } } + private async Task SavePeopleMetadataAsync(IEnumerable people, CancellationToken cancellationToken) + { + var personsToSave = new List(); + + foreach (var person in people) + { + cancellationToken.ThrowIfCancellationRequested(); + + var itemUpdateType = ItemUpdateType.MetadataDownload; + var saveEntity = false; + var personEntity = GetPerson(person.Name); + + // if PresentationUniqueKey is empty it's likely a new item. + if (string.IsNullOrEmpty(personEntity.PresentationUniqueKey)) + { + personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey(); + saveEntity = true; + } + + foreach (var id in person.ProviderIds) + { + if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) + { + personEntity.SetProviderId(id.Key, id.Value); + saveEntity = true; + } + } + + if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) + { + personEntity.SetImage( + new ItemImageInfo + { + Path = person.ImageUrl, + Type = ImageType.Primary + }, + 0); + + saveEntity = true; + itemUpdateType = ItemUpdateType.ImageUpdate; + } + + if (saveEntity) + { + personsToSave.Add(personEntity); + await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); + } + } + + CreateItems(personsToSave, null, CancellationToken.None); + } + private void StartScanInBackground() { Task.Run(() => diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 80fcf71f3e..6d9b568da8 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -466,6 +466,15 @@ namespace MediaBrowser.Controller.Library /// The people. void UpdatePeople(BaseItem item, List people); + /// + /// Asynchronously updates the people. + /// + /// The item. + /// The people. + /// The cancellation token. + /// The async task. + Task UpdatePeopleAsync(BaseItem item, List people, CancellationToken cancellationToken); + /// /// Gets the item ids. /// diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index f12586665f..6b778a090b 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -201,7 +201,7 @@ namespace MediaBrowser.Providers.Manager } // Save to database - await SaveItemAsync(metadataResult, libraryOptions, updateType, cancellationToken).ConfigureAwait(false); + await SaveItemAsync(metadataResult, updateType, cancellationToken).ConfigureAwait(false); } await AfterMetadataRefresh(itemOfType, refreshOptions, cancellationToken).ConfigureAwait(false); @@ -216,71 +216,18 @@ namespace MediaBrowser.Providers.Manager lookupInfo.Year = result.ProductionYear; } - protected async Task SaveItemAsync(MetadataResult result, LibraryOptions libraryOptions, ItemUpdateType reason, CancellationToken cancellationToken) + protected async Task SaveItemAsync(MetadataResult result, ItemUpdateType reason, CancellationToken cancellationToken) { if (result.Item.SupportsPeople && result.People != null) { var baseItem = result.Item; - LibraryManager.UpdatePeople(baseItem, result.People); - await SavePeopleMetadataAsync(result.People, cancellationToken).ConfigureAwait(false); + await LibraryManager.UpdatePeopleAsync(baseItem, result.People, cancellationToken).ConfigureAwait(false); } await result.Item.UpdateToRepositoryAsync(reason, cancellationToken).ConfigureAwait(false); } - private async Task SavePeopleMetadataAsync(IEnumerable people, CancellationToken cancellationToken) - { - var personsToSave = new List(); - - foreach (var person in people) - { - cancellationToken.ThrowIfCancellationRequested(); - - var itemUpdateType = ItemUpdateType.MetadataDownload; - var saveEntity = false; - var personEntity = LibraryManager.GetPerson(person.Name); - - // if PresentationUniqueKey is empty it's likely a new item. - if (string.IsNullOrEmpty(personEntity.PresentationUniqueKey)) - { - personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey(); - saveEntity = true; - } - - foreach (var id in person.ProviderIds) - { - if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase)) - { - personEntity.SetProviderId(id.Key, id.Value); - saveEntity = true; - } - } - - if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary)) - { - personEntity.SetImage( - new ItemImageInfo - { - Path = person.ImageUrl, - Type = ImageType.Primary - }, - 0); - - saveEntity = true; - itemUpdateType = ItemUpdateType.ImageUpdate; - } - - if (saveEntity) - { - personsToSave.Add(personEntity); - await LibraryManager.RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false); - } - } - - LibraryManager.CreateItems(personsToSave, null, CancellationToken.None); - } - protected virtual Task AfterMetadataRefresh(TItemType item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) { item.AfterMetadataRefresh(); From eee3b385daae376efb6f05af19692bc8b64e9c96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 12:00:42 +0000 Subject: [PATCH 1523/1930] Bump AutoFixture from 4.16.0 to 4.17.0 Bumps [AutoFixture](https://github.com/AutoFixture/AutoFixture) from 4.16.0 to 4.17.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.16.0...v4.17.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 050d4c040c..0071cda6eb 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -15,7 +15,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 486899f4f0..7a4ab9b26e 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 0de92249a9..8646b60b1a 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 9e60dbcd9f..64383a2d90 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -10,7 +10,7 @@ - + From d5037a8988df1e4790b45ed55696f7afa7f43b5f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 12:00:48 +0000 Subject: [PATCH 1524/1930] Bump Swashbuckle.AspNetCore from 6.0.7 to 6.1.3 Bumps [Swashbuckle.AspNetCore](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.0.7 to 6.1.3. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.0.7...v6.1.3) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index d6dc5a2dc3..01341d8b16 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -17,7 +17,7 @@ - + From 24a05bc9f83236a2e52b5c754c2a775ac1e6c1c6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 12:00:57 +0000 Subject: [PATCH 1525/1930] Bump sharpcompress from 0.28.1 to 0.28.2 Bumps [sharpcompress](https://github.com/adamhathcock/sharpcompress) from 0.28.1 to 0.28.2. - [Release notes](https://github.com/adamhathcock/sharpcompress/releases) - [Commits](https://github.com/adamhathcock/sharpcompress/compare/0.28.1...0.28.2) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 9248053f54..4ee23127e7 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -30,7 +30,7 @@ - + From e409d89138b21daef34dd64afb4d6434956b56fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 12:03:24 +0000 Subject: [PATCH 1526/1930] Bump alex-page/github-project-automation-plus from v0.5.1 to v0.6.0 Bumps [alex-page/github-project-automation-plus](https://github.com/alex-page/github-project-automation-plus) from v0.5.1 to v0.6.0. - [Release notes](https://github.com/alex-page/github-project-automation-plus/releases) - [Commits](https://github.com/alex-page/github-project-automation-plus/compare/v0.5.1...4230e39aec629f1b622666350cdbdf29ff149aca) Signed-off-by: dependabot[bot] --- .github/workflows/automation.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index db34693cc7..d5d3081857 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -16,7 +16,7 @@ jobs: label: stable backport - name: Remove from 'Current Release' project - uses: alex-page/github-project-automation-plus@v0.5.1 + uses: alex-page/github-project-automation-plus@v0.6.0 if: (github.event.pull_request || github.event.issue.pull_request) && !steps.checkLabel.outputs.hasLabel continue-on-error: true with: @@ -25,7 +25,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add to 'Release Next' project - uses: alex-page/github-project-automation-plus@v0.5.1 + uses: alex-page/github-project-automation-plus@v0.6.0 if: (github.event.pull_request || github.event.issue.pull_request) && github.event.action == 'opened' continue-on-error: true with: @@ -34,7 +34,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add to 'Current Release' project - uses: alex-page/github-project-automation-plus@v0.5.1 + uses: alex-page/github-project-automation-plus@v0.6.0 if: (github.event.pull_request || github.event.issue.pull_request) && steps.checkLabel.outputs.hasLabel continue-on-error: true with: @@ -48,7 +48,7 @@ jobs: run: echo "::set-output name=number::$(curl -s ${{ github.event.issue.comments_url }} | jq '.[] | select(.author_association == "MEMBER") | .author_association' | wc -l)" - name: Move issue to needs triage - uses: alex-page/github-project-automation-plus@v0.5.1 + uses: alex-page/github-project-automation-plus@v0.6.0 if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' && steps.member_comments.outputs.number <= 1 continue-on-error: true with: @@ -57,7 +57,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add issue to triage project - uses: alex-page/github-project-automation-plus@v0.5.1 + uses: alex-page/github-project-automation-plus@v0.6.0 if: github.event.issue.pull_request == '' && github.event.action == 'opened' continue-on-error: true with: From 47c54166e14a89a6895f6ceda3ab48591c097fad Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 14:43:14 +0000 Subject: [PATCH 1527/1930] Bump prometheus-net.DotNetRuntime from 3.4.1 to 4.0.0 Bumps [prometheus-net.DotNetRuntime](https://github.com/djluck/prometheus-net.DotNetRuntime) from 3.4.1 to 4.0.0. - [Release notes](https://github.com/djluck/prometheus-net.DotNetRuntime/releases) - [Commits](https://github.com/djluck/prometheus-net.DotNetRuntime/compare/3.4.1...4.0.0) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 4ee23127e7..adbfe52c4e 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -29,7 +29,7 @@ - + From a3cb8dbc9de4b8aa9c5bb4f6c5e0bd1ee53f60a7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Apr 2021 21:47:14 +0000 Subject: [PATCH 1528/1930] Bump Swashbuckle.AspNetCore.ReDoc from 6.0.7 to 6.1.3 Bumps [Swashbuckle.AspNetCore.ReDoc](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.0.7 to 6.1.3. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.0.7...v6.1.3) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 01341d8b16..3868882e5e 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -18,7 +18,7 @@ - + From c1563d9303da386fb37c78cfa4976917fb649b5a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 27 Apr 2021 13:35:13 +0000 Subject: [PATCH 1529/1930] Bump AutoFixture.Xunit2 from 4.16.0 to 4.17.0 Bumps [AutoFixture.Xunit2](https://github.com/AutoFixture/AutoFixture) from 4.16.0 to 4.17.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.16.0...v4.17.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 0071cda6eb..9a5ffaa550 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -17,7 +17,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 8646b60b1a..81878eafa4 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 64383a2d90..f259982522 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -12,7 +12,7 @@ - + From d27ca993a5670d69bb40dd9879137c56eefe00e8 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 28 Apr 2021 18:33:30 -0600 Subject: [PATCH 1530/1930] Add ability to sort on Genre, MusicGenre, Artist --- Emby.Server.Implementations/Data/SqliteItemRepository.cs | 4 +++- Jellyfin.Api/Controllers/ArtistsController.cs | 7 ++++++- Jellyfin.Api/Controllers/GenresController.cs | 8 +++++++- Jellyfin.Api/Controllers/MusicGenresController.cs | 7 ++++++- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 694805ebe9..a9815ae36e 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -5469,7 +5469,9 @@ AND Type = @InternalPersonType)"); commandText += whereText + " group by PresentationUniqueKey"; - if (query.SimilarTo != null || !string.IsNullOrEmpty(query.SearchTerm)) + if (query.OrderBy.Count != 0 + || query.SimilarTo != null + || !string.IsNullOrEmpty(query.SearchTerm)) { commandText += GetOrderByText(query); } diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 4b2e5e7ea6..85d7c50d34 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -77,6 +77,8 @@ namespace Jellyfin.Api.Controllers /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. /// Optional filter by items whose name is equally or lesser than a given input string. + /// Optional. Specify one or more sort orders, comma delimited. + /// Sort Order - Ascending,Descending. /// Optional, include image information in output. /// Total record count. /// Artists returned. @@ -112,6 +114,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { @@ -150,7 +154,8 @@ namespace Jellyfin.Api.Controllers MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount + EnableTotalRecordCount = enableTotalRecordCount, + OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder) }; if (parentId.HasValue) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 7bcf4674c6..2c67e82f26 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -63,12 +63,15 @@ namespace Jellyfin.Api.Controllers /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. /// Optional filter by items whose name is equally or lesser than a given input string. + /// Optional. Specify one or more sort orders, comma delimited. + /// Sort Order - Ascending,Descending. /// Optional, include image information in output. /// Optional. Include total record count. /// Genres returned. /// An containing the queryresult of genres. [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] + [AllowAnonymous] public ActionResult> GetGenres( [FromQuery] int? startIndex, [FromQuery] int? limit, @@ -84,6 +87,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { @@ -107,7 +112,8 @@ namespace Jellyfin.Api.Controllers NameStartsWithOrGreater = nameStartsWithOrGreater, DtoOptions = dtoOptions, SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount + EnableTotalRecordCount = enableTotalRecordCount, + OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder) }; if (parentId.HasValue) diff --git a/Jellyfin.Api/Controllers/MusicGenresController.cs b/Jellyfin.Api/Controllers/MusicGenresController.cs index 7f7058b5ef..27eec2b9a8 100644 --- a/Jellyfin.Api/Controllers/MusicGenresController.cs +++ b/Jellyfin.Api/Controllers/MusicGenresController.cs @@ -63,6 +63,8 @@ namespace Jellyfin.Api.Controllers /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. /// Optional filter by items whose name is equally or lesser than a given input string. + /// Optional. Specify one or more sort orders, comma delimited. + /// Sort Order - Ascending,Descending. /// Optional, include image information in output. /// Optional. Include total record count. /// Music genres returned. @@ -84,6 +86,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { @@ -107,7 +111,8 @@ namespace Jellyfin.Api.Controllers NameStartsWithOrGreater = nameStartsWithOrGreater, DtoOptions = dtoOptions, SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount + EnableTotalRecordCount = enableTotalRecordCount, + OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder) }; if (parentId.HasValue) From 69e91c33d8af168d12ba02c1a3e4762131ded952 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Thu, 29 Apr 2021 04:10:26 -0600 Subject: [PATCH 1531/1930] Update Jellyfin.Api/Controllers/GenresController.cs --- Jellyfin.Api/Controllers/GenresController.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/GenresController.cs b/Jellyfin.Api/Controllers/GenresController.cs index 2c67e82f26..5aa457153c 100644 --- a/Jellyfin.Api/Controllers/GenresController.cs +++ b/Jellyfin.Api/Controllers/GenresController.cs @@ -71,7 +71,6 @@ namespace Jellyfin.Api.Controllers /// An containing the queryresult of genres. [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] - [AllowAnonymous] public ActionResult> GetGenres( [FromQuery] int? startIndex, [FromQuery] int? limit, From 34313ef2165b4889454eaac92b563fe1998854c0 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 29 Apr 2021 16:23:29 +0200 Subject: [PATCH 1532/1930] SqliteItemRepository: Parse ChannelId directly from utf-8 data --- .../Data/SqliteItemRepository.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 694805ebe9..8d220c807e 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Buffers.Text; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -1311,7 +1312,14 @@ namespace Emby.Server.Implementations.Data if (!reader.IsDBNull(index)) { - item.ChannelId = new Guid(reader.GetString(index)); + if (!Utf8Parser.TryParse(reader[index].ToBlob(), out Guid value, out _, standardFormat: 'N')) + { + var str = reader.GetString(index); + Logger.LogWarning("{ChannelId} isn't in the expected format", str); + value = new Guid(str); + } + + item.ChannelId = value; } index++; From bdab8d1edbbad79ccecd4e0325c090ebf6ded2bc Mon Sep 17 00:00:00 2001 From: Nathan Mascitelli Date: Thu, 29 Apr 2021 22:35:57 -0400 Subject: [PATCH 1533/1930] Add ResumeBook section --- Jellyfin.Data/Enums/HomeSectionType.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Data/Enums/HomeSectionType.cs b/Jellyfin.Data/Enums/HomeSectionType.cs index e597c9431a..9bcd097dc6 100644 --- a/Jellyfin.Data/Enums/HomeSectionType.cs +++ b/Jellyfin.Data/Enums/HomeSectionType.cs @@ -48,6 +48,11 @@ /// /// Live TV. /// - LiveTv = 8 + LiveTv = 8, + + /// + /// Continue Reading. + /// + ResumeBook = 9 } } From 182117d0a7c60a00e03f69bc8cd237ddd3e73f34 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 30 Apr 2021 08:47:38 +0000 Subject: [PATCH 1534/1930] Bump AutoFixture.AutoMoq from 4.16.0 to 4.17.0 Bumps [AutoFixture.AutoMoq](https://github.com/AutoFixture/AutoFixture) from 4.16.0 to 4.17.0. - [Release notes](https://github.com/AutoFixture/AutoFixture/releases) - [Commits](https://github.com/AutoFixture/AutoFixture/compare/v4.16.0...v4.17.0) Signed-off-by: dependabot[bot] --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Implementations.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 9a5ffaa550..397b863b70 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -16,7 +16,7 @@ - + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 7a4ab9b26e..27713d58a3 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -23,7 +23,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 81878eafa4..c1d871126f 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -10,7 +10,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index f259982522..72e40ebcb5 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -11,7 +11,7 @@ - + From e90fbe90f9dc9603b6d9e07cc2c8ee096062c57b Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Fri, 30 Apr 2021 15:07:27 +0200 Subject: [PATCH 1535/1930] Remove extraneous 'stream' parameter The argument isn't passed to the method but causes the API generator to include an unnecessary parameter. Also fixes some typos in the documentation comments. --- Jellyfin.Api/Controllers/VideosController.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Controllers/VideosController.cs b/Jellyfin.Api/Controllers/VideosController.cs index 8dbb6aaa58..e544d001ed 100644 --- a/Jellyfin.Api/Controllers/VideosController.cs +++ b/Jellyfin.Api/Controllers/VideosController.cs @@ -527,7 +527,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The dlna device profile id to utilize. /// The play session id. /// The segment container. - /// The segment lenght. + /// The segment length. /// The minimum number of segments. /// The media version id, if playing an alternate version. /// The device id of the client requesting. Used to stop encoding processes when needed. @@ -556,7 +556,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The maximum video bit depth. /// Optional. Whether to require avc. /// Optional. Whether to deinterlace the video. - /// Optional. Whether to require a non anamporphic stream. + /// Optional. Whether to require a non anamorphic stream. /// Optional. The maximum number of audio channels to transcode. /// Optional. The limit of how many cpu cores to use. /// The live stream id. @@ -570,8 +570,8 @@ namespace Jellyfin.Api.Controllers /// Optional. The streaming options. /// Video stream returned. /// A containing the audio file. - [HttpGet("{itemId}/{stream=stream}.{container}")] - [HttpHead("{itemId}/{stream=stream}.{container}", Name = "HeadVideoStreamByContainer")] + [HttpGet("{itemId}/stream.{container}")] + [HttpHead("{itemId}/stream.{container}", Name = "HeadVideoStreamByContainer")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesVideoFile] public Task GetVideoStreamByContainer( From 608cba817c54df60959079719bafca4d7d54269a Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 30 Apr 2021 15:09:36 +0200 Subject: [PATCH 1536/1930] Reduce some allocations with the magic of spans etc. --- .../Data/SqliteItemRepository.cs | 155 ++++++++++++------ .../Library/MediaSourceManager.cs | 13 +- .../LiveTv/EmbyTV/EmbyTV.cs | 14 +- .../Localization/LocalizationManager.cs | 3 +- .../QuickConnect/QuickConnectManager.cs | 15 +- .../SyncPlay/SyncPlayManager.cs | 13 +- .../Extensions/SplitLinesStringExtensions.cs | 102 ++++++++++++ MediaBrowser.Controller/Entities/Folder.cs | 17 +- .../Entities/ProviderIdsExtensions.cs | 30 ++++ 9 files changed, 267 insertions(+), 95 deletions(-) create mode 100644 MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 28e59913c0..bd5a3e30b1 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1007,15 +1007,12 @@ namespace Emby.Server.Implementations.Data return; } - var parts = value.Split('|', StringSplitOptions.RemoveEmptyEntries); - - foreach (var part in parts) + foreach (var part in value.SpanSplit('|')) { - var idParts = part.Split('='); - - if (idParts.Length == 2) + var providerDelimiterIndex = part.IndexOf('='); + if (providerDelimiterIndex != -1 && providerDelimiterIndex == part.LastIndexOf('=')) { - item.SetProviderId(idParts[0], idParts[1]); + item.SetProviderId(part.Slice(0, providerDelimiterIndex), part.Slice(providerDelimiterIndex + 1)); } } } @@ -1057,9 +1054,8 @@ namespace Emby.Server.Implementations.Data return; } - var parts = value.Split('|' , StringSplitOptions.RemoveEmptyEntries); var list = new List(); - foreach (var part in parts) + foreach (var part in value.SpanSplit('|')) { var image = ItemImageInfoFromValueString(part); @@ -1094,41 +1090,89 @@ namespace Emby.Server.Implementations.Data .Append(hash.Replace('*', '/').Replace('|', '\\')); } - public ItemImageInfo ItemImageInfoFromValueString(string value) + private ItemImageInfo ItemImageInfoFromValueString(ReadOnlySpan value) { - var parts = value.Split('*', StringSplitOptions.None); - - if (parts.Length < 3) + var nextSegment = value.IndexOf('*'); + if (nextSegment == -1) { return null; } - var image = new ItemImageInfo(); + ReadOnlySpan path = value[..nextSegment]; + value = value[(nextSegment + 1)..]; + nextSegment = value.IndexOf('*'); + if (nextSegment == -1) + { + return null; + } - image.Path = RestorePath(parts[0]); + ReadOnlySpan dateModified = value[..nextSegment]; + value = value[(nextSegment + 1)..]; + nextSegment = value.IndexOf('*'); + if (nextSegment == -1) + { + return null; + } - if (long.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks)) + ReadOnlySpan imageType = value[..nextSegment]; + + var image = new ItemImageInfo + { + Path = RestorePath(path.ToString()) + }; + + if (long.TryParse(dateModified, NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks)) { image.DateModified = new DateTime(ticks, DateTimeKind.Utc); } - if (Enum.TryParse(parts[2], true, out ImageType type)) + if (Enum.TryParse(imageType.ToString(), true, out ImageType type)) { image.Type = type; } - if (parts.Length >= 5) + // Optional parameters: width*height*blurhash + if (nextSegment + 1 < value.Length - 1) { - if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var width) - && int.TryParse(parts[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out var height)) + value = value[(nextSegment + 1)..]; + nextSegment = value.IndexOf('*'); + ReadOnlySpan widthSpan = value[..nextSegment]; + + value = value[(nextSegment + 1)..]; + nextSegment = value.IndexOf('*'); + if (nextSegment == -1) + { + return image; + } + + ReadOnlySpan heightSpan = value[..nextSegment]; + + if (int.TryParse(widthSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var width) + && int.TryParse(heightSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var height)) { image.Width = width; image.Height = height; } - if (parts.Length >= 6) + nextSegment += 1; + if (nextSegment < value.Length - 1) { - image.BlurHash = parts[5].Replace('/', '*').Replace('\\', '|'); + value = value[nextSegment..]; + var length = value.Length; + + Span blurHashSpan = stackalloc char[length]; + for (int i = 0; i < length; i++) + { + var c = value[i]; + blurHashSpan[i] = c switch + { + '/' => '*', + '\\' => '|', + _ => c + }; + } + + image.BlurHash = new string(blurHashSpan); } } @@ -2118,27 +2162,6 @@ namespace Emby.Server.Implementations.Data private readonly ItemFields[] _allFields = Enum.GetValues(); - private string[] GetColumnNamesFromField(ItemFields field) - { - switch (field) - { - case ItemFields.Settings: - return new[] { "IsLocked", "PreferredMetadataCountryCode", "PreferredMetadataLanguage", "LockedFields" }; - case ItemFields.ServiceName: - return new[] { "ExternalServiceId" }; - case ItemFields.SortName: - return new[] { "ForcedSortName" }; - case ItemFields.Taglines: - return new[] { "Tagline" }; - case ItemFields.Tags: - return new[] { "Tags" }; - case ItemFields.IsHD: - return Array.Empty(); - default: - return new[] { field.ToString() }; - } - } - private bool HasField(InternalItemsQuery query, ItemFields name) { switch (name) @@ -2327,9 +2350,32 @@ namespace Emby.Server.Implementations.Data { if (!HasField(query, field)) { - foreach (var fieldToRemove in GetColumnNamesFromField(field)) + switch (field) { - list.Remove(fieldToRemove); + case ItemFields.Settings: + list.Remove("IsLocked"); + list.Remove("PreferredMetadataCountryCode"); + list.Remove("PreferredMetadataLanguage"); + list.Remove("LockedFields"); + break; + case ItemFields.ServiceName: + list.Remove("ExternalServiceId"); + break; + case ItemFields.SortName: + list.Remove("ForcedSortName"); + break; + case ItemFields.Taglines: + list.Remove("Tagline"); + break; + case ItemFields.Tags: + list.Remove("Tags"); + break; + case ItemFields.IsHD: + // do nothing + break; + default: + list.Remove(field.ToString()); + break; } } } @@ -2575,10 +2621,21 @@ namespace Emby.Server.Implementations.Data query.Limit = query.Limit.Value + 4; } - var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" })) - + GetFromText() - + GetJoinUserDataText(query); + var commandText = "select "; + if (EnableGroupByPresentationUniqueKey(query)) + { + commandText += "count (distinct PresentationUniqueKey)"; + } + else if (query.GroupBySeriesPresentationUniqueKey) + { + commandText += "count (distinct SeriesPresentationUniqueKey)"; + } + else + { + commandText += "count (guid)"; + } + + commandText += GetFromText() + GetJoinUserDataText(query); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index d0b85f07d4..85d6d3043e 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -590,18 +590,9 @@ namespace Emby.Server.Implementations.Library public Task GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken) { - var info = _openStreams.Values.FirstOrDefault(i => - { - var liveStream = i as ILiveStream; - if (liveStream != null) - { - return string.Equals(liveStream.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase); - } + var info = _openStreams.FirstOrDefault(i => i.Value != null && string.Equals(i.Value.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase)); - return false; - }); - - return Task.FromResult(info as IDirectStreamProvider); + return Task.FromResult(info.Value as IDirectStreamProvider); } public async Task OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationToken) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index c9d9cc49af..665fbfa0fe 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -801,22 +801,22 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV public ActiveRecordingInfo GetActiveRecordingInfo(string path) { - if (string.IsNullOrWhiteSpace(path)) + if (string.IsNullOrWhiteSpace(path) || _activeRecordings.IsEmpty) { return null; } - foreach (var recording in _activeRecordings.Values) + foreach (var (_, recordingInfo) in _activeRecordings) { - if (string.Equals(recording.Path, path, StringComparison.Ordinal) && !recording.CancellationTokenSource.IsCancellationRequested) + if (string.Equals(recordingInfo.Path, path, StringComparison.Ordinal) && !recordingInfo.CancellationTokenSource.IsCancellationRequested) { - var timer = recording.Timer; + var timer = recordingInfo.Timer; if (timer.Status != RecordingStatus.InProgress) { return null; } - return recording; + return recordingInfo; } } @@ -1621,9 +1621,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } return _activeRecordings - .Values - .ToList() - .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase)); + .Any(i => string.Equals(i.Value.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Value.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase)); } private IRecorder GetRecorder(MediaSourceInfo mediaSource) diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 2fdc2b4d91..46858b4fb5 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -315,10 +315,9 @@ namespace Emby.Server.Implementations.Localization } const string Prefix = "Core"; - var key = Prefix + culture; return _dictionaries.GetOrAdd( - key, + culture, f => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult()); } diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs index 22739a0081..0259dc436b 100644 --- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs +++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs @@ -257,20 +257,17 @@ namespace Emby.Server.Implementations.QuickConnect } // Expire stale connection requests - var code = string.Empty; - var values = _currentRequests.Values.ToList(); - - for (int i = 0; i < values.Count; i++) + foreach (var (_, currentRequest) in _currentRequests) { - var added = values[i].DateAdded ?? DateTime.UnixEpoch; - if (DateTime.UtcNow > added.AddMinutes(Timeout) || expireAll) + var added = currentRequest.DateAdded ?? DateTime.UnixEpoch; + if (expireAll || DateTime.UtcNow > added.AddMinutes(Timeout)) { - code = values[i].Code; - _logger.LogDebug("Removing expired request {code}", code); + var code = currentRequest.Code; + _logger.LogDebug("Removing expired request {Code}", code); if (!_currentRequests.TryRemove(code, out _)) { - _logger.LogWarning("Request {code} already expired", code); + _logger.LogWarning("Request {Code} already expired", code); } } } diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 315277985c..72c0a838e2 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -269,14 +269,17 @@ namespace Emby.Server.Implementations.SyncPlay var user = _userManager.GetUserById(session.UserId); List list = new List(); - foreach (var group in _groups.Values) + lock (_groupsLock) { - // Locking required as group is not thread-safe. - lock (group) + foreach (var (_, group) in _groups) { - if (group.HasAccessToPlayQueue(user)) + // Locking required as group is not thread-safe. + lock (group) { - list.Add(group.GetInfo()); + if (group.HasAccessToPlayQueue(user)) + { + list.Add(group.GetInfo()); + } } } } diff --git a/MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs b/MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs new file mode 100644 index 0000000000..5332aba9ff --- /dev/null +++ b/MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs @@ -0,0 +1,102 @@ +/* +MIT License + +Copyright (c) 2019 Gérald Barré + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ +#nullable enable +#pragma warning disable CS1591 +#pragma warning disable CA1034 +using System; +using System.Diagnostics.Contracts; +using System.Runtime.InteropServices; + +namespace MediaBrowser.Common.Extensions +{ + /// + /// Extension class for splitting lines without unnecessary allocations. + /// + public static class SplitLinesStringExtensions + { + /// + /// Creates a new line split enumerator. + /// + /// The string to split. + /// The separator to split on. + /// The enumerator struct. + [Pure] + public static LineSplitEnumerator SpanSplit(this string str, char separator) => new (str.AsSpan(), separator); + + /// + /// Creates a new line split enumerator. + /// + /// The span to split. + /// The separator to split on. + /// The enumerator struct. + [Pure] + public static LineSplitEnumerator Split(this ReadOnlySpan str, char separator) => new (str, separator); + + [StructLayout(LayoutKind.Auto)] + public ref struct LineSplitEnumerator + { + private readonly char _separator; + private ReadOnlySpan _str; + + public LineSplitEnumerator(ReadOnlySpan str, char separator) + { + _str = str; + _separator = separator; + Current = default; + } + + public ReadOnlySpan Current { get; private set; } + + public readonly LineSplitEnumerator GetEnumerator() => this; + + public bool MoveNext() + { + if (_str.Length == 0) + { + return false; + } + + var span = _str; + var index = span.IndexOf(_separator); + if (index == -1) + { + _str = ReadOnlySpan.Empty; + Current = span; + return true; + } + + if (index < span.Length - 1 && span[index] == _separator) + { + Current = span.Slice(0, index); + _str = span[(index + 1)..]; + return true; + } + + Current = span.Slice(0, index); + _str = span[(index + 1)..]; + return true; + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index d45f8758cb..d74e6f9d8c 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1768,20 +1768,15 @@ namespace MediaBrowser.Controller.Entities { EnableImages = false } - }); + }).TotalRecordCount; - double unplayedCount = unplayedQueryResult.TotalRecordCount; + dto.UnplayedItemCount = unplayedQueryResult; - dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount; - - if (itemDto != null && itemDto.RecursiveItemCount.HasValue) + if (itemDto?.RecursiveItemCount > 0) { - if (itemDto.RecursiveItemCount.Value > 0) - { - var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100; - dto.PlayedPercentage = 100 - unplayedPercentage; - dto.Played = dto.PlayedPercentage.Value >= 100; - } + var unplayedPercentage = ((double)unplayedQueryResult / itemDto.RecursiveItemCount.Value) * 100; + dto.PlayedPercentage = 100 - unplayedPercentage; + dto.Played = dto.PlayedPercentage.Value >= 100; } else { diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 09d14dc6a4..bc14da7f2f 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -132,6 +132,36 @@ namespace MediaBrowser.Model.Entities } } + /// + /// Sets a provider id. + /// + /// The instance. + /// The name. + /// The value. + public static void SetProviderId(this IHasProviderIds instance, ReadOnlySpan name, ReadOnlySpan value) + { + if (instance == null) + { + throw new ArgumentNullException(nameof(instance)); + } + + // If it's null remove the key from the dictionary + if (value.IsEmpty) + { + instance.ProviderIds?.Remove(name.ToString()); + } + else + { + // Ensure it exists + if (instance.ProviderIds == null) + { + instance.ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + instance.ProviderIds[name.ToString()] = value.ToString(); + } + } + /// /// Sets a provider id. /// From a6726730fc181599db0ba68545adce9b88c11f7b Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 30 Apr 2021 15:11:16 +0200 Subject: [PATCH 1537/1930] revert the last bits of the getcount experiment --- .../Data/SqliteItemRepository.cs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index bd5a3e30b1..7cee309d09 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -2621,21 +2621,10 @@ namespace Emby.Server.Implementations.Data query.Limit = query.Limit.Value + 4; } - var commandText = "select "; - if (EnableGroupByPresentationUniqueKey(query)) - { - commandText += "count (distinct PresentationUniqueKey)"; - } - else if (query.GroupBySeriesPresentationUniqueKey) - { - commandText += "count (distinct SeriesPresentationUniqueKey)"; - } - else - { - commandText += "count (guid)"; - } - - commandText += GetFromText() + GetJoinUserDataText(query); + var commandText = "select " + + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" })) + + GetFromText() + + GetJoinUserDataText(query); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) From ba2e346d1246cc51e186a64d38a9b7385492ca4f Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 30 Apr 2021 15:27:07 +0200 Subject: [PATCH 1538/1930] prevent cancellationtoken leakage --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +++- Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs | 3 ++- Jellyfin.Api/Helpers/ProgressiveFileCopier.cs | 3 ++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 1dcc786874..c32ca2fb69 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -661,7 +661,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun _modelCache.Clear(); } - cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(discoveryDurationMs).Token, cancellationToken).Token; + using var timedCancellationToken = new CancellationTokenSource(discoveryDurationMs); + using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timedCancellationToken.Token, cancellationToken); + cancellationToken = linkedCancellationTokenSource.Token; var list = new List(); // Create udp broadcast discovery message diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index 78e62ff0a5..f8baf55da7 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -150,7 +150,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken) { - cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token; + using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token); + cancellationToken = linkedCancellationTokenSource.Token; // use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039 var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT; diff --git a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs index 8bddf00d5f..963e177245 100644 --- a/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs +++ b/Jellyfin.Api/Helpers/ProgressiveFileCopier.cs @@ -71,7 +71,8 @@ namespace Jellyfin.Api.Helpers /// A . public async Task WriteToAsync(Stream outputStream, CancellationToken cancellationToken) { - cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken).Token; + using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken); + cancellationToken = linkedCancellationTokenSource.Token; try { From 716cbb06958da987ab917c1f6408396d4ace7a0c Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 30 Apr 2021 23:35:29 +0200 Subject: [PATCH 1539/1930] remove span based setproviderid --- .../Data/SqliteItemRepository.cs | 2 +- .../Entities/ProviderIdsExtensions.cs | 30 ------------------- 2 files changed, 1 insertion(+), 31 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 7cee309d09..e78ebbc502 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1012,7 +1012,7 @@ namespace Emby.Server.Implementations.Data var providerDelimiterIndex = part.IndexOf('='); if (providerDelimiterIndex != -1 && providerDelimiterIndex == part.LastIndexOf('=')) { - item.SetProviderId(part.Slice(0, providerDelimiterIndex), part.Slice(providerDelimiterIndex + 1)); + item.SetProviderId(part.Slice(0, providerDelimiterIndex).ToString(), part.Slice(providerDelimiterIndex + 1).ToString()); } } } diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index bc14da7f2f..09d14dc6a4 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -132,36 +132,6 @@ namespace MediaBrowser.Model.Entities } } - /// - /// Sets a provider id. - /// - /// The instance. - /// The name. - /// The value. - public static void SetProviderId(this IHasProviderIds instance, ReadOnlySpan name, ReadOnlySpan value) - { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - - // If it's null remove the key from the dictionary - if (value.IsEmpty) - { - instance.ProviderIds?.Remove(name.ToString()); - } - else - { - // Ensure it exists - if (instance.ProviderIds == null) - { - instance.ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } - - instance.ProviderIds[name.ToString()] = value.ToString(); - } - } - /// /// Sets a provider id. /// From 70771fdcd60ec5d8a9f13713662778c7e57d0633 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sat, 1 May 2021 13:06:10 +0200 Subject: [PATCH 1540/1930] Nullability handling for device profile classes --- Emby.Dlna/Didl/DidlBuilder.cs | 26 +++-- .../Controllers/UniversalAudioController.cs | 6 +- MediaBrowser.Model/Dlna/ContainerProfile.cs | 63 ++++------- MediaBrowser.Model/Dlna/DeviceProfile.cs | 104 ++++++++---------- MediaBrowser.Model/Dlna/DirectPlayProfile.cs | 11 +- MediaBrowser.Model/Dlna/TranscodingProfile.cs | 27 ++++- 6 files changed, 114 insertions(+), 123 deletions(-) diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index 66ae07329e..c66bdbf22c 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -976,15 +976,28 @@ namespace Emby.Dlna.Didl return; } - var albumartUrlInfo = GetImageUrl(imageInfo, _profile.MaxAlbumArtWidth, _profile.MaxAlbumArtHeight, "jpg"); + // TODO: Remove these default values + var albumArtUrlInfo = GetImageUrl( + imageInfo, + _profile.MaxAlbumArtWidth ?? 10000, + _profile.MaxAlbumArtHeight ?? 10000, + "jpg"); writer.WriteStartElement("upnp", "albumArtURI", NsUpnp); - writer.WriteAttributeString("dlna", "profileID", NsDlna, _profile.AlbumArtPn); - writer.WriteString(albumartUrlInfo.url); + if (!string.IsNullOrEmpty(_profile.AlbumArtPn)) + { + writer.WriteAttributeString("dlna", "profileID", NsDlna, _profile.AlbumArtPn); + } + + writer.WriteString(albumArtUrlInfo.url); writer.WriteFullEndElement(); - // TOOD: Remove these default values - var iconUrlInfo = GetImageUrl(imageInfo, _profile.MaxIconWidth ?? 48, _profile.MaxIconHeight ?? 48, "jpg"); + // TODO: Remove these default values + var iconUrlInfo = GetImageUrl( + imageInfo, + _profile.MaxIconWidth ?? 48, + _profile.MaxIconHeight ?? 48, + "jpg"); writer.WriteElementString("upnp", "icon", NsUpnp, iconUrlInfo.url); if (!_profile.EnableAlbumArtInDidl) @@ -1207,8 +1220,7 @@ namespace Emby.Dlna.Didl if (width.HasValue && height.HasValue) { - var newSize = DrawingUtils.Resize( - new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight); + var newSize = DrawingUtils.Resize(new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight); width = newSize.Width; height = newSize.Height; diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index dcdd8b3677..679f055bc2 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -298,9 +298,9 @@ namespace Jellyfin.Api.Controllers { Type = DlnaProfileType.Audio, Context = EncodingContext.Streaming, - Container = transcodingContainer, - AudioCodec = audioCodec, - Protocol = transcodingProtocol, + Container = transcodingContainer ?? "mp3", + AudioCodec = audioCodec ?? "mp3", + Protocol = transcodingProtocol ?? "http", BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, MaxAudioChannels = transcodingAudioChannels?.ToString(CultureInfo.InvariantCulture) } diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index d83c8f2f3c..54d4f7f38a 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -1,7 +1,7 @@ -#nullable disable #pragma warning disable CS1591 using System; +using System.ComponentModel.DataAnnotations; using System.Linq; using System.Xml.Serialization; @@ -9,25 +9,17 @@ namespace MediaBrowser.Model.Dlna { public class ContainerProfile { - public ContainerProfile() - { - Conditions = Array.Empty(); - } - + [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } - public ProfileCondition[] Conditions { get; set; } + public ProfileCondition[]? Conditions { get; set; } = Array.Empty(); + [Required] [XmlAttribute("container")] - public string Container { get; set; } + public string Container { get; set; } = string.Empty; - public string[] GetContainers() - { - return SplitValue(Container); - } - - public static string[] SplitValue(string value) + public static string[] SplitValue(string? value) { if (string.IsNullOrEmpty(value)) { @@ -37,14 +29,14 @@ namespace MediaBrowser.Model.Dlna return value.Split(',', StringSplitOptions.RemoveEmptyEntries); } - public bool ContainsContainer(string container) + public bool ContainsContainer(string? container) { - var containers = GetContainers(); + var containers = SplitValue(Container); return ContainsContainer(containers, container); } - public static bool ContainsContainer(string profileContainers, string inputContainer) + public static bool ContainsContainer(string? profileContainers, string? inputContainer) { var isNegativeList = false; if (profileContainers != null && profileContainers.StartsWith('-')) @@ -56,46 +48,29 @@ namespace MediaBrowser.Model.Dlna return ContainsContainer(SplitValue(profileContainers), isNegativeList, inputContainer); } - public static bool ContainsContainer(string[] profileContainers, string inputContainer) + public static bool ContainsContainer(string[]? profileContainers, string? inputContainer) { return ContainsContainer(profileContainers, false, inputContainer); } - public static bool ContainsContainer(string[] profileContainers, bool isNegativeList, string inputContainer) + public static bool ContainsContainer(string[]? profileContainers, bool isNegativeList, string? inputContainer) { - if (profileContainers.Length == 0) + if (profileContainers == null || profileContainers.Length == 0) { - return true; + return isNegativeList; } - if (isNegativeList) - { - var allInputContainers = SplitValue(inputContainer); + var allInputContainers = SplitValue(inputContainer); - foreach (var container in allInputContainers) + foreach (var container in allInputContainers) + { + if (profileContainers.Contains(container, StringComparer.OrdinalIgnoreCase)) { - if (profileContainers.Contains(container, StringComparer.OrdinalIgnoreCase)) - { - return false; - } + return !isNegativeList; } - - return true; } - else - { - var allInputContainers = SplitValue(inputContainer); - foreach (var container in allInputContainers) - { - if (profileContainers.Contains(container, StringComparer.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; - } + return isNegativeList; } } } diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index ff51866587..6ec4cb547e 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -1,6 +1,6 @@ -#nullable disable #pragma warning disable CA1819 // Properties should not return arrays using System; +using System.ComponentModel; using System.Linq; using System.Xml.Serialization; using MediaBrowser.Model.MediaInfo; @@ -13,121 +13,104 @@ namespace MediaBrowser.Model.Dlna [XmlRoot("Profile")] public class DeviceProfile { - /// - /// Initializes a new instance of the class. - /// - public DeviceProfile() - { - DirectPlayProfiles = Array.Empty(); - TranscodingProfiles = Array.Empty(); - ResponseProfiles = Array.Empty(); - CodecProfiles = Array.Empty(); - ContainerProfiles = Array.Empty(); - SubtitleProfiles = Array.Empty(); - - XmlRootAttributes = Array.Empty(); - - SupportedMediaTypes = "Audio,Photo,Video"; - MaxStreamingBitrate = 8000000; - MaxStaticBitrate = 8000000; - MusicStreamingTranscodingBitrate = 128000; - } - /// /// Gets or sets the Name. /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the Id. /// [XmlIgnore] - public string Id { get; set; } + public string? Id { get; set; } /// /// Gets or sets the Identification. /// - public DeviceIdentification Identification { get; set; } + public DeviceIdentification? Identification { get; set; } /// /// Gets or sets the FriendlyName. /// - public string FriendlyName { get; set; } + public string? FriendlyName { get; set; } /// /// Gets or sets the Manufacturer. /// - public string Manufacturer { get; set; } + public string? Manufacturer { get; set; } /// /// Gets or sets the ManufacturerUrl. /// - public string ManufacturerUrl { get; set; } + public string? ManufacturerUrl { get; set; } /// /// Gets or sets the ModelName. /// - public string ModelName { get; set; } + public string? ModelName { get; set; } /// /// Gets or sets the ModelDescription. /// - public string ModelDescription { get; set; } + public string? ModelDescription { get; set; } /// /// Gets or sets the ModelNumber. /// - public string ModelNumber { get; set; } + public string? ModelNumber { get; set; } /// /// Gets or sets the ModelUrl. /// - public string ModelUrl { get; set; } + public string? ModelUrl { get; set; } /// /// Gets or sets the SerialNumber. /// - public string SerialNumber { get; set; } + public string? SerialNumber { get; set; } /// /// Gets or sets a value indicating whether EnableAlbumArtInDidl. /// + [DefaultValue(false)] public bool EnableAlbumArtInDidl { get; set; } /// /// Gets or sets a value indicating whether EnableSingleAlbumArtLimit. /// + [DefaultValue(false)] public bool EnableSingleAlbumArtLimit { get; set; } /// /// Gets or sets a value indicating whether EnableSingleSubtitleLimit. /// + [DefaultValue(false)] public bool EnableSingleSubtitleLimit { get; set; } /// /// Gets or sets the SupportedMediaTypes. /// - public string SupportedMediaTypes { get; set; } + public string SupportedMediaTypes { get; set; } = "Audio,Photo,Video"; /// /// Gets or sets the UserId. /// - public string UserId { get; set; } + public string? UserId { get; set; } /// /// Gets or sets the AlbumArtPn. /// - public string AlbumArtPn { get; set; } + public string? AlbumArtPn { get; set; } /// /// Gets or sets the MaxAlbumArtWidth. /// - public int MaxAlbumArtWidth { get; set; } + public int? MaxAlbumArtWidth { get; set; } /// /// Gets or sets the MaxAlbumArtHeight. /// - public int MaxAlbumArtHeight { get; set; } + public int? MaxAlbumArtHeight { get; set; } /// /// Gets or sets the MaxIconWidth. @@ -142,92 +125,97 @@ namespace MediaBrowser.Model.Dlna /// /// Gets or sets the MaxStreamingBitrate. /// - public int? MaxStreamingBitrate { get; set; } + public int? MaxStreamingBitrate { get; set; } = 8000000; /// /// Gets or sets the MaxStaticBitrate. /// - public int? MaxStaticBitrate { get; set; } + public int? MaxStaticBitrate { get; set; } = 8000000; /// /// Gets or sets the MusicStreamingTranscodingBitrate. /// - public int? MusicStreamingTranscodingBitrate { get; set; } + public int? MusicStreamingTranscodingBitrate { get; set; } = 128000; /// /// Gets or sets the MaxStaticMusicBitrate. /// - public int? MaxStaticMusicBitrate { get; set; } + public int? MaxStaticMusicBitrate { get; set; } = 8000000; /// /// Gets or sets the content of the aggregationFlags element in the urn:schemas-sonycom:av namespace. /// - public string SonyAggregationFlags { get; set; } + public string? SonyAggregationFlags { get; set; } /// /// Gets or sets the ProtocolInfo. /// - public string ProtocolInfo { get; set; } + public string? ProtocolInfo { get; set; } /// /// Gets or sets the TimelineOffsetSeconds. /// + [DefaultValue(0)] public int TimelineOffsetSeconds { get; set; } /// /// Gets or sets a value indicating whether RequiresPlainVideoItems. /// + [DefaultValue(false)] public bool RequiresPlainVideoItems { get; set; } /// /// Gets or sets a value indicating whether RequiresPlainFolders. /// + [DefaultValue(false)] public bool RequiresPlainFolders { get; set; } /// /// Gets or sets a value indicating whether EnableMSMediaReceiverRegistrar. /// + [DefaultValue(false)] public bool EnableMSMediaReceiverRegistrar { get; set; } /// /// Gets or sets a value indicating whether IgnoreTranscodeByteRangeRequests. /// + [DefaultValue(false)] public bool IgnoreTranscodeByteRangeRequests { get; set; } /// /// Gets or sets the XmlRootAttributes. /// - public XmlAttribute[] XmlRootAttributes { get; set; } + public XmlAttribute[] XmlRootAttributes { get; set; } = Array.Empty(); /// /// Gets or sets the direct play profiles. /// - public DirectPlayProfile[] DirectPlayProfiles { get; set; } + public DirectPlayProfile[] DirectPlayProfiles { get; set; } = Array.Empty(); /// /// Gets or sets the transcoding profiles. /// - public TranscodingProfile[] TranscodingProfiles { get; set; } + public TranscodingProfile[] TranscodingProfiles { get; set; } = Array.Empty(); /// /// Gets or sets the ContainerProfiles. /// - public ContainerProfile[] ContainerProfiles { get; set; } + public ContainerProfile[] ContainerProfiles { get; set; } = Array.Empty(); /// /// Gets or sets the CodecProfiles. /// - public CodecProfile[] CodecProfiles { get; set; } + public CodecProfile[] CodecProfiles { get; set; } = Array.Empty(); /// /// Gets or sets the ResponseProfiles. /// - public ResponseProfile[] ResponseProfiles { get; set; } + public ResponseProfile[] ResponseProfiles { get; set; } = Array.Empty(); /// /// Gets or sets the SubtitleProfiles. /// - public SubtitleProfile[] SubtitleProfiles { get; set; } + public SubtitleProfile[] SubtitleProfiles { get; set; } = Array.Empty(); /// /// The GetSupportedMediaTypes. @@ -244,13 +232,13 @@ namespace MediaBrowser.Model.Dlna /// The container. /// The audio Codec. /// A . - public TranscodingProfile GetAudioTranscodingProfile(string container, string audioCodec) + public TranscodingProfile? GetAudioTranscodingProfile(string? container, string? audioCodec) { container = (container ?? string.Empty).TrimStart('.'); foreach (var i in TranscodingProfiles) { - if (i.Type != MediaBrowser.Model.Dlna.DlnaProfileType.Audio) + if (i.Type != DlnaProfileType.Audio) { continue; } @@ -278,13 +266,13 @@ namespace MediaBrowser.Model.Dlna /// The audio Codec. /// The video Codec. /// The . - public TranscodingProfile GetVideoTranscodingProfile(string container, string audioCodec, string videoCodec) + public TranscodingProfile? GetVideoTranscodingProfile(string? container, string? audioCodec, string? videoCodec) { container = (container ?? string.Empty).TrimStart('.'); foreach (var i in TranscodingProfiles) { - if (i.Type != MediaBrowser.Model.Dlna.DlnaProfileType.Video) + if (i.Type != DlnaProfileType.Video) { continue; } @@ -299,7 +287,7 @@ namespace MediaBrowser.Model.Dlna continue; } - if (!string.Equals(videoCodec, i.VideoCodec ?? string.Empty, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(videoCodec, i.VideoCodec, StringComparison.OrdinalIgnoreCase)) { continue; } @@ -320,7 +308,7 @@ namespace MediaBrowser.Model.Dlna /// The audio sample rate. /// The audio bit depth. /// The . - public ResponseProfile GetAudioMediaProfile(string container, string audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth) + public ResponseProfile? GetAudioMediaProfile(string container, string? audioCodec, int? audioChannels, int? audioBitrate, int? audioSampleRate, int? audioBitDepth) { foreach (var i in ResponseProfiles) { @@ -384,7 +372,7 @@ namespace MediaBrowser.Model.Dlna /// The width. /// The height. /// The . - public ResponseProfile GetImageMediaProfile(string container, int? width, int? height) + public ResponseProfile? GetImageMediaProfile(string container, int? width, int? height) { foreach (var i in ResponseProfiles) { @@ -442,7 +430,7 @@ namespace MediaBrowser.Model.Dlna /// The video Codec tag. /// True if Avc. /// The . - public ResponseProfile GetVideoMediaProfile( + public ResponseProfile? GetVideoMediaProfile( string container, string audioCodec, string videoCodec, diff --git a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs index 88cb839918..417d915b50 100644 --- a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs +++ b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs @@ -1,6 +1,6 @@ -#nullable disable #pragma warning disable CS1591 +using System.ComponentModel.DataAnnotations; using System.Xml.Serialization; namespace MediaBrowser.Model.Dlna @@ -8,14 +8,15 @@ namespace MediaBrowser.Model.Dlna public class DirectPlayProfile { [XmlAttribute("container")] - public string Container { get; set; } + public string? Container { get; set; } [XmlAttribute("audioCodec")] - public string AudioCodec { get; set; } + public string? AudioCodec { get; set; } [XmlAttribute("videoCodec")] - public string VideoCodec { get; set; } + public string? VideoCodec { get; set; } + [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } @@ -31,7 +32,7 @@ namespace MediaBrowser.Model.Dlna public bool SupportsAudioCodec(string codec) { - return (Type == DlnaProfileType.Audio || Type == DlnaProfileType.Video) && ContainerProfile.ContainsContainer(AudioCodec, codec); + return (Type is DlnaProfileType.Audio or DlnaProfileType.Video) && ContainerProfile.ContainsContainer(AudioCodec, codec); } } } diff --git a/MediaBrowser.Model/Dlna/TranscodingProfile.cs b/MediaBrowser.Model/Dlna/TranscodingProfile.cs index f05e31047c..ea446b733f 100644 --- a/MediaBrowser.Model/Dlna/TranscodingProfile.cs +++ b/MediaBrowser.Model/Dlna/TranscodingProfile.cs @@ -1,54 +1,69 @@ -#nullable disable #pragma warning disable CS1591 +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using System.Xml.Serialization; namespace MediaBrowser.Model.Dlna { public class TranscodingProfile { + [Required] [XmlAttribute("container")] - public string Container { get; set; } + public string Container { get; set; } = string.Empty; + [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } + [Required] [XmlAttribute("videoCodec")] - public string VideoCodec { get; set; } + public string VideoCodec { get; set; } = string.Empty; + [Required] [XmlAttribute("audioCodec")] - public string AudioCodec { get; set; } + public string AudioCodec { get; set; } = string.Empty; + [Required] [XmlAttribute("protocol")] - public string Protocol { get; set; } + public string Protocol { get; set; } = string.Empty; + [DefaultValue(false)] [XmlAttribute("estimateContentLength")] public bool EstimateContentLength { get; set; } + [DefaultValue(false)] [XmlAttribute("enableMpegtsM2TsMode")] public bool EnableMpegtsM2TsMode { get; set; } + [DefaultValue(TranscodeSeekInfo.Auto)] [XmlAttribute("transcodeSeekInfo")] public TranscodeSeekInfo TranscodeSeekInfo { get; set; } + [DefaultValue(false)] [XmlAttribute("copyTimestamps")] public bool CopyTimestamps { get; set; } + [DefaultValue(EncodingContext.Streaming)] [XmlAttribute("context")] public EncodingContext Context { get; set; } + [DefaultValue(false)] [XmlAttribute("enableSubtitlesInManifest")] public bool EnableSubtitlesInManifest { get; set; } [XmlAttribute("maxAudioChannels")] - public string MaxAudioChannels { get; set; } + public string? MaxAudioChannels { get; set; } + [DefaultValue(0)] [XmlAttribute("minSegments")] public int MinSegments { get; set; } + [DefaultValue(0)] [XmlAttribute("segmentLength")] public int SegmentLength { get; set; } + [DefaultValue(false)] [XmlAttribute("breakOnNonKeyFrames")] public bool BreakOnNonKeyFrames { get; set; } From c608d5104df7b7281e35595552734d77e42b5036 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 1 May 2021 15:56:16 +0200 Subject: [PATCH 1541/1930] Fix scanning --- Emby.Server.Implementations/IO/ManagedFileSystem.cs | 2 -- Emby.Server.Implementations/Library/LibraryManager.cs | 2 +- Emby.Server.Implementations/Library/ResolverHelper.cs | 3 +-- MediaBrowser.Controller/Library/ItemResolveArgs.cs | 2 +- MediaBrowser.Model/IO/FileSystemMetadata.cs | 6 ------ 5 files changed, 3 insertions(+), 12 deletions(-) diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index df973f9715..27096ed334 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -260,8 +260,6 @@ namespace Emby.Server.Implementations.IO result.Exists = false; } } - - result.DirectoryName = fileInfo.DirectoryName; } result.CreationTimeUtc = GetCreationTimeUtc(info); diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index ec59ca9b95..7629676f5b 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -683,7 +683,7 @@ namespace Emby.Server.Implementations.Library foreach (var item in items) { - ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService); + ResolverHelper.SetInitialItemValues(item, parent, this, directoryService); } items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions)); diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs index 8be80d726c..b1a2e92847 100644 --- a/Emby.Server.Implementations/Library/ResolverHelper.cs +++ b/Emby.Server.Implementations/Library/ResolverHelper.cs @@ -20,11 +20,10 @@ namespace Emby.Server.Implementations.Library /// /// The item. /// The parent. - /// The file system. /// The library manager. /// The directory service. /// Item must have a path. - public static void SetInitialItemValues(BaseItem item, Folder? parent, IFileSystem fileSystem, ILibraryManager libraryManager, IDirectoryService directoryService) + public static void SetInitialItemValues(BaseItem item, Folder? parent, ILibraryManager libraryManager, IDirectoryService directoryService) { // This version of the below method has no ItemResolveArgs, so we have to require the path already being set if (string.IsNullOrEmpty(item.Path)) diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index df88422370..f86f7df25e 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -87,7 +87,7 @@ namespace MediaBrowser.Controller.Library return false; } - var parentDir = FileInfo.DirectoryName ?? string.Empty; + var parentDir = System.IO.Path.GetDirectoryName(Path) ?? string.Empty; return parentDir.Length > _appPaths.RootFolderPath.Length && parentDir.StartsWith(_appPaths.RootFolderPath, StringComparison.OrdinalIgnoreCase); diff --git a/MediaBrowser.Model/IO/FileSystemMetadata.cs b/MediaBrowser.Model/IO/FileSystemMetadata.cs index 118c78e801..fb74886bfa 100644 --- a/MediaBrowser.Model/IO/FileSystemMetadata.cs +++ b/MediaBrowser.Model/IO/FileSystemMetadata.cs @@ -37,12 +37,6 @@ namespace MediaBrowser.Model.IO /// The length. public long Length { get; set; } - /// - /// Gets or sets the name of the directory. - /// - /// The name of the directory. - public string DirectoryName { get; set; } - /// /// Gets or sets the last write time UTC. /// From e128b6d9978dc219060fe27bc4de0e73495822c2 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 1 May 2021 15:59:21 +0200 Subject: [PATCH 1542/1930] TmdbUtils: Use ordinal string compare --- MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 15a44c7ed3..2498ce9c42 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -63,19 +63,19 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// The Jellyfin person type. public static string MapCrewToPersonType(Crew crew) { - if (crew.Department.Equals("production", StringComparison.InvariantCultureIgnoreCase) - && crew.Job.Contains("director", StringComparison.InvariantCultureIgnoreCase)) + if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase) + && crew.Job.Contains("director", StringComparison.OrdinalIgnoreCase)) { return PersonType.Director; } - if (crew.Department.Equals("production", StringComparison.InvariantCultureIgnoreCase) - && crew.Job.Contains("producer", StringComparison.InvariantCultureIgnoreCase)) + if (crew.Department.Equals("production", StringComparison.OrdinalIgnoreCase) + && crew.Job.Contains("producer", StringComparison.OrdinalIgnoreCase)) { return PersonType.Producer; } - if (crew.Department.Equals("writing", StringComparison.InvariantCultureIgnoreCase)) + if (crew.Department.Equals("writing", StringComparison.OrdinalIgnoreCase)) { return PersonType.Writer; } From 8a6b9e1fb6d89ac77bd8d62da66bd05abd75ca65 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 2 May 2021 00:26:30 +0200 Subject: [PATCH 1543/1930] Add tests for SqliteItemRepository.(De)SerializeImages --- .../Data/SqliteItemRepository.cs | 41 ++--- .../Data/SqliteItemRepositoryTests.cs | 172 ++++++++++++++++++ 2 files changed, 191 insertions(+), 22 deletions(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 28e59913c0..9b558d34b1 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -502,7 +502,7 @@ namespace Emby.Server.Implementations.Data using (var saveImagesStatement = base.PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id")) { saveImagesStatement.TryBind("@Id", item.Id.ToByteArray()); - saveImagesStatement.TryBind("@Images", SerializeImages(item)); + saveImagesStatement.TryBind("@Images", SerializeImages(item.ImageInfos)); saveImagesStatement.MoveNext(); } @@ -898,7 +898,7 @@ namespace Emby.Server.Implementations.Data saveItemStatement.TryBind("@Tagline", item.Tagline); saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item)); - saveItemStatement.TryBind("@Images", SerializeImages(item)); + saveItemStatement.TryBind("@Images", SerializeImages(item.ImageInfos)); if (item.ProductionLocations.Length > 0) { @@ -1020,10 +1020,8 @@ namespace Emby.Server.Implementations.Data } } - private string SerializeImages(BaseItem item) + internal string SerializeImages(ItemImageInfo[] images) { - var images = item.ImageInfos; - if (images.Length == 0) { return null; @@ -1045,16 +1043,11 @@ namespace Emby.Server.Implementations.Data return str.ToString(); } - private void DeserializeImages(string value, BaseItem item) + internal ItemImageInfo[] DeserializeImages(string value) { if (string.IsNullOrWhiteSpace(value)) { - return; - } - - if (item.ImageInfos.Length > 0) - { - return; + return Array.Empty(); } var parts = value.Split('|' , StringSplitOptions.RemoveEmptyEntries); @@ -1069,15 +1062,14 @@ namespace Emby.Server.Implementations.Data } } - item.ImageInfos = list.ToArray(); + return list.ToArray(); } - public void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image) + private void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image) { const char Delimiter = '*'; var path = image.Path ?? string.Empty; - var hash = image.BlurHash ?? string.Empty; bldr.Append(GetPathToSave(path)) .Append(Delimiter) @@ -1087,11 +1079,16 @@ namespace Emby.Server.Implementations.Data .Append(Delimiter) .Append(image.Width) .Append(Delimiter) - .Append(image.Height) - .Append(Delimiter) - // Replace delimiters with other characters. - // This can be removed when we migrate to a proper DB. - .Append(hash.Replace('*', '/').Replace('|', '\\')); + .Append(image.Height); + + var hash = image.BlurHash; + if (!string.IsNullOrEmpty(hash)) + { + bldr.Append(Delimiter) + // Replace delimiters with other characters. + // This can be removed when we migrate to a proper DB. + .Append(hash.Replace('*', '/').Replace('|', '\\')); + } } public ItemImageInfo ItemImageInfoFromValueString(string value) @@ -1797,11 +1794,11 @@ namespace Emby.Server.Implementations.Data index++; - if (query.DtoOptions.EnableImages) + if (query.DtoOptions.EnableImages && item.ImageInfos.Length == 0) { if (!reader.IsDBNull(index)) { - DeserializeImages(reader.GetString(index), item); + item.ImageInfos = DeserializeImages(reader.GetString(index)); } index++; diff --git a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs new file mode 100644 index 0000000000..e9cfd5b128 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Server.Implementations.Data; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Entities; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Data +{ + public class SqliteItemRepositoryTests + { + public const string VirtualMetaDataPath = "%MetadataPath%"; + public const string MetaDataPath = "/meta/data/path"; + + private readonly IFixture _fixture; + private readonly SqliteItemRepository _sqliteItemRepository; + + public SqliteItemRepositoryTests() + { + var appHost = new Mock(); + appHost.Setup(x => x.ExpandVirtualPath(It.IsAny())) + .Returns((string x) => x.Replace(VirtualMetaDataPath, MetaDataPath, StringComparison.Ordinal)); + appHost.Setup(x => x.ReverseVirtualPath(It.IsAny())) + .Returns((string x) => x.Replace(MetaDataPath, VirtualMetaDataPath, StringComparison.Ordinal)); + + _fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }); + _fixture.Inject(appHost); + _sqliteItemRepository = _fixture.Create(); + } + + public static IEnumerable ItemImageInfoFromValueString_Valid_TestData() + { + yield return new object[] + { + "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN", + new ItemImageInfo() + { + Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg", + Type = ImageType.Primary, + DateModified = new DateTime(637452096478512963, DateTimeKind.Utc), + Width = 1920, + Height = 1080, + BlurHash = "WjQbtJtSO8nhNZ%L_Io#R*oaS6o}-;adXAoIn7j[%hW9s:WGw[nN" + } + }; + + yield return new object[] + { + "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary*0*0", + new ItemImageInfo() + { + Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg", + Type = ImageType.Primary, + } + }; + + yield return new object[] + { + "%MetadataPath%/library/68/68578562b96c80a7ebd530848801f645/poster.jpg*637264380567586027*Primary*600*336", + new ItemImageInfo() + { + Path = "/meta/data/path/library/68/68578562b96c80a7ebd530848801f645/poster.jpg", + Type = ImageType.Primary, + DateModified = new DateTime(637264380567586027, DateTimeKind.Utc), + Width = 600, + Height = 336 + } + }; + } + + [Theory] + [MemberData(nameof(ItemImageInfoFromValueString_Valid_TestData))] + public void ItemImageInfoFromValueString_Valid_Success(string value, ItemImageInfo expected) + { + var result = _sqliteItemRepository.ItemImageInfoFromValueString(value); + Assert.Equal(expected.Path, result.Path); + Assert.Equal(expected.Type, result.Type); + Assert.Equal(expected.DateModified, result.DateModified); + Assert.Equal(expected.Width, result.Width); + Assert.Equal(expected.Height, result.Height); + Assert.Equal(expected.BlurHash, result.BlurHash); + } + + [Theory] + [InlineData("")] + [InlineData("*")] + public void ItemImageInfoFromValueString_Invalid_Null(string value) + { + Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value)); + } + + public static IEnumerable DeserializeImages_Valid_TestData() + { + yield return new object[] + { + "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN", + new ItemImageInfo[] + { + new ItemImageInfo() + { + Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg", + Type = ImageType.Primary, + DateModified = new DateTime(637452096478512963, DateTimeKind.Utc), + Width = 1920, + Height = 1080, + BlurHash = "WjQbtJtSO8nhNZ%L_Io#R*oaS6o}-;adXAoIn7j[%hW9s:WGw[nN" + } + } + }; + + yield return new object[] + { + "%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/poster.jpg*637261226720645297*Primary*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/logo.png*637261226720805297*Logo*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/landscape.jpg*637261226721285297*Thumb*0*0|%MetadataPath%/library/2a/2a27372f1e9bc757b1db99721bbeae1e/backdrop.jpg*637261226721685297*Backdrop*0*0", + new ItemImageInfo[] + { + new ItemImageInfo() + { + Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/poster.jpg", + Type = ImageType.Primary, + DateModified = new DateTime(637261226720645297, DateTimeKind.Utc), + }, + new ItemImageInfo() + { + Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/logo.png", + Type = ImageType.Logo, + DateModified = new DateTime(637261226720805297, DateTimeKind.Utc), + }, + new ItemImageInfo() + { + Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/landscape.jpg", + Type = ImageType.Thumb, + DateModified = new DateTime(637261226721285297, DateTimeKind.Utc), + }, + new ItemImageInfo() + { + Path = "/meta/data/path/library/2a/2a27372f1e9bc757b1db99721bbeae1e/backdrop.jpg", + Type = ImageType.Backdrop, + DateModified = new DateTime(637261226721685297, DateTimeKind.Utc), + } + } + }; + } + + [Theory] + [MemberData(nameof(DeserializeImages_Valid_TestData))] + public void DeserializeImages_Valid_Success(string value, ItemImageInfo[] expected) + { + var result = _sqliteItemRepository.DeserializeImages(value); + Assert.Equal(expected.Length, result.Length); + for (int i = 0; i < expected.Length; i++) + { + Assert.Equal(expected[i].Path, result[i].Path); + Assert.Equal(expected[i].Type, result[i].Type); + Assert.Equal(expected[i].DateModified, result[i].DateModified); + Assert.Equal(expected[i].Width, result[i].Width); + Assert.Equal(expected[i].Height, result[i].Height); + Assert.Equal(expected[i].BlurHash, result[i].BlurHash); + } + } + + [Theory] + [MemberData(nameof(DeserializeImages_Valid_TestData))] + public void SerializeImages_Valid_Success(string expected, ItemImageInfo[] value) + { + Assert.Equal(expected, _sqliteItemRepository.SerializeImages(value)); + } + } +} From dc81d576ab78cc6e666f768343cb6d29e5820670 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sun, 2 May 2021 01:20:58 -0400 Subject: [PATCH 1544/1930] Remove /Images/Remote API endpoint --- .../Controllers/RemoteImageController.cs | 52 ------------------- 1 file changed, 52 deletions(-) diff --git a/Jellyfin.Api/Controllers/RemoteImageController.cs b/Jellyfin.Api/Controllers/RemoteImageController.cs index e226adc646..ec836f43e3 100644 --- a/Jellyfin.Api/Controllers/RemoteImageController.cs +++ b/Jellyfin.Api/Controllers/RemoteImageController.cs @@ -145,58 +145,6 @@ namespace Jellyfin.Api.Controllers return Ok(_providerManager.GetRemoteImageProviderInfo(item)); } - /// - /// Gets a remote image. - /// - /// The image url. - /// Remote image returned. - /// Remote image not found. - /// Image Stream. - [HttpGet("Images/Remote")] - [Produces(MediaTypeNames.Application.Octet)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - [ProducesImageFile] - public async Task GetRemoteImage([FromQuery, Required] Uri imageUrl) - { - var urlHash = imageUrl.ToString().GetMD5(); - var pointerCachePath = GetFullCachePath(urlHash.ToString()); - - string? contentPath = null; - var hasFile = false; - - try - { - contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false); - if (System.IO.File.Exists(contentPath)) - { - hasFile = true; - } - } - catch (FileNotFoundException) - { - // The file isn't cached yet - } - catch (IOException) - { - // The file isn't cached yet - } - - if (!hasFile) - { - await DownloadImage(imageUrl, urlHash, pointerCachePath).ConfigureAwait(false); - contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false); - } - - if (string.IsNullOrEmpty(contentPath)) - { - return NotFound(); - } - - var contentType = MimeTypes.GetMimeType(contentPath); - return PhysicalFile(contentPath, contentType); - } - /// /// Downloads a remote image for an item. /// From 3e4c86098613d92eb2fc34ee158459c0d063f910 Mon Sep 17 00:00:00 2001 From: "Joshua M. Boniface" Date: Sun, 2 May 2021 01:22:52 -0400 Subject: [PATCH 1545/1930] Remove /Items/RemoteSearch/Image API endpoint --- .../Controllers/ItemLookupController.cs | 91 ------------------- 1 file changed, 91 deletions(-) diff --git a/Jellyfin.Api/Controllers/ItemLookupController.cs b/Jellyfin.Api/Controllers/ItemLookupController.cs index dabd4deb79..9fa307858f 100644 --- a/Jellyfin.Api/Controllers/ItemLookupController.cs +++ b/Jellyfin.Api/Controllers/ItemLookupController.cs @@ -237,48 +237,6 @@ namespace Jellyfin.Api.Controllers return Ok(results); } - /// - /// Gets a remote image. - /// - /// The image url. - /// The provider name. - /// Remote image retrieved. - /// - /// A that represents the asynchronous operation to get the remote search results. - /// The task result contains an containing the images file stream. - /// - [HttpGet("Items/RemoteSearch/Image")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesImageFile] - public async Task GetRemoteSearchImage( - [FromQuery, Required] string imageUrl, - [FromQuery, Required] string providerName) - { - var urlHash = imageUrl.GetMD5(); - var pointerCachePath = GetFullCachePath(urlHash.ToString()); - - try - { - var contentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false); - if (System.IO.File.Exists(contentPath)) - { - return PhysicalFile(contentPath, MimeTypes.GetMimeType(contentPath)); - } - } - catch (FileNotFoundException) - { - // Means the file isn't cached yet - } - catch (IOException) - { - // Means the file isn't cached yet - } - - await DownloadImage(providerName, imageUrl, urlHash, pointerCachePath).ConfigureAwait(false); - var updatedContentPath = await System.IO.File.ReadAllTextAsync(pointerCachePath).ConfigureAwait(false); - return PhysicalFile(updatedContentPath, MimeTypes.GetMimeType(updatedContentPath)); - } - /// /// Applies search criteria to an item and refreshes metadata. /// @@ -320,54 +278,5 @@ namespace Jellyfin.Api.Controllers return NoContent(); } - - /// - /// Downloads the image. - /// - /// Name of the provider. - /// The URL. - /// The URL hash. - /// The pointer cache path. - /// Task. - private async Task DownloadImage(string providerName, string url, Guid urlHash, string pointerCachePath) - { - using var result = await _providerManager.GetSearchImage(providerName, url, CancellationToken.None).ConfigureAwait(false); - if (result.Content.Headers.ContentType?.MediaType == null) - { - throw new ResourceNotFoundException(nameof(result.Content.Headers.ContentType)); - } - - var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; - var fullCachePath = GetFullCachePath(urlHash + "." + ext); - - var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException($"Provided path ({fullCachePath}) is not valid."); - Directory.CreateDirectory(directory); - using (var stream = result.Content) - { - // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 . - await using var fileStream = new FileStream( - fullCachePath, - FileMode.Create, - FileAccess.Write, - FileShare.None, - IODefaults.FileStreamBufferSize, - true); - - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - } - - var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ArgumentException($"Provided path ({pointerCachePath}) is not valid.", nameof(pointerCachePath)); - - Directory.CreateDirectory(pointerCacheDirectory); - await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false); - } - - /// - /// Gets the full cache path. - /// - /// The filename. - /// System.String. - private string GetFullCachePath(string filename) - => Path.Combine(_appPaths.CachePath, "remote-images", filename.Substring(0, 1), filename); } } From 874f92e93a1411fbba7097f0665db68234441dfa Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 2 May 2021 12:45:02 +0200 Subject: [PATCH 1546/1930] Add tests for SqliteItemRepository.(De)SerializeProviderIds --- .../Data/SqliteItemRepository.cs | 19 +++---- .../Data/SqliteItemRepositoryTests.cs | 57 +++++++++++++++++++ 2 files changed, 64 insertions(+), 12 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 9b558d34b1..786e3b6fa1 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -897,7 +897,7 @@ namespace Emby.Server.Implementations.Data saveItemStatement.TryBind("@ExternalSeriesId", item.ExternalSeriesId); saveItemStatement.TryBind("@Tagline", item.Tagline); - saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item)); + saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item.ProviderIds)); saveItemStatement.TryBind("@Images", SerializeImages(item.ImageInfos)); if (item.ProductionLocations.Length > 0) @@ -968,10 +968,10 @@ namespace Emby.Server.Implementations.Data saveItemStatement.MoveNext(); } - private static string SerializeProviderIds(BaseItem item) + internal static string SerializeProviderIds(Dictionary providerIds) { StringBuilder str = new StringBuilder(); - foreach (var i in item.ProviderIds) + foreach (var i in providerIds) { // Ideally we shouldn't need this IsNullOrWhiteSpace check, // but we're seeing some cases of bad data slip through @@ -995,18 +995,13 @@ namespace Emby.Server.Implementations.Data return str.ToString(); } - private static void DeserializeProviderIds(string value, BaseItem item) + internal static void DeserializeProviderIds(string value, IHasProviderIds item) { if (string.IsNullOrWhiteSpace(value)) { return; } - if (item.ProviderIds.Count > 0) - { - return; - } - var parts = value.Split('|', StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) @@ -1787,16 +1782,16 @@ namespace Emby.Server.Implementations.Data index++; } - if (!reader.IsDBNull(index)) + if (item.ProviderIds.Count == 0 && !reader.IsDBNull(index)) { DeserializeProviderIds(reader.GetString(index), item); } index++; - if (query.DtoOptions.EnableImages && item.ImageInfos.Length == 0) + if (query.DtoOptions.EnableImages) { - if (!reader.IsDBNull(index)) + if (item.ImageInfos.Length == 0 && !reader.IsDBNull(index)) { item.ImageInfos = DeserializeImages(reader.GetString(index)); } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs index e9cfd5b128..af6ec32458 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs @@ -168,5 +168,62 @@ namespace Jellyfin.Server.Implementations.Tests.Data { Assert.Equal(expected, _sqliteItemRepository.SerializeImages(value)); } + + public static IEnumerable DeserializeProviderIds_Valid_TestData() + { + yield return new object[] + { + "Imdb=tt0119567", + new Dictionary() + { + { "Imdb", "tt0119567" }, + } + }; + + yield return new object[] + { + "Imdb=tt0119567|Tmdb=330|TmdbCollection=328", + new Dictionary() + { + { "Imdb", "tt0119567" }, + { "Tmdb", "330" }, + { "TmdbCollection", "328" }, + } + }; + + yield return new object[] + { + "MusicBrainzAlbum=9d363e43-f24f-4b39-bc5a-7ef305c677c7|MusicBrainzReleaseGroup=63eba062-847c-3b73-8b0f-6baf27bba6fa|AudioDbArtist=111352|AudioDbAlbum=2116560|MusicBrainzAlbumArtist=20244d07-534f-4eff-b4d4-930878889970", + new Dictionary() + { + { "MusicBrainzAlbum", "9d363e43-f24f-4b39-bc5a-7ef305c677c7" }, + { "MusicBrainzReleaseGroup", "63eba062-847c-3b73-8b0f-6baf27bba6fa" }, + { "AudioDbArtist", "111352" }, + { "AudioDbAlbum", "2116560" }, + { "MusicBrainzAlbumArtist", "20244d07-534f-4eff-b4d4-930878889970" }, + } + }; + } + + [Theory] + [MemberData(nameof(DeserializeProviderIds_Valid_TestData))] + public void DeserializeProviderIds_Valid_Success(string value, Dictionary expected) + { + var result = new ProviderIdsExtensionsTestsObject(); + SqliteItemRepository.DeserializeProviderIds(value, result); + Assert.Equal(expected, result.ProviderIds); + } + + [Theory] + [MemberData(nameof(DeserializeProviderIds_Valid_TestData))] + public void SerializeProviderIds_Valid_Success(string expected, Dictionary values) + { + Assert.Equal(expected, SqliteItemRepository.SerializeProviderIds(values)); + } + + private class ProviderIdsExtensionsTestsObject : IHasProviderIds + { + public Dictionary ProviderIds { get; set; } = new Dictionary(); + } } } From bdd7a37794518b0487b191e7dbbbd3beb2397458 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sun, 2 May 2021 13:04:35 +0200 Subject: [PATCH 1547/1930] Don't run integration tests in parallel * Easier to debug failing tests when the logs aren't scrambled * Static properties could cause issues --- .../Jellyfin.Server.Integration.Tests.csproj | 7 +++++++ tests/Jellyfin.Server.Integration.Tests/xunit.runner.json | 4 ++++ 2 files changed, 11 insertions(+) create mode 100644 tests/Jellyfin.Server.Integration.Tests/xunit.runner.json diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index c1d871126f..938385a2ad 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -22,6 +22,13 @@ + + + + PreserveNewest + + + diff --git a/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json b/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json new file mode 100644 index 0000000000..809e880c71 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/xunit.runner.json @@ -0,0 +1,4 @@ +{ + "parallelizeAssembly": false, + "parallelizeTestCollections": false +} From bcba501dfbe1e0f422829f26159d9a9625530231 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sun, 2 May 2021 19:25:04 +0100 Subject: [PATCH 1548/1930] minor optimization. --- Emby.Server.Implementations/Plugins/PluginManager.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 3a8296455b..fd2ee6b7a7 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -166,9 +166,7 @@ namespace Emby.Server.Implementations.Plugins /// public void CreatePlugins() { - _ = _appHost.GetExports(CreatePluginInstance) - .Where(i => i != null) - .ToArray(); + _ = _appHost.GetExports(CreatePluginInstance); } /// From 6f722bac0f5b3fb019a8313753b198f34afa714c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 May 2021 12:00:39 +0000 Subject: [PATCH 1549/1930] Bump Swashbuckle.AspNetCore from 6.1.3 to 6.1.4 Bumps [Swashbuckle.AspNetCore](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.1.3 to 6.1.4. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.1.3...v6.1.4) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index 3868882e5e..d6d07cd27c 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -17,7 +17,7 @@ - + From 9b1243cf5ef21bffdd31054e35121d811688ba3c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 May 2021 12:00:50 +0000 Subject: [PATCH 1550/1930] Bump SQLitePCL.pretty.netstandard from 2.1.0 to 2.2.0 Bumps [SQLitePCL.pretty.netstandard](https://github.com/jellyfin/SQLitePCL.pretty.netstandard) from 2.1.0 to 2.2.0. - [Release notes](https://github.com/jellyfin/SQLitePCL.pretty.netstandard/releases) - [Commits](https://github.com/jellyfin/SQLitePCL.pretty.netstandard/commits) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index adbfe52c4e..b8a544b8c3 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -31,7 +31,7 @@ - + From 2ee33bd602fb17411774b278a3f104e5121fab13 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 May 2021 12:03:25 +0000 Subject: [PATCH 1551/1930] Bump alex-page/github-project-automation-plus from v0.6.0 to v0.7.1 Bumps [alex-page/github-project-automation-plus](https://github.com/alex-page/github-project-automation-plus) from v0.6.0 to v0.7.1. - [Release notes](https://github.com/alex-page/github-project-automation-plus/releases) - [Commits](https://github.com/alex-page/github-project-automation-plus/compare/v0.6.0...50502d399cbb98cefe7ce1f99f93f78c6756562e) Signed-off-by: dependabot[bot] --- .github/workflows/automation.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index d5d3081857..a203e66956 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -16,7 +16,7 @@ jobs: label: stable backport - name: Remove from 'Current Release' project - uses: alex-page/github-project-automation-plus@v0.6.0 + uses: alex-page/github-project-automation-plus@v0.7.1 if: (github.event.pull_request || github.event.issue.pull_request) && !steps.checkLabel.outputs.hasLabel continue-on-error: true with: @@ -25,7 +25,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add to 'Release Next' project - uses: alex-page/github-project-automation-plus@v0.6.0 + uses: alex-page/github-project-automation-plus@v0.7.1 if: (github.event.pull_request || github.event.issue.pull_request) && github.event.action == 'opened' continue-on-error: true with: @@ -34,7 +34,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add to 'Current Release' project - uses: alex-page/github-project-automation-plus@v0.6.0 + uses: alex-page/github-project-automation-plus@v0.7.1 if: (github.event.pull_request || github.event.issue.pull_request) && steps.checkLabel.outputs.hasLabel continue-on-error: true with: @@ -48,7 +48,7 @@ jobs: run: echo "::set-output name=number::$(curl -s ${{ github.event.issue.comments_url }} | jq '.[] | select(.author_association == "MEMBER") | .author_association' | wc -l)" - name: Move issue to needs triage - uses: alex-page/github-project-automation-plus@v0.6.0 + uses: alex-page/github-project-automation-plus@v0.7.1 if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' && steps.member_comments.outputs.number <= 1 continue-on-error: true with: @@ -57,7 +57,7 @@ jobs: repo-token: ${{ secrets.GH_TOKEN }} - name: Add issue to triage project - uses: alex-page/github-project-automation-plus@v0.6.0 + uses: alex-page/github-project-automation-plus@v0.7.1 if: github.event.issue.pull_request == '' && github.event.action == 'opened' continue-on-error: true with: From c0feb3694b86ccc242a637468070daff9120e631 Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 3 May 2021 23:51:45 +0200 Subject: [PATCH 1552/1930] rename to SplitEnumerator and fix test --- .../Data/SqliteItemRepository.cs | 14 ++++++--- ...Extensions.cs => SplitStringExtensions.cs} | 16 +++++----- .../Data/SqliteItemRepositoryTests.cs | 31 ++++++++++++++++--- 3 files changed, 43 insertions(+), 18 deletions(-) rename MediaBrowser.Common/Extensions/{SplitLinesStringExtensions.cs => SplitStringExtensions.cs} (84%) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 292ff48faa..4b9b0bed08 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1082,7 +1082,7 @@ namespace Emby.Server.Implementations.Data } } - private ItemImageInfo ItemImageInfoFromValueString(ReadOnlySpan value) + internal ItemImageInfo ItemImageInfoFromValueString(ReadOnlySpan value) { var nextSegment = value.IndexOf('*'); if (nextSegment == -1) @@ -1103,7 +1103,7 @@ namespace Emby.Server.Implementations.Data nextSegment = value.IndexOf('*'); if (nextSegment == -1) { - return null; + nextSegment = value.Length; } ReadOnlySpan imageType = value[..nextSegment]; @@ -1128,13 +1128,18 @@ namespace Emby.Server.Implementations.Data { value = value[(nextSegment + 1)..]; nextSegment = value.IndexOf('*'); + if (nextSegment == -1 || nextSegment == value.Length) + { + return image; + } + ReadOnlySpan widthSpan = value[..nextSegment]; value = value[(nextSegment + 1)..]; nextSegment = value.IndexOf('*'); if (nextSegment == -1) { - return image; + nextSegment = value.Length; } ReadOnlySpan heightSpan = value[..nextSegment]; @@ -1146,10 +1151,9 @@ namespace Emby.Server.Implementations.Data image.Height = height; } - nextSegment += 1; if (nextSegment < value.Length - 1) { - value = value[nextSegment..]; + value = value[(nextSegment + 1)..]; var length = value.Length; Span blurHashSpan = stackalloc char[length]; diff --git a/MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs similarity index 84% rename from MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs rename to MediaBrowser.Common/Extensions/SplitStringExtensions.cs index 5332aba9ff..6c1c45013d 100644 --- a/MediaBrowser.Common/Extensions/SplitLinesStringExtensions.cs +++ b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs @@ -33,33 +33,33 @@ namespace MediaBrowser.Common.Extensions /// /// Extension class for splitting lines without unnecessary allocations. /// - public static class SplitLinesStringExtensions + public static class SplitStringExtensions { /// - /// Creates a new line split enumerator. + /// Creates a new string split enumerator. /// /// The string to split. /// The separator to split on. /// The enumerator struct. [Pure] - public static LineSplitEnumerator SpanSplit(this string str, char separator) => new (str.AsSpan(), separator); + public static SplitEnumerator SpanSplit(this string str, char separator) => new (str.AsSpan(), separator); /// - /// Creates a new line split enumerator. + /// Creates a new span split enumerator. /// /// The span to split. /// The separator to split on. /// The enumerator struct. [Pure] - public static LineSplitEnumerator Split(this ReadOnlySpan str, char separator) => new (str, separator); + public static SplitEnumerator Split(this ReadOnlySpan str, char separator) => new (str, separator); [StructLayout(LayoutKind.Auto)] - public ref struct LineSplitEnumerator + public ref struct SplitEnumerator { private readonly char _separator; private ReadOnlySpan _str; - public LineSplitEnumerator(ReadOnlySpan str, char separator) + public SplitEnumerator(ReadOnlySpan str, char separator) { _str = str; _separator = separator; @@ -68,7 +68,7 @@ namespace MediaBrowser.Common.Extensions public ReadOnlySpan Current { get; private set; } - public readonly LineSplitEnumerator GetEnumerator() => this; + public readonly SplitEnumerator GetEnumerator() => this; public bool MoveNext() { diff --git a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs index af6ec32458..c0f34afa76 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs @@ -37,7 +37,7 @@ namespace Jellyfin.Server.Implementations.Tests.Data yield return new object[] { "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg*637452096478512963*Primary*1920*1080*WjQbtJtSO8nhNZ%L_Io#R/oaS6o}-;adXAoIn7j[%hW9s:WGw[nN", - new ItemImageInfo() + new ItemImageInfo { Path = "/mnt/series/Family Guy/Season 1/Family Guy - S01E01-thumb.jpg", Type = ImageType.Primary, @@ -51,7 +51,27 @@ namespace Jellyfin.Server.Implementations.Tests.Data yield return new object[] { "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary*0*0", - new ItemImageInfo() + new ItemImageInfo + { + Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg", + Type = ImageType.Primary, + } + }; + + yield return new object[] + { + "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary", + new ItemImageInfo + { + Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg", + Type = ImageType.Primary, + } + }; + + yield return new object[] + { + "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0*Primary*600", + new ItemImageInfo { Path = "https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg", Type = ImageType.Primary, @@ -61,7 +81,7 @@ namespace Jellyfin.Server.Implementations.Tests.Data yield return new object[] { "%MetadataPath%/library/68/68578562b96c80a7ebd530848801f645/poster.jpg*637264380567586027*Primary*600*336", - new ItemImageInfo() + new ItemImageInfo { Path = "/meta/data/path/library/68/68578562b96c80a7ebd530848801f645/poster.jpg", Type = ImageType.Primary, @@ -76,7 +96,7 @@ namespace Jellyfin.Server.Implementations.Tests.Data [MemberData(nameof(ItemImageInfoFromValueString_Valid_TestData))] public void ItemImageInfoFromValueString_Valid_Success(string value, ItemImageInfo expected) { - var result = _sqliteItemRepository.ItemImageInfoFromValueString(value); + var result = _sqliteItemRepository.ItemImageInfoFromValueString(value.AsSpan()); Assert.Equal(expected.Path, result.Path); Assert.Equal(expected.Type, result.Type); Assert.Equal(expected.DateModified, result.DateModified); @@ -88,9 +108,10 @@ namespace Jellyfin.Server.Implementations.Tests.Data [Theory] [InlineData("")] [InlineData("*")] + [InlineData("https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0")] public void ItemImageInfoFromValueString_Invalid_Null(string value) { - Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value)); + Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value.AsSpan())); } public static IEnumerable DeserializeImages_Valid_TestData() From ee92dffa82bf2cc5eb6e8e088a391c3e22c03345 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 4 May 2021 09:01:23 +0000 Subject: [PATCH 1553/1930] Bump Swashbuckle.AspNetCore.ReDoc from 6.1.3 to 6.1.4 Bumps [Swashbuckle.AspNetCore.ReDoc](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) from 6.1.3 to 6.1.4. - [Release notes](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/releases) - [Commits](https://github.com/domaindrivendev/Swashbuckle.AspNetCore/compare/v6.1.3...v6.1.4) Signed-off-by: dependabot[bot] --- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index d6d07cd27c..c10c34b59a 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -18,7 +18,7 @@ - + From ad3e835bcf7e800b483495af74adc36e10139be5 Mon Sep 17 00:00:00 2001 From: cvium Date: Tue, 4 May 2021 19:57:03 +0200 Subject: [PATCH 1554/1930] remove redundant code --- MediaBrowser.Common/Extensions/SplitStringExtensions.cs | 7 ------- .../Data/SqliteItemRepositoryTests.cs | 4 ++-- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/MediaBrowser.Common/Extensions/SplitStringExtensions.cs b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs index 6c1c45013d..e78fa78d6a 100644 --- a/MediaBrowser.Common/Extensions/SplitStringExtensions.cs +++ b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs @@ -86,13 +86,6 @@ namespace MediaBrowser.Common.Extensions return true; } - if (index < span.Length - 1 && span[index] == _separator) - { - Current = span.Slice(0, index); - _str = span[(index + 1)..]; - return true; - } - Current = span.Slice(0, index); _str = span[(index + 1)..]; return true; diff --git a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs index c0f34afa76..71f8c51818 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Data/SqliteItemRepositoryTests.cs @@ -96,7 +96,7 @@ namespace Jellyfin.Server.Implementations.Tests.Data [MemberData(nameof(ItemImageInfoFromValueString_Valid_TestData))] public void ItemImageInfoFromValueString_Valid_Success(string value, ItemImageInfo expected) { - var result = _sqliteItemRepository.ItemImageInfoFromValueString(value.AsSpan()); + var result = _sqliteItemRepository.ItemImageInfoFromValueString(value); Assert.Equal(expected.Path, result.Path); Assert.Equal(expected.Type, result.Type); Assert.Equal(expected.DateModified, result.DateModified); @@ -111,7 +111,7 @@ namespace Jellyfin.Server.Implementations.Tests.Data [InlineData("https://image.tmdb.org/t/p/original/zhB5CHEgqqh4wnEqDNJLfWXJlcL.jpg*0")] public void ItemImageInfoFromValueString_Invalid_Null(string value) { - Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value.AsSpan())); + Assert.Null(_sqliteItemRepository.ItemImageInfoFromValueString(value)); } public static IEnumerable DeserializeImages_Valid_TestData() From 244ad5b22577efa4dc737db549e62e422f42449e Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Tue, 4 May 2021 22:57:27 +0200 Subject: [PATCH 1555/1930] Apply review feedback --- MediaBrowser.Model/Dlna/DeviceProfile.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 6ec4cb547e..47d1016139 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -432,8 +432,8 @@ namespace MediaBrowser.Model.Dlna /// The . public ResponseProfile? GetVideoMediaProfile( string container, - string audioCodec, - string videoCodec, + string? audioCodec, + string? videoCodec, int? width, int? height, int? bitDepth, From b2bb062ced57870eb0a116a9518685a8bae48131 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Tue, 4 May 2021 23:38:17 +0200 Subject: [PATCH 1556/1930] Revert shortened 'is ... or' check --- MediaBrowser.Model/Dlna/DirectPlayProfile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs index 417d915b50..7b8cbe1818 100644 --- a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs +++ b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs @@ -32,7 +32,7 @@ namespace MediaBrowser.Model.Dlna public bool SupportsAudioCodec(string codec) { - return (Type is DlnaProfileType.Audio or DlnaProfileType.Video) && ContainerProfile.ContainsContainer(AudioCodec, codec); + return (Type == DlnaProfileType.Audio || Type == DlnaProfileType.Video) && ContainerProfile.ContainsContainer(AudioCodec, codec); } } } From 031a5c122d6e874fab5f8e4c3b27de5c03ac7217 Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Sat, 1 May 2021 00:43:43 +0200 Subject: [PATCH 1557/1930] Improve documentation for DeviceProfile --- MediaBrowser.Model/Dlna/DeviceProfile.cs | 41 +++++++++++++----------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 47d1016139..feb3d880ec 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -8,13 +8,18 @@ using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Model.Dlna { /// - /// Defines the . + /// A represents a set of metadata which determines which content a certain device is able to play. + ///
+ /// Specifically, it defines the supported containers and + /// codecs (video and/or audio, including codec profiles and levels) + /// the device is able to direct play (without transcoding or remuxing), + /// as well as which containers/codecs to transcode to in case it isn't. ///
[XmlRoot("Profile")] public class DeviceProfile { /// - /// Gets or sets the Name. + /// Gets or sets the name of this device profile. /// public string? Name { get; set; } @@ -30,32 +35,32 @@ namespace MediaBrowser.Model.Dlna public DeviceIdentification? Identification { get; set; } /// - /// Gets or sets the FriendlyName. + /// Gets or sets the friendly name of the device profile, which can be shown to users. /// public string? FriendlyName { get; set; } /// - /// Gets or sets the Manufacturer. + /// Gets or sets the manufacturer of the device which this profile represents. /// public string? Manufacturer { get; set; } /// - /// Gets or sets the ManufacturerUrl. + /// Gets or sets an url for the manufacturer of the device which this profile represents. /// public string? ManufacturerUrl { get; set; } /// - /// Gets or sets the ModelName. + /// Gets or sets the model name of the device which this profile represents. /// public string? ModelName { get; set; } /// - /// Gets or sets the ModelDescription. + /// Gets or sets the model description of the device which this profile represents. /// public string? ModelDescription { get; set; } /// - /// Gets or sets the ModelNumber. + /// Gets or sets the model number of the device which this profile represents. /// public string? ModelNumber { get; set; } @@ -65,7 +70,7 @@ namespace MediaBrowser.Model.Dlna public string? ModelUrl { get; set; } /// - /// Gets or sets the SerialNumber. + /// Gets or sets the serial number of the device which this profile represents. /// public string? SerialNumber { get; set; } @@ -113,32 +118,32 @@ namespace MediaBrowser.Model.Dlna public int? MaxAlbumArtHeight { get; set; } /// - /// Gets or sets the MaxIconWidth. + /// Gets or sets the maximum allowed width of embedded icons. /// public int? MaxIconWidth { get; set; } /// - /// Gets or sets the MaxIconHeight. + /// Gets or sets the maximum allowed height of embedded icons. /// public int? MaxIconHeight { get; set; } /// - /// Gets or sets the MaxStreamingBitrate. + /// Gets or sets the maximum allowed bitrate for all streamed content. /// public int? MaxStreamingBitrate { get; set; } = 8000000; /// - /// Gets or sets the MaxStaticBitrate. + /// Gets or sets the maximum allowed bitrate for statically streamed content (= direct played files). /// public int? MaxStaticBitrate { get; set; } = 8000000; /// - /// Gets or sets the MusicStreamingTranscodingBitrate. + /// Gets or sets the maximum allowed bitrate for transcoded music streams. /// public int? MusicStreamingTranscodingBitrate { get; set; } = 128000; /// - /// Gets or sets the MaxStaticMusicBitrate. + /// Gets or sets the maximum allowed bitrate for statically streamed (= direct played) music files. /// public int? MaxStaticMusicBitrate { get; set; } = 8000000; @@ -198,12 +203,12 @@ namespace MediaBrowser.Model.Dlna public TranscodingProfile[] TranscodingProfiles { get; set; } = Array.Empty(); /// - /// Gets or sets the ContainerProfiles. + /// Gets or sets the container profiles. /// public ContainerProfile[] ContainerProfiles { get; set; } = Array.Empty(); /// - /// Gets or sets the CodecProfiles. + /// Gets or sets the codec profiles. /// public CodecProfile[] CodecProfiles { get; set; } = Array.Empty(); @@ -213,7 +218,7 @@ namespace MediaBrowser.Model.Dlna public ResponseProfile[] ResponseProfiles { get; set; } = Array.Empty(); /// - /// Gets or sets the SubtitleProfiles. + /// Gets or sets the subtitle profiles. /// public SubtitleProfile[] SubtitleProfiles { get; set; } = Array.Empty(); From 31cf9f4b76a258babec0838a6e114979dd23b93c Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 4 May 2021 18:21:08 -0600 Subject: [PATCH 1558/1930] Remove legacy apiclient generation --- .ci/azure-pipelines-api-client.yml | 59 ------------------- .../Properties/launchSettings.json | 3 +- apiclient/.openapi-generator-ignore | 2 - .../templates/typescript/axios/generate.sh | 11 ---- .../typescript/axios/package.mustache | 30 ---------- 5 files changed, 2 insertions(+), 103 deletions(-) delete mode 100644 .ci/azure-pipelines-api-client.yml delete mode 100644 apiclient/.openapi-generator-ignore delete mode 100644 apiclient/templates/typescript/axios/generate.sh delete mode 100644 apiclient/templates/typescript/axios/package.mustache diff --git a/.ci/azure-pipelines-api-client.yml b/.ci/azure-pipelines-api-client.yml deleted file mode 100644 index 0e944e6f47..0000000000 --- a/.ci/azure-pipelines-api-client.yml +++ /dev/null @@ -1,59 +0,0 @@ -parameters: - - name: LinuxImage - type: string - default: "ubuntu-latest" - - name: GeneratorVersion - type: string - default: "5.0.1" - -jobs: -- job: GenerateApiClients - displayName: 'Generate Api Clients' - condition: startsWith(variables['Build.SourceBranch'], 'refs/tags/v') - dependsOn: Test - - pool: - vmImage: "${{ parameters.LinuxImage }}" - - steps: - - task: DownloadPipelineArtifact@2 - displayName: 'Download OpenAPI Spec Artifact' - inputs: - source: 'current' - artifact: "OpenAPI Spec" - path: "$(System.ArtifactsDirectory)/openapispec" - runVersion: "latest" - - - task: CmdLine@2 - displayName: 'Download OpenApi Generator' - inputs: - script: "wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/${{ parameters.GeneratorVersion }}/openapi-generator-cli-${{ parameters.GeneratorVersion }}.jar -O openapi-generator-cli.jar" - -## Authenticate with npm registry - - task: npmAuthenticate@0 - inputs: - workingFile: ./.npmrc - customEndpoint: 'jellyfin-bot for NPM' - -## Generate npm api client - - task: CmdLine@2 - displayName: 'Build stable typescript axios client' - inputs: - script: "bash ./apiclient/templates/typescript/axios/generate.sh $(System.ArtifactsDirectory)" - -## Run npm install - - task: Npm@1 - displayName: 'Install npm dependencies' - inputs: - command: install - workingDir: ./apiclient/generated/typescript/axios - -## Publish npm packages - - task: Npm@1 - displayName: 'Publish stable typescript axios client' - inputs: - command: custom - customCommand: publish --access public - publishRegistry: useExternalRegistry - publishEndpoint: 'jellyfin-bot for NPM' - workingDir: ./apiclient/generated/typescript/axios diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json index 20d432afc4..61a1723bd2 100644 --- a/Jellyfin.Server/Properties/launchSettings.json +++ b/Jellyfin.Server/Properties/launchSettings.json @@ -6,7 +6,8 @@ "applicationUrl": "http://localhost:8096", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - } + }, + "commandLineArgs": "--webdir C:\\Users\\Cody\\Code\\Jellyfin\\jellyfin-web\\dist" }, "Jellyfin.Server (nowebclient)": { "commandName": "Project", diff --git a/apiclient/.openapi-generator-ignore b/apiclient/.openapi-generator-ignore deleted file mode 100644 index f3802cf541..0000000000 --- a/apiclient/.openapi-generator-ignore +++ /dev/null @@ -1,2 +0,0 @@ -# Prevent generator from creating these files: -git_push.sh diff --git a/apiclient/templates/typescript/axios/generate.sh b/apiclient/templates/typescript/axios/generate.sh deleted file mode 100644 index 9599f85dbd..0000000000 --- a/apiclient/templates/typescript/axios/generate.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -artifactsDirectory="${1}" - -java -jar openapi-generator-cli.jar generate \ - --input-spec ${artifactsDirectory}/openapispec/openapi.json \ - --generator-name typescript-axios \ - --output ./apiclient/generated/typescript/axios \ - --template-dir ./apiclient/templates/typescript/axios \ - --ignore-file-override ./apiclient/.openapi-generator-ignore \ - --additional-properties=useSingleRequestParameter="true",withSeparateModelsAndApi="true",modelPackage="models",apiPackage="api",npmName="axios" diff --git a/apiclient/templates/typescript/axios/package.mustache b/apiclient/templates/typescript/axios/package.mustache deleted file mode 100644 index 7bfab08cbb..0000000000 --- a/apiclient/templates/typescript/axios/package.mustache +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "@jellyfin/client-axios", - "version": "10.7.0{{snapshotVersion}}", - "description": "Jellyfin api client using axios", - "author": "Jellyfin Contributors", - "keywords": [ - "axios", - "typescript", - "jellyfin" - ], - "license": "GPL-3.0-only", - "main": "./dist/index.js", - "typings": "./dist/index.d.ts", - "scripts": { - "build": "tsc --outDir dist/", - "prepublishOnly": "npm run build" - }, - "dependencies": { - "axios": "^0.19.2" - }, - "devDependencies": { - "@types/node": "^12.11.5", - "typescript": "^3.6.4" - }{{#npmRepository}},{{/npmRepository}} -{{#npmRepository}} - "publishConfig": { - "registry": "{{npmRepository}}" - } -{{/npmRepository}} -} From 1a178e84905c776766c49551f52dc163b93c81b0 Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 4 May 2021 19:11:01 -0600 Subject: [PATCH 1559/1930] Remove Required attributes --- MediaBrowser.Model/Dlna/ContainerProfile.cs | 2 -- MediaBrowser.Model/Dlna/DirectPlayProfile.cs | 1 - MediaBrowser.Model/Dlna/TranscodingProfile.cs | 5 ----- 3 files changed, 8 deletions(-) diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index 54d4f7f38a..c66ec8bc37 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -9,13 +9,11 @@ namespace MediaBrowser.Model.Dlna { public class ContainerProfile { - [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } public ProfileCondition[]? Conditions { get; set; } = Array.Empty(); - [Required] [XmlAttribute("container")] public string Container { get; set; } = string.Empty; diff --git a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs index 7b8cbe1818..fa3ad098f0 100644 --- a/MediaBrowser.Model/Dlna/DirectPlayProfile.cs +++ b/MediaBrowser.Model/Dlna/DirectPlayProfile.cs @@ -16,7 +16,6 @@ namespace MediaBrowser.Model.Dlna [XmlAttribute("videoCodec")] public string? VideoCodec { get; set; } - [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } diff --git a/MediaBrowser.Model/Dlna/TranscodingProfile.cs b/MediaBrowser.Model/Dlna/TranscodingProfile.cs index ea446b733f..214578a85e 100644 --- a/MediaBrowser.Model/Dlna/TranscodingProfile.cs +++ b/MediaBrowser.Model/Dlna/TranscodingProfile.cs @@ -8,23 +8,18 @@ namespace MediaBrowser.Model.Dlna { public class TranscodingProfile { - [Required] [XmlAttribute("container")] public string Container { get; set; } = string.Empty; - [Required] [XmlAttribute("type")] public DlnaProfileType Type { get; set; } - [Required] [XmlAttribute("videoCodec")] public string VideoCodec { get; set; } = string.Empty; - [Required] [XmlAttribute("audioCodec")] public string AudioCodec { get; set; } = string.Empty; - [Required] [XmlAttribute("protocol")] public string Protocol { get; set; } = string.Empty; From 08d07656237fd53668796e0d6a2d78bbba5f706f Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Tue, 4 May 2021 19:17:16 -0600 Subject: [PATCH 1560/1930] Restore launchSettings.json --- Jellyfin.Server/Properties/launchSettings.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Jellyfin.Server/Properties/launchSettings.json b/Jellyfin.Server/Properties/launchSettings.json index 61a1723bd2..20d432afc4 100644 --- a/Jellyfin.Server/Properties/launchSettings.json +++ b/Jellyfin.Server/Properties/launchSettings.json @@ -6,8 +6,7 @@ "applicationUrl": "http://localhost:8096", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" - }, - "commandLineArgs": "--webdir C:\\Users\\Cody\\Code\\Jellyfin\\jellyfin-web\\dist" + } }, "Jellyfin.Server (nowebclient)": { "commandName": "Project", From 08213f2368aed728e2e12e92e5d799952f7b412a Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 4 May 2021 19:30:51 -0600 Subject: [PATCH 1561/1930] Fully remove reference. --- .ci/azure-pipelines.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.ci/azure-pipelines.yml b/.ci/azure-pipelines.yml index 6430503f9a..c028b6e3e8 100644 --- a/.ci/azure-pipelines.yml +++ b/.ci/azure-pipelines.yml @@ -61,6 +61,3 @@ jobs: - ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}: - template: azure-pipelines-package.yml - -- ${{ if or(startsWith(variables['Build.SourceBranch'], 'refs/tags/v'), startsWith(variables['Build.SourceBranch'], 'refs/heads/master')) }}: - - template: azure-pipelines-api-client.yml From 260782349c7a800a576f0a7d3ff2b2ccc205013a Mon Sep 17 00:00:00 2001 From: Bill Thornton Date: Wed, 5 May 2021 00:58:12 -0400 Subject: [PATCH 1562/1930] Fix web build in dockerfiles --- Dockerfile | 6 +++--- Dockerfile.arm | 6 +++--- Dockerfile.arm64 | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Dockerfile b/Dockerfile index ebe5eb00c6..4e2d06b82a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ ARG DOTNET_VERSION=5.0 -FROM node:alpine as web-builder +FROM node:lts-alpine as web-builder ARG JELLYFIN_WEB_VERSION=master -RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ +RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm ci --no-audit \ + && npm ci --no-audit --unsafe-perm \ && mv dist /dist FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} as builder diff --git a/Dockerfile.arm b/Dockerfile.arm index d63dbee758..25a0de7db6 100644 --- a/Dockerfile.arm +++ b/Dockerfile.arm @@ -5,12 +5,12 @@ ARG DOTNET_VERSION=5.0 -FROM node:alpine as web-builder +FROM node:lts-alpine as web-builder ARG JELLYFIN_WEB_VERSION=master -RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ +RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm ci --no-audit \ + && npm ci --no-audit --unsafe-perm \ && mv dist /dist diff --git a/Dockerfile.arm64 b/Dockerfile.arm64 index e95999f2a6..c9f19c5a39 100644 --- a/Dockerfile.arm64 +++ b/Dockerfile.arm64 @@ -5,12 +5,12 @@ ARG DOTNET_VERSION=5.0 -FROM node:alpine as web-builder +FROM node:lts-alpine as web-builder ARG JELLYFIN_WEB_VERSION=master -RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python \ +RUN apk add curl git zlib zlib-dev autoconf g++ make libpng-dev gifsicle alpine-sdk automake libtool make gcc musl-dev nasm python3 \ && curl -L https://github.com/jellyfin/jellyfin-web/archive/${JELLYFIN_WEB_VERSION}.tar.gz | tar zxf - \ && cd jellyfin-web-* \ - && npm ci --no-audit \ + && npm ci --no-audit --unsafe-perm \ && mv dist /dist From e57b80b8e2c094c27eef835a335d4c7386bff968 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Wed, 5 May 2021 10:10:51 +0200 Subject: [PATCH 1563/1930] Add support for fanart aspect in thumb tag --- MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs | 1 + .../Parsers/MovieNfoParserTests.cs | 6 +++++- .../Test Data/Justice League.nfo | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs index 317dc0bf68..302c93f0bc 100644 --- a/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs +++ b/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs @@ -1333,6 +1333,7 @@ namespace MediaBrowser.XbmcMetadata.Parsers "discart" => ImageType.Disc, "landscape" => ImageType.Thumb, "clearart" => ImageType.Art, + "fanart" => ImageType.Backdrop, // unknown type (including "poster") --> primary _ => ImageType.Primary, }; diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs index b58151b3b4..30a48857a4 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs +++ b/tests/Jellyfin.XbmcMetadata.Tests/Parsers/MovieNfoParserTests.cs @@ -156,7 +156,7 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Equal("Justice League Collection", item.CollectionName); // Images - Assert.Equal(6, result.RemoteImages.Count); + Assert.Equal(7, result.RemoteImages.Count); var posters = result.RemoteImages.Where(x => x.type == ImageType.Primary).ToList(); Assert.Single(posters); @@ -182,6 +182,10 @@ namespace Jellyfin.XbmcMetadata.Tests.Parsers Assert.Single(discArt); Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a3af26360617.png", discArt[0].url); + var backdrop = result.RemoteImages.Where(x => x.type == ImageType.Backdrop).ToList(); + Assert.Single(backdrop); + Assert.Equal("https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg", backdrop[0].url); + // Local Image - contains only one item depending on operating system Assert.Single(result.Images); Assert.Equal(_localImageFileMetadata.Name, result.Images[0].FileInfo.Name); diff --git a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo index b0c5e3c572..4e8c79dcaa 100644 --- a/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo +++ b/tests/Jellyfin.XbmcMetadata.Tests/Test Data/Justice League.nfo @@ -82,8 +82,8 @@ https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a0b913c233be.png https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-5a87e0cdb1209.png https://assets.fanart.tv/fanart/movies/141052/moviedisc/justice-league-59dc595362ef1.png + https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg - https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5793f518c6d6e.jpg https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a5332c7b5e77.jpg https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5a53cf2dac1c8.jpg https://assets.fanart.tv/fanart/movies/141052/moviebackground/justice-league-5976ba93eb5d3.jpg From 65a9a4771afc5b6b7c956f7b799586400b23af8b Mon Sep 17 00:00:00 2001 From: Maxr1998 Date: Wed, 5 May 2021 12:25:54 +0200 Subject: [PATCH 1564/1930] Fix direct play for DirectPlayProfiles without any codecs set 70771fdcd60ec5d8a9f13713662778c7e57d0633 broke direct play by treating empty container/codec strings as unsupported in `ContainerProfile.ContainsContainer()`` (which is also used for video and audio codec checks). Instead, they should be treated as supported, for both the positive and negative list option. --- MediaBrowser.Model/Dlna/ContainerProfile.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index c66ec8bc37..b059e43f3d 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -55,7 +55,8 @@ namespace MediaBrowser.Model.Dlna { if (profileContainers == null || profileContainers.Length == 0) { - return isNegativeList; + // Empty profiles always support all containers/codecs + return true; } var allInputContainers = SplitValue(inputContainer); From 91c2a57b284011a21c926e9238dbc7edb5eaab13 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 12:57:01 +0200 Subject: [PATCH 1565/1930] Enable nullable reference types for MediaBrowser.Common --- Jellyfin.Api/Auth/BaseAuthorizationHandler.cs | 5 +++-- .../Controllers/ConfigurationController.cs | 6 ++++++ .../Configuration/ConfigurationStore.cs | 2 ++ .../ConfigurationUpdateEventArgs.cs | 1 + .../Configuration/IApplicationPaths.cs | 2 ++ .../Cryptography/PasswordHash.cs | 1 - MediaBrowser.Common/Events/EventHelper.cs | 4 ++-- .../Extensions/BaseExtensions.cs | 2 -- .../Extensions/CopyToExtensions.cs | 2 -- .../Extensions/HttpContextExtensions.cs | 2 +- .../Extensions/MethodNotAllowedException.cs | 2 -- .../Extensions/ProcessExtensions.cs | 2 -- .../Extensions/RateLimitExceededException.cs | 1 - .../Extensions/ResourceNotFoundException.cs | 2 -- .../Extensions/ShuffleExtensions.cs | 2 -- .../Extensions/SplitStringExtensions.cs | 2 +- .../Extensions/StreamExtensions.cs | 2 -- MediaBrowser.Common/IApplicationHost.cs | 2 ++ .../JsonCommaDelimitedArrayConverter.cs | 14 ++++++++++---- .../JsonCommaDelimitedArrayConverterFactory.cs | 4 ++-- .../JsonNullableStructConverterFactory.cs | 6 +++--- .../JsonOmdbNotAvailableStringConverter.cs | 18 ++++++++++++------ .../JsonPipeDelimitedArrayConverter.cs | 13 ++++++++++--- .../JsonPipeDelimitedArrayConverterFactory.cs | 4 ++-- .../Json/Converters/JsonStringConverter.cs | 8 ++++---- .../Json/Converters/JsonVersionConverter.cs | 2 +- MediaBrowser.Common/MediaBrowser.Common.csproj | 1 + MediaBrowser.Common/Net/INetworkManager.cs | 1 - MediaBrowser.Common/Net/IPHost.cs | 1 - MediaBrowser.Common/Net/IPNetAddress.cs | 1 - MediaBrowser.Common/Net/IPObject.cs | 1 - MediaBrowser.Common/Plugins/BasePlugin.cs | 2 ++ MediaBrowser.Common/Plugins/BasePluginOfT.cs | 2 ++ MediaBrowser.Common/Plugins/IPlugin.cs | 2 ++ MediaBrowser.Common/Plugins/IPluginManager.cs | 2 -- MediaBrowser.Common/Plugins/LocalPlugin.cs | 1 - MediaBrowser.Common/Plugins/PluginManifest.cs | 2 -- .../Progress/ActionableProgress.cs | 4 ++-- MediaBrowser.Common/Progress/SimpleProgress.cs | 2 +- .../Providers/ProviderIdParsers.cs | 4 +--- .../Updates/IInstallationManager.cs | 2 -- .../Updates/InstallationEventArgs.cs | 2 ++ .../Updates/InstallationFailedEventArgs.cs | 1 + 43 files changed, 78 insertions(+), 64 deletions(-) diff --git a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs index 7d68aecf99..392498c530 100644 --- a/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/BaseAuthorizationHandler.cs @@ -77,8 +77,9 @@ namespace Jellyfin.Api.Auth return false; } - var ip = _httpContextAccessor.HttpContext.GetNormalizedRemoteIp(); - var isInLocalNetwork = _networkManager.IsInLocalNetwork(ip); + var isInLocalNetwork = _httpContextAccessor.HttpContext != null + && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp()); + // User cannot access remotely and user is remote if (!user.HasPermission(PermissionKind.EnableRemoteAccess) && !isInLocalNetwork) { diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index 049a4bed7b..b6309baab0 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel.DataAnnotations; using System.Net.Mime; using System.Text.Json; @@ -94,6 +95,11 @@ namespace Jellyfin.Api.Controllers { var configurationType = _configurationManager.GetConfigurationType(key); var configuration = await JsonSerializer.DeserializeAsync(Request.Body, configurationType, _serializerOptions).ConfigureAwait(false); + if (configuration == null) + { + throw new ArgumentException("Body doesn't contain a valid configuration"); + } + _configurationManager.SaveConfiguration(key, configuration); return NoContent(); } diff --git a/MediaBrowser.Common/Configuration/ConfigurationStore.cs b/MediaBrowser.Common/Configuration/ConfigurationStore.cs index d31d45e4c3..050ab1ab51 100644 --- a/MediaBrowser.Common/Configuration/ConfigurationStore.cs +++ b/MediaBrowser.Common/Configuration/ConfigurationStore.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; namespace MediaBrowser.Common.Configuration diff --git a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs index 344aecf530..2df87d8792 100644 --- a/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs +++ b/MediaBrowser.Common/Configuration/ConfigurationUpdateEventArgs.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Common/Configuration/IApplicationPaths.cs b/MediaBrowser.Common/Configuration/IApplicationPaths.cs index 57c6546675..1370e6d79e 100644 --- a/MediaBrowser.Common/Configuration/IApplicationPaths.cs +++ b/MediaBrowser.Common/Configuration/IApplicationPaths.cs @@ -1,3 +1,5 @@ +#nullable disable + namespace MediaBrowser.Common.Configuration { /// diff --git a/MediaBrowser.Common/Cryptography/PasswordHash.cs b/MediaBrowser.Common/Cryptography/PasswordHash.cs index ec21d05803..0e20653029 100644 --- a/MediaBrowser.Common/Cryptography/PasswordHash.cs +++ b/MediaBrowser.Common/Cryptography/PasswordHash.cs @@ -1,5 +1,4 @@ #pragma warning disable CS1591 -#nullable enable using System; using System.Collections.Generic; diff --git a/MediaBrowser.Common/Events/EventHelper.cs b/MediaBrowser.Common/Events/EventHelper.cs index c9d3226ac8..a9cf86fbc3 100644 --- a/MediaBrowser.Common/Events/EventHelper.cs +++ b/MediaBrowser.Common/Events/EventHelper.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Common.Events /// The sender. /// The instance containing the event data. /// The logger. - public static void QueueEventIfNotNull(EventHandler handler, object sender, EventArgs args, ILogger logger) + public static void QueueEventIfNotNull(EventHandler? handler, object sender, EventArgs args, ILogger logger) { if (handler != null) { @@ -43,7 +43,7 @@ namespace MediaBrowser.Common.Events /// The sender. /// The args. /// The logger. - public static void QueueEventIfNotNull(EventHandler handler, object sender, T args, ILogger logger) + public static void QueueEventIfNotNull(EventHandler? handler, object sender, T args, ILogger logger) { if (handler != null) { diff --git a/MediaBrowser.Common/Extensions/BaseExtensions.cs b/MediaBrowser.Common/Extensions/BaseExtensions.cs index 40020093b6..08964420e7 100644 --- a/MediaBrowser.Common/Extensions/BaseExtensions.cs +++ b/MediaBrowser.Common/Extensions/BaseExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Security.Cryptography; using System.Text; diff --git a/MediaBrowser.Common/Extensions/CopyToExtensions.cs b/MediaBrowser.Common/Extensions/CopyToExtensions.cs index 94bf7c7401..2ecbc6539b 100644 --- a/MediaBrowser.Common/Extensions/CopyToExtensions.cs +++ b/MediaBrowser.Common/Extensions/CopyToExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Collections.Generic; namespace MediaBrowser.Common.Extensions diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs index e51ad42d12..1e5877c84c 100644 --- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs +++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs @@ -17,7 +17,7 @@ namespace MediaBrowser.Common.Extensions { return (context.Connection.LocalIpAddress == null && context.Connection.RemoteIpAddress == null) - || context.Connection.LocalIpAddress.Equals(context.Connection.RemoteIpAddress); + || Equals(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress); } /// diff --git a/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs index 258bd6662c..48e758ee4c 100644 --- a/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs +++ b/MediaBrowser.Common/Extensions/MethodNotAllowedException.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; namespace MediaBrowser.Common.Extensions diff --git a/MediaBrowser.Common/Extensions/ProcessExtensions.cs b/MediaBrowser.Common/Extensions/ProcessExtensions.cs index 2f52ba196a..c747871222 100644 --- a/MediaBrowser.Common/Extensions/ProcessExtensions.cs +++ b/MediaBrowser.Common/Extensions/ProcessExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Diagnostics; using System.Threading; diff --git a/MediaBrowser.Common/Extensions/RateLimitExceededException.cs b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs index 7c7bdaa92f..95802a4626 100644 --- a/MediaBrowser.Common/Extensions/RateLimitExceededException.cs +++ b/MediaBrowser.Common/Extensions/RateLimitExceededException.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs index ebac9d8e6b..22130c5a1e 100644 --- a/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs +++ b/MediaBrowser.Common/Extensions/ResourceNotFoundException.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; namespace MediaBrowser.Common.Extensions diff --git a/MediaBrowser.Common/Extensions/ShuffleExtensions.cs b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs index 6f0ea9bd58..2604abf85c 100644 --- a/MediaBrowser.Common/Extensions/ShuffleExtensions.cs +++ b/MediaBrowser.Common/Extensions/ShuffleExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; diff --git a/MediaBrowser.Common/Extensions/SplitStringExtensions.cs b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs index e78fa78d6a..9c9108495f 100644 --- a/MediaBrowser.Common/Extensions/SplitStringExtensions.cs +++ b/MediaBrowser.Common/Extensions/SplitStringExtensions.cs @@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#nullable enable + #pragma warning disable CS1591 #pragma warning disable CA1034 using System; diff --git a/MediaBrowser.Common/Extensions/StreamExtensions.cs b/MediaBrowser.Common/Extensions/StreamExtensions.cs index cd77be7b2b..08d81ffc32 100644 --- a/MediaBrowser.Common/Extensions/StreamExtensions.cs +++ b/MediaBrowser.Common/Extensions/StreamExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Collections.Generic; using System.IO; using System.Linq; diff --git a/MediaBrowser.Common/IApplicationHost.cs b/MediaBrowser.Common/IApplicationHost.cs index c3e4ed6db8..46d93e4940 100644 --- a/MediaBrowser.Common/IApplicationHost.cs +++ b/MediaBrowser.Common/IApplicationHost.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Reflection; diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index 2ec702165d..55c4665e83 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Common.Json.Converters /// Convert comma delimited string to array of type. /// /// Type to convert to. - public class JsonCommaDelimitedArrayConverter : JsonConverter + public class JsonCommaDelimitedArrayConverter : JsonConverter { private readonly TypeConverter _typeConverter; @@ -22,11 +22,17 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + if (reader.TokenType == JsonTokenType.String) { - var stringEntries = reader.GetString().Split(',', StringSplitOptions.RemoveEmptyEntries); + // GetString can't return null here because we already handled it above + var stringEntries = reader.GetString()!.Split(',', StringSplitOptions.RemoveEmptyEntries); if (stringEntries.Length == 0) { return Array.Empty(); @@ -67,7 +73,7 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, T[]? value, JsonSerializerOptions options) { throw new NotImplementedException(); } diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs index 24ed3ea19e..de41348dda 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverterFactory.cs @@ -19,10 +19,10 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0]; - return (JsonConverter)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType)); + return (JsonConverter?)Activator.CreateInstance(typeof(JsonCommaDelimitedArrayConverter<>).MakeGenericType(structType)); } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs index d5b54e3ca8..e2a3d798a2 100644 --- a/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs +++ b/MediaBrowser.Common/Json/Converters/JsonNullableStructConverterFactory.cs @@ -18,10 +18,10 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var structType = typeToConvert.GenericTypeArguments[0]; - return (JsonConverter)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType)); + return (JsonConverter?)Activator.CreateInstance(typeof(JsonNullableStructConverter<>).MakeGenericType(structType)); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs index 6a8790374b..77cf46b706 100644 --- a/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonOmdbNotAvailableStringConverter.cs @@ -7,15 +7,21 @@ namespace MediaBrowser.Common.Json.Converters /// /// Converts a string N/A to string.Empty. /// - public class JsonOmdbNotAvailableStringConverter : JsonConverter + public class JsonOmdbNotAvailableStringConverter : JsonConverter { /// - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + { + return null; + } + if (reader.TokenType == JsonTokenType.String) { - var str = reader.GetString(); - if (str != null && str.Equals("N/A", StringComparison.OrdinalIgnoreCase)) + // GetString can't return null here because we already handled it above + var str = reader.GetString()!; + if (str.Equals("N/A", StringComparison.OrdinalIgnoreCase)) { return null; } @@ -23,11 +29,11 @@ namespace MediaBrowser.Common.Json.Converters return str; } - return JsonSerializer.Deserialize(ref reader, options); + return JsonSerializer.Deserialize(ref reader, options); } /// - public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { writer.WriteStringValue(value); } diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs index c408a3be13..c83657b5f9 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -24,10 +24,16 @@ namespace MediaBrowser.Common.Json.Converters /// public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + { + return Array.Empty(); + } + if (reader.TokenType == JsonTokenType.String) { - var stringEntries = reader.GetString()?.Split('|', StringSplitOptions.RemoveEmptyEntries); - if (stringEntries == null || stringEntries.Length == 0) + // GetString can't return null here because we already handled it above + var stringEntries = reader.GetString()!.Split('|', StringSplitOptions.RemoveEmptyEntries); + if (stringEntries.Length == 0) { return Array.Empty(); } @@ -63,7 +69,8 @@ namespace MediaBrowser.Common.Json.Converters return typedValues; } - return JsonSerializer.Deserialize(ref reader, options); + // can't return null here because we already handled it above + return JsonSerializer.Deserialize(ref reader, options)!; } /// diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs index 5e77223ef2..1bebc49ecc 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverterFactory.cs @@ -19,10 +19,10 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var structType = typeToConvert.GetElementType() ?? typeToConvert.GenericTypeArguments[0]; - return (JsonConverter)Activator.CreateInstance(typeof(JsonPipeDelimitedArrayConverter<>).MakeGenericType(structType)); + return (JsonConverter?)Activator.CreateInstance(typeof(JsonPipeDelimitedArrayConverter<>).MakeGenericType(structType)); } } } diff --git a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs index 669b3cd077..6cd980e48a 100644 --- a/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonStringConverter.cs @@ -9,10 +9,10 @@ namespace MediaBrowser.Common.Json.Converters /// /// Converter to allow the serializer to read strings. /// - public class JsonStringConverter : JsonConverter + public class JsonStringConverter : JsonConverter { /// - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.TokenType switch { @@ -23,7 +23,7 @@ namespace MediaBrowser.Common.Json.Converters } /// - public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) { writer.WriteStringValue(value); } @@ -36,4 +36,4 @@ namespace MediaBrowser.Common.Json.Converters return Encoding.UTF8.GetString(utf8Bytes); } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs index f69e868cc4..81c093c541 100644 --- a/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonVersionConverter.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Common.Json.Converters { /// public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - => new Version(reader.GetString()); + => new Version(reader.GetString()!); // Will throw ArgumentNullException on null /// public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) diff --git a/MediaBrowser.Common/MediaBrowser.Common.csproj b/MediaBrowser.Common/MediaBrowser.Common.csproj index 0d9f78704e..0299a84563 100644 --- a/MediaBrowser.Common/MediaBrowser.Common.csproj +++ b/MediaBrowser.Common/MediaBrowser.Common.csproj @@ -33,6 +33,7 @@ false true true + enable AllEnabledByDefault ../jellyfin.ruleset true diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 185df5b773..b939397301 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,4 +1,3 @@ -#nullable enable using System; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index fb3ef9b12b..72197db078 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -1,4 +1,3 @@ -#nullable enable using System; using System.Diagnostics; using System.Linq; diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs index 589aad4b09..f6e3971bf3 100644 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ b/MediaBrowser.Common/Net/IPNetAddress.cs @@ -1,4 +1,3 @@ -#nullable enable using System; using System.Net; using System.Net.Sockets; diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index 3542dcd75e..2612268fd8 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -1,4 +1,3 @@ -#nullable enable using System; using System.Net; using System.Net.Sockets; diff --git a/MediaBrowser.Common/Plugins/BasePlugin.cs b/MediaBrowser.Common/Plugins/BasePlugin.cs index ad5a7338dd..8972089a8e 100644 --- a/MediaBrowser.Common/Plugins/BasePlugin.cs +++ b/MediaBrowser.Common/Plugins/BasePlugin.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.IO; using System.Reflection; diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index 99c226f509..361f4803bd 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -1,4 +1,6 @@ +#nullable disable #pragma warning disable SA1649 // File name should match first type name + using System; using System.IO; using System.Runtime.InteropServices; diff --git a/MediaBrowser.Common/Plugins/IPlugin.cs b/MediaBrowser.Common/Plugins/IPlugin.cs index b2ba1179c1..01e0a536da 100644 --- a/MediaBrowser.Common/Plugins/IPlugin.cs +++ b/MediaBrowser.Common/Plugins/IPlugin.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Model.Plugins; diff --git a/MediaBrowser.Common/Plugins/IPluginManager.cs b/MediaBrowser.Common/Plugins/IPluginManager.cs index 0e2e814cb0..176bcbbd54 100644 --- a/MediaBrowser.Common/Plugins/IPluginManager.cs +++ b/MediaBrowser.Common/Plugins/IPluginManager.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; using System.Reflection; diff --git a/MediaBrowser.Common/Plugins/LocalPlugin.cs b/MediaBrowser.Common/Plugins/LocalPlugin.cs index 12a1ad1ec8..4c8e2d5044 100644 --- a/MediaBrowser.Common/Plugins/LocalPlugin.cs +++ b/MediaBrowser.Common/Plugins/LocalPlugin.cs @@ -1,4 +1,3 @@ -#nullable enable using System; using System.Collections.Generic; using MediaBrowser.Model.Plugins; diff --git a/MediaBrowser.Common/Plugins/PluginManifest.cs b/MediaBrowser.Common/Plugins/PluginManifest.cs index 4c724f6949..2910dbe144 100644 --- a/MediaBrowser.Common/Plugins/PluginManifest.cs +++ b/MediaBrowser.Common/Plugins/PluginManifest.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Text.Json.Serialization; using MediaBrowser.Model.Plugins; diff --git a/MediaBrowser.Common/Progress/ActionableProgress.cs b/MediaBrowser.Common/Progress/ActionableProgress.cs index fe7cb10788..0ba46ea3ba 100644 --- a/MediaBrowser.Common/Progress/ActionableProgress.cs +++ b/MediaBrowser.Common/Progress/ActionableProgress.cs @@ -14,9 +14,9 @@ namespace MediaBrowser.Common.Progress /// /// The _actions. /// - private Action _action; + private Action? _action; - public event EventHandler ProgressChanged; + public event EventHandler? ProgressChanged; /// /// Registers the action. diff --git a/MediaBrowser.Common/Progress/SimpleProgress.cs b/MediaBrowser.Common/Progress/SimpleProgress.cs index 988d8ad34a..7071f2bc3d 100644 --- a/MediaBrowser.Common/Progress/SimpleProgress.cs +++ b/MediaBrowser.Common/Progress/SimpleProgress.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Common.Progress { public class SimpleProgress : IProgress { - public event EventHandler ProgressChanged; + public event EventHandler? ProgressChanged; public void Report(T value) { diff --git a/MediaBrowser.Common/Providers/ProviderIdParsers.cs b/MediaBrowser.Common/Providers/ProviderIdParsers.cs index 64c2e19766..33d09ed385 100644 --- a/MediaBrowser.Common/Providers/ProviderIdParsers.cs +++ b/MediaBrowser.Common/Providers/ProviderIdParsers.cs @@ -1,6 +1,4 @@ -#nullable enable - -using System; +using System; using System.Diagnostics.CodeAnalysis; namespace MediaBrowser.Common.Providers diff --git a/MediaBrowser.Common/Updates/IInstallationManager.cs b/MediaBrowser.Common/Updates/IInstallationManager.cs index 0844c2d792..c2a28e0a2c 100644 --- a/MediaBrowser.Common/Updates/IInstallationManager.cs +++ b/MediaBrowser.Common/Updates/IInstallationManager.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Common/Updates/InstallationEventArgs.cs b/MediaBrowser.Common/Updates/InstallationEventArgs.cs index adf336313f..f4f7599559 100644 --- a/MediaBrowser.Common/Updates/InstallationEventArgs.cs +++ b/MediaBrowser.Common/Updates/InstallationEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Model.Updates; diff --git a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs index 46f10c84fd..d37146195c 100644 --- a/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs +++ b/MediaBrowser.Common/Updates/InstallationFailedEventArgs.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; From 39931fe3ade3ad10e758b3dbb5acf80c37bc05fa Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 13:33:34 +0200 Subject: [PATCH 1566/1930] Add regression test for ContainerProfile.ContainsContainer --- MediaBrowser.Model/Dlna/ContainerProfile.cs | 1 - .../Dlna/ContainerProfileTests.cs | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs diff --git a/MediaBrowser.Model/Dlna/ContainerProfile.cs b/MediaBrowser.Model/Dlna/ContainerProfile.cs index c66ec8bc37..530ffed438 100644 --- a/MediaBrowser.Model/Dlna/ContainerProfile.cs +++ b/MediaBrowser.Model/Dlna/ContainerProfile.cs @@ -1,7 +1,6 @@ #pragma warning disable CS1591 using System; -using System.ComponentModel.DataAnnotations; using System.Linq; using System.Xml.Serialization; diff --git a/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs b/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs new file mode 100644 index 0000000000..cca056c280 --- /dev/null +++ b/tests/Jellyfin.Model.Tests/Dlna/ContainerProfileTests.cs @@ -0,0 +1,19 @@ +using MediaBrowser.Model.Dlna; +using Xunit; + +namespace Jellyfin.Model.Tests.Dlna +{ + public class ContainerProfileTests + { + private readonly ContainerProfile _emptyContainerProfile = new ContainerProfile(); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("mp4")] + public void ContainsContainer_EmptyContainerProfile_True(string? containers) + { + Assert.True(_emptyContainerProfile.ContainsContainer(containers)); + } + } +} From f2c10471bf00263adc6411b38db60ba931d0ec15 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 12:37:36 +0100 Subject: [PATCH 1567/1930] Code Clean up: Use Pattern Matching (#5838) Co-authored-by: Cody Robibero Co-authored-by: Patrick Barron <18354464+barronpm@users.noreply.github.com> --- .../Images/PlaylistImageProvider.cs | 4 +--- .../Library/MusicManager.cs | 3 +-- .../ScheduledTasks/ScheduledTaskWorker.cs | 4 +--- .../TV/TVSeriesManager.cs | 8 ++------ .../Entities/CollectionFolder.cs | 4 +--- .../Entities/Movies/BoxSet.cs | 3 +-- MediaBrowser.Controller/Entities/Photo.cs | 3 +-- MediaBrowser.Controller/Entities/TV/Series.cs | 11 ++--------- MediaBrowser.Controller/Providers/ItemInfo.cs | 3 +-- .../Parsers/BaseItemXmlParser.cs | 3 +-- .../Savers/BaseXmlSaver.cs | 6 ++---- .../BdInfo/BdInfoExaminer.cs | 16 ++++------------ .../Manager/MetadataService.cs | 6 ++---- .../MediaInfo/AudioImageProvider.cs | 4 +--- .../MediaInfo/SubtitleDownloader.cs | 4 +--- .../MediaInfo/VideoImageProvider.cs | 4 +--- 16 files changed, 23 insertions(+), 63 deletions(-) diff --git a/Emby.Server.Implementations/Images/PlaylistImageProvider.cs b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs index 0ce1b91e88..a4c106e879 100644 --- a/Emby.Server.Implementations/Images/PlaylistImageProvider.cs +++ b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs @@ -29,9 +29,7 @@ namespace Emby.Server.Implementations.Images { var subItem = i.Item2; - var episode = subItem as Episode; - - if (episode != null) + if (subItem is Episode episode) { var series = episode.Series; if (series != null && series.HasImage(ImageType.Primary)) diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs index 658c53f288..f8bae4fd1a 100644 --- a/Emby.Server.Implementations/Library/MusicManager.cs +++ b/Emby.Server.Implementations/Library/MusicManager.cs @@ -100,8 +100,7 @@ namespace Emby.Server.Implementations.Library public List GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions) { - var genre = item as MusicGenre; - if (genre != null) + if (item is MusicGenre genre) { return GetInstantMixFromGenreIds(new[] { item.Id }, user, dtoOptions); } diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 9c0e927058..61dccaa19f 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -348,9 +348,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { var trigger = (ITaskTrigger)sender; - var configurableTask = ScheduledTask as IConfigurableScheduledTask; - - if (configurableTask != null && !configurableTask.IsEnabled) + if (ScheduledTask is IConfigurableScheduledTask configurableTask && !configurableTask.IsEnabled) { return; } diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index d3f6fa34d8..829df64bfb 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -43,9 +43,7 @@ namespace Emby.Server.Implementations.TV string presentationUniqueKey = null; if (!string.IsNullOrEmpty(request.SeriesId)) { - var series = _libraryManager.GetItemById(request.SeriesId) as Series; - - if (series != null) + if (_libraryManager.GetItemById(request.SeriesId) is Series series) { presentationUniqueKey = GetUniqueSeriesKey(series); } @@ -95,9 +93,7 @@ namespace Emby.Server.Implementations.TV int? limit = null; if (!string.IsNullOrEmpty(request.SeriesId)) { - var series = _libraryManager.GetItemById(request.SeriesId) as Series; - - if (series != null) + if (_libraryManager.GetItemById(request.SeriesId) is Series series) { presentationUniqueKey = GetUniqueSeriesKey(series); limit = 1; diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 16a2c77e92..347d5b73c7 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -354,9 +354,7 @@ namespace MediaBrowser.Controller.Entities if (result.Count == 0) { - var folder = LibraryManager.FindByPath(path, true) as Folder; - - if (folder != null) + if (LibraryManager.FindByPath(path, true) is Folder folder) { result.Add(folder); } diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 05e4229cad..507f400f12 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -217,8 +217,7 @@ namespace MediaBrowser.Controller.Entities.Movies private IEnumerable FlattenItems(BaseItem item, List expandedFolders) { - var boxset = item as BoxSet; - if (boxset != null) + if (item is BoxSet boxset) { if (!expandedFolders.Contains(item.Id)) { diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs index 2fc66176f6..0f82f742fd 100644 --- a/MediaBrowser.Controller/Entities/Photo.cs +++ b/MediaBrowser.Controller/Entities/Photo.cs @@ -24,8 +24,7 @@ namespace MediaBrowser.Controller.Entities var parents = GetParents(); foreach (var parent in parents) { - var photoAlbum = parent as PhotoAlbum; - if (photoAlbum != null) + if (parent is PhotoAlbum photoAlbum) { return photoAlbum; } diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 9f9a2ad50f..06a405121c 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -316,20 +316,13 @@ namespace MediaBrowser.Controller.Entities.TV cancellationToken.ThrowIfCancellationRequested(); - var skipItem = false; - - var episode = item as Episode; - - if (episode != null + bool skipItem = item is Episode episode && refreshOptions.MetadataRefreshMode != MetadataRefreshMode.FullRefresh && !refreshOptions.ReplaceAllMetadata && episode.IsMissingEpisode && episode.LocationType == LocationType.Virtual && episode.PremiereDate.HasValue - && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30) - { - skipItem = true; - } + && (DateTime.UtcNow - episode.PremiereDate.Value).TotalDays > 30; if (!skipItem) { diff --git a/MediaBrowser.Controller/Providers/ItemInfo.cs b/MediaBrowser.Controller/Providers/ItemInfo.cs index b50def043f..3a97127eaa 100644 --- a/MediaBrowser.Controller/Providers/ItemInfo.cs +++ b/MediaBrowser.Controller/Providers/ItemInfo.cs @@ -14,8 +14,7 @@ namespace MediaBrowser.Controller.Providers ContainingFolderPath = item.ContainingFolderPath; IsInMixedFolder = item.IsInMixedFolder; - var video = item as Video; - if (video != null) + if (item is Video video) { VideoType = video.VideoType; IsPlaceHolder = video.IsPlaceHolder; diff --git a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs index 5f620634fb..32e5ac7615 100644 --- a/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs +++ b/MediaBrowser.LocalMetadata/Parsers/BaseItemXmlParser.cs @@ -468,8 +468,7 @@ namespace MediaBrowser.LocalMetadata.Parsers { var val = reader.ReadElementContentAsString(); - var hasDisplayOrder = item as IHasDisplayOrder; - if (hasDisplayOrder != null) + if (item is IHasDisplayOrder hasDisplayOrder) { if (!string.IsNullOrWhiteSpace(val)) { diff --git a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs index dfbce5f49a..98ed3dcf7d 100644 --- a/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs +++ b/MediaBrowser.LocalMetadata/Savers/BaseXmlSaver.cs @@ -296,8 +296,7 @@ namespace MediaBrowser.LocalMetadata.Savers writer.WriteEndElement(); } - var hasDisplayOrder = item as IHasDisplayOrder; - if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder)) + if (item is IHasDisplayOrder hasDisplayOrder && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder)) { writer.WriteElementString("DisplayOrder", hasDisplayOrder.DisplayOrder); } @@ -312,8 +311,7 @@ namespace MediaBrowser.LocalMetadata.Savers writer.WriteElementString("ProductionYear", item.ProductionYear.Value.ToString(_usCulture)); } - var hasAspectRatio = item as IHasAspectRatio; - if (hasAspectRatio != null) + if (item is IHasAspectRatio hasAspectRatio) { if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio)) { diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs index 9108d96497..6ebaa4fff0 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs @@ -61,33 +61,25 @@ namespace MediaBrowser.MediaEncoding.BdInfo foreach (var stream in playlist.SortedStreams) { - var videoStream = stream as TSVideoStream; - - if (videoStream != null) + if (stream is TSVideoStream videoStream) { AddVideoStream(mediaStreams, videoStream); continue; } - var audioStream = stream as TSAudioStream; - - if (audioStream != null) + if (stream is TSAudioStream audioStream) { AddAudioStream(mediaStreams, audioStream); continue; } - var textStream = stream as TSTextStream; - - if (textStream != null) + if (stream is TSTextStream textStream) { AddSubtitleStream(mediaStreams, textStream); continue; } - var graphicsStream = stream as TSGraphicsStream; - - if (graphicsStream != null) + if (stream is TSGraphicsStream graphicsStream) { AddSubtitleStream(mediaStreams, graphicsStream); } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 6b778a090b..401c7e99f2 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -281,8 +281,7 @@ namespace MediaBrowser.Providers.Manager return true; } - var folder = item as Folder; - if (folder != null) + if (item is Folder folder) { return folder.SupportsDateLastMediaAdded || folder.SupportsCumulativeRunTimeTicks; } @@ -336,8 +335,7 @@ namespace MediaBrowser.Providers.Manager private ItemUpdateType UpdateCumulativeRunTimeTicks(TItemType item, IList children) { - var folder = item as Folder; - if (folder != null && folder.SupportsCumulativeRunTimeTicks) + if (item is Folder folder && folder.SupportsCumulativeRunTimeTicks) { long ticks = 0; diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs index 64ad1bddfe..03e45fb869 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs @@ -137,9 +137,7 @@ namespace MediaBrowser.Providers.MediaInfo return false; } - var audio = item as Audio; - - return audio != null; + return item is Audio; } } } diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs index 912aedb0db..44ab5aa5b9 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs @@ -172,9 +172,7 @@ namespace MediaBrowser.Providers.MediaInfo SubtitleFetcherOrder = subtitleFetcherOrder }; - var episode = video as Episode; - - if (episode != null) + if (video is Episode episode) { request.IndexNumberEnd = episode.IndexNumberEnd; request.SeriesName = episode.SeriesName; diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index c36c3af6a7..30af6710ab 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -154,9 +154,7 @@ namespace MediaBrowser.Providers.MediaInfo return false; } - var video = item as Video; - - if (video != null && !video.IsPlaceHolder && video.IsCompleteMedia) + if (item is Video video && !video.IsPlaceHolder && video.IsCompleteMedia) { return true; } From 2e98de90628e9a4e42fb182f2d5a2a296acfd827 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 12:51:14 +0100 Subject: [PATCH 1568/1930] Code Clean up: Convert to null-coalescing operator ?? (#5845) Co-authored-by: Cody Robibero Co-authored-by: Patrick Barron <18354464+barronpm@users.noreply.github.com> --- .../ApplicationHost.cs | 10 +---- Emby.Server.Implementations/Dto/DtoService.cs | 15 ++----- .../Library/LibraryManager.cs | 5 +-- .../Library/Resolvers/TV/EpisodeResolver.cs | 14 ++---- .../LiveTv/EmbyTV/EmbyTV.cs | 10 ++--- .../LiveTv/Listings/SchedulesDirect.cs | 7 +-- .../LiveTv/LiveTvManager.cs | 15 ++----- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 5 +-- .../Plugins/PluginManager.cs | 13 +----- .../ScheduledTasks/ScheduledTaskWorker.cs | 7 +-- .../Session/SessionManager.cs | 5 +-- Jellyfin.Api/Controllers/PluginsController.cs | 7 +-- Jellyfin.Api/Controllers/SearchController.cs | 5 +-- Jellyfin.Api/Helpers/StreamingHelpers.cs | 5 +-- MediaBrowser.Common/Net/IPHost.cs | 5 +-- MediaBrowser.Common/Plugins/BasePluginOfT.cs | 5 +-- MediaBrowser.Controller/Entities/BaseItem.cs | 26 ++++------- MediaBrowser.Controller/Entities/UserView.cs | 5 +-- .../Library/ItemResolveArgs.cs | 5 +-- MediaBrowser.Controller/Playlists/Playlist.cs | 5 +-- .../Providers/MetadataRefreshOptions.cs | 5 +-- .../Providers/MetadataResult.cs | 16 +++---- .../Probing/ProbeResultNormalizer.cs | 45 +++++-------------- .../Entities/ProviderIdsExtensions.cs | 5 +-- .../MediaInfo/FFProbeVideoInfo.cs | 5 +-- .../Subtitles/SubtitleManager.cs | 5 +-- RSSDP/SsdpCommunicationsServer.cs | 5 +-- 27 files changed, 60 insertions(+), 200 deletions(-) diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 703f8d20da..75d8fc113d 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -335,10 +335,7 @@ namespace Emby.Server.Implementations { get { - if (_deviceId == null) - { - _deviceId = new DeviceId(ApplicationPaths, LoggerFactory); - } + _deviceId ??= new DeviceId(ApplicationPaths, LoggerFactory); return _deviceId.Value; } @@ -370,10 +367,7 @@ namespace Emby.Server.Implementations /// System.Object. protected object CreateInstanceSafe(Type type) { - if (_creatingInstances == null) - { - _creatingInstances = new List(); - } + _creatingInstances ??= new List(); if (_creatingInstances.IndexOf(type) != -1) { diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 54b18a8c80..4ae35039ab 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -665,10 +665,7 @@ namespace Emby.Server.Implementations.Dto var tag = GetImageCacheTag(item, image); if (!string.IsNullOrEmpty(image.BlurHash)) { - if (dto.ImageBlurHashes == null) - { - dto.ImageBlurHashes = new Dictionary>(); - } + dto.ImageBlurHashes ??= new Dictionary>(); if (!dto.ImageBlurHashes.ContainsKey(image.Type)) { @@ -702,10 +699,7 @@ namespace Emby.Server.Implementations.Dto if (hashes.Count > 0) { - if (dto.ImageBlurHashes == null) - { - dto.ImageBlurHashes = new Dictionary>(); - } + dto.ImageBlurHashes ??= new Dictionary>(); dto.ImageBlurHashes[imageType] = hashes; } @@ -898,10 +892,7 @@ namespace Emby.Server.Implementations.Dto dto.Taglines = new string[] { item.Tagline }; } - if (dto.Taglines == null) - { - dto.Taglines = Array.Empty(); - } + dto.Taglines ??= Array.Empty(); } dto.Type = item.GetBaseItemKind(); diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index a44edad161..4d207471a2 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -176,10 +176,7 @@ namespace Emby.Server.Implementations.Library { lock (_rootFolderSyncLock) { - if (_rootFolder == null) - { - _rootFolder = CreateRootFolder(); - } + _rootFolder ??= CreateRootFolder(); } } diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index 9b4cd7a3df..6f29bc6494 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -35,14 +35,10 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - var season = parent as Season; - // Just in case the user decided to nest episodes. // Not officially supported but in some cases we can handle it. - if (season == null) - { - season = parent.GetParents().OfType().FirstOrDefault(); - } + + var season = parent as Season ?? parent.GetParents().OfType().FirstOrDefault(); // If the parent is a Season or Series and the parent is not an extras folder, then this is an Episode if the VideoResolver returns something // Also handle flat tv folders @@ -55,11 +51,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV if (episode != null) { - var series = parent as Series; - if (series == null) - { - series = parent.GetParents().OfType().FirstOrDefault(); - } + var series = parent as Series ?? parent.GetParents().OfType().FirstOrDefault(); if (series != null) { diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 665fbfa0fe..28a2095e16 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -2237,14 +2237,10 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV var enabledTimersForSeries = new List(); foreach (var timer in allTimers) { - var existingTimer = _timerProvider.GetTimer(timer.Id); - - if (existingTimer == null) - { - existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId) + var existingTimer = _timerProvider.GetTimer(timer.Id) + ?? (string.IsNullOrWhiteSpace(timer.ProgramId) ? null - : _timerProvider.GetTimerByProgramId(timer.ProgramId); - } + : _timerProvider.GetTimerByProgramId(timer.ProgramId)); if (existingTimer == null) { diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 1926e738f2..9af65cabba 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -787,14 +787,11 @@ namespace Emby.Server.Implementations.LiveTv.Listings { var channelNumber = GetChannelNumber(channel); - var station = allStations.Find(item => string.Equals(item.stationID, channel.stationID, StringComparison.OrdinalIgnoreCase)); - if (station == null) - { - station = new ScheduleDirect.Station + var station = allStations.Find(item => string.Equals(item.stationID, channel.stationID, StringComparison.OrdinalIgnoreCase)) + ?? new ScheduleDirect.Station { stationID = channel.stationID }; - } var channelInfo = new ChannelInfo { diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 63a3146aa9..1145d8aa1e 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -987,10 +987,7 @@ namespace Emby.Server.Implementations.LiveTv var externalProgramId = programTuple.Item2; string externalSeriesId = programTuple.Item3; - if (timerList == null) - { - timerList = (await GetTimersInternal(new TimerQuery(), cancellationToken).ConfigureAwait(false)).Items; - } + timerList ??= (await GetTimersInternal(new TimerQuery(), cancellationToken).ConfigureAwait(false)).Items; var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase)); var foundSeriesTimer = false; @@ -1018,10 +1015,7 @@ namespace Emby.Server.Implementations.LiveTv continue; } - if (seriesTimerList == null) - { - seriesTimerList = (await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false)).Items; - } + seriesTimerList ??= (await GetSeriesTimersInternal(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false)).Items; var seriesTimer = seriesTimerList.FirstOrDefault(i => string.Equals(i.SeriesId, externalSeriesId, StringComparison.OrdinalIgnoreCase)); @@ -1974,10 +1968,7 @@ namespace Emby.Server.Implementations.LiveTv }; } - if (service == null) - { - service = _services[0]; - } + service ??= _services[0]; var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index c32ca2fb69..4aa5832b18 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -421,10 +421,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun string audioCodec = channelInfo.AudioCodec; - if (!videoBitrate.HasValue) - { - videoBitrate = isHd ? 15000000 : 2000000; - } + videoBitrate ??= isHd ? 15000000 : 2000000; int? audioBitrate = isHd ? 448000 : 192000; diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index fd2ee6b7a7..14df20936c 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -44,12 +44,7 @@ namespace Emby.Server.Implementations.Plugins { get { - if (_httpClientFactory == null) - { - _httpClientFactory = _appHost.Resolve(); - } - - return _httpClientFactory; + return _httpClientFactory ?? (_httpClientFactory = _appHost.Resolve()); } } @@ -276,11 +271,7 @@ namespace Emby.Server.Implementations.Plugins // If no version is given, return the current instance. var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList(); - plugin = plugins.FirstOrDefault(p => p.Instance != null); - if (plugin == null) - { - plugin = plugins.OrderByDescending(p => p.Version).FirstOrDefault(); - } + plugin = plugins.FirstOrDefault(p => p.Instance != null) ?? plugins.OrderByDescending(p => p.Version).FirstOrDefault(); } else { diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 61dccaa19f..101d9b5377 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -301,12 +301,7 @@ namespace Emby.Server.Implementations.ScheduledTasks { get { - if (_id == null) - { - _id = ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture); - } - - return _id; + return _id ??= ScheduledTask.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture); } } diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 6f21ec31e5..6844152ea5 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1475,10 +1475,7 @@ namespace Emby.Server.Implementations.Session user = _userManager.GetUserById(request.UserId); } - if (user == null) - { - user = _userManager.GetUserByName(request.Username); - } + user ??= _userManager.GetUserByName(request.Username); if (enforcePassword) { diff --git a/Jellyfin.Api/Controllers/PluginsController.cs b/Jellyfin.Api/Controllers/PluginsController.cs index adec86a102..7a61307195 100644 --- a/Jellyfin.Api/Controllers/PluginsController.cs +++ b/Jellyfin.Api/Controllers/PluginsController.cs @@ -207,12 +207,7 @@ namespace Jellyfin.Api.Controllers var plugins = _pluginManager.Plugins.Where(p => p.Id.Equals(pluginId)); // Select the un-instanced one first. - var plugin = plugins.FirstOrDefault(p => p.Instance == null); - if (plugin == null) - { - // Then by the status. - plugin = plugins.OrderBy(p => p.Manifest.Status).FirstOrDefault(); - } + var plugin = plugins.FirstOrDefault(p => p.Instance == null) ?? plugins.OrderBy(p => p.Manifest.Status).FirstOrDefault(); if (plugin != null) { diff --git a/Jellyfin.Api/Controllers/SearchController.cs b/Jellyfin.Api/Controllers/SearchController.cs index 6c22050a79..73bdf90182 100644 --- a/Jellyfin.Api/Controllers/SearchController.cs +++ b/Jellyfin.Api/Controllers/SearchController.cs @@ -228,10 +228,7 @@ namespace Jellyfin.Api.Controllers itemWithImage = GetParentWithImage(item, ImageType.Thumb); } - if (itemWithImage == null) - { - itemWithImage = GetParentWithImage(item, ImageType.Thumb); - } + itemWithImage ??= GetParentWithImage(item, ImageType.Thumb); if (itemWithImage != null) { diff --git a/Jellyfin.Api/Helpers/StreamingHelpers.cs b/Jellyfin.Api/Helpers/StreamingHelpers.cs index 583e613b4c..8cffe9c4c9 100644 --- a/Jellyfin.Api/Helpers/StreamingHelpers.cs +++ b/Jellyfin.Api/Helpers/StreamingHelpers.cs @@ -292,10 +292,7 @@ namespace Jellyfin.Api.Helpers } } - if (profile == null) - { - profile = dlnaManager.GetDefaultProfile(); - } + profile ??= dlnaManager.GetDefaultProfile(); var audioCodec = state.ActualOutputAudioCodec; diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index fb3ef9b12b..7156ce6188 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -400,10 +400,7 @@ namespace MediaBrowser.Common.Net private bool ResolveHost() { // When was the last time we resolved? - if (_lastResolved == null) - { - _lastResolved = DateTime.UtcNow; - } + _lastResolved ??= DateTime.UtcNow; // If we haven't resolved before, or our timer has run out... if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout))) diff --git a/MediaBrowser.Common/Plugins/BasePluginOfT.cs b/MediaBrowser.Common/Plugins/BasePluginOfT.cs index 99c226f509..e074cc6a01 100644 --- a/MediaBrowser.Common/Plugins/BasePluginOfT.cs +++ b/MediaBrowser.Common/Plugins/BasePluginOfT.cs @@ -105,10 +105,7 @@ namespace MediaBrowser.Common.Plugins { lock (_configurationSyncLock) { - if (_configuration == null) - { - _configuration = LoadConfiguration(); - } + _configuration ??= LoadConfiguration(); } } diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 1b69c66469..32ae154983 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -106,15 +106,10 @@ namespace MediaBrowser.Controller.Entities { get { - if (_themeSongIds == null) - { - _themeSongIds = GetExtras() - .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeSong) - .Select(song => song.Id) - .ToArray(); - } - - return _themeSongIds; + return _themeSongIds ??= GetExtras() + .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeSong) + .Select(song => song.Id) + .ToArray(); } private set @@ -128,15 +123,10 @@ namespace MediaBrowser.Controller.Entities { get { - if (_themeVideoIds == null) - { - _themeVideoIds = GetExtras() - .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeVideo) - .Select(song => song.Id) - .ToArray(); - } - - return _themeVideoIds; + return _themeVideoIds ??= GetExtras() + .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeVideo) + .Select(song => song.Id) + .ToArray(); } private set diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index b1da4d64cb..fec83dd941 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -75,10 +75,7 @@ namespace MediaBrowser.Controller.Entities public override List GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query) { - if (query == null) - { - query = new InternalItemsQuery(user); - } + query ??= new InternalItemsQuery(user); query.EnableTotalRecordCount = false; var result = GetItemList(query); diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index f86f7df25e..f9086066d7 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -147,10 +147,7 @@ namespace MediaBrowser.Controller.Library throw new ArgumentException("The path was empty or null.", nameof(path)); } - if (AdditionalLocations == null) - { - AdditionalLocations = new List(); - } + AdditionalLocations ??= new List(); AdditionalLocations.Add(path); } diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index c9c168c4c6..3c93cfc79c 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -126,10 +126,7 @@ namespace MediaBrowser.Controller.Playlists private List GetPlayableItems(User user, InternalItemsQuery query) { - if (query == null) - { - query = new InternalItemsQuery(user); - } + query ??= new InternalItemsQuery(user); query.IsFolder = false; diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index b92b837012..db0ef70728 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -45,10 +45,7 @@ namespace MediaBrowser.Controller.Providers if (copy.RefreshPaths != null && copy.RefreshPaths.Length > 0) { - if (RefreshPaths == null) - { - RefreshPaths = Array.Empty(); - } + RefreshPaths ??= Array.Empty(); RefreshPaths = copy.RefreshPaths.ToArray(); } diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs index 864cb30506..98c7eadfe0 100644 --- a/MediaBrowser.Controller/Providers/MetadataResult.cs +++ b/MediaBrowser.Controller/Providers/MetadataResult.cs @@ -37,10 +37,7 @@ namespace MediaBrowser.Controller.Providers public void AddPerson(PersonInfo p) { - if (People == null) - { - People = new List(); - } + People ??= new List(); PeopleHelper.AddPerson(People, p); } @@ -54,16 +51,15 @@ namespace MediaBrowser.Controller.Providers { People = new List(); } - - People.Clear(); + else + { + People.Clear(); + } } public UserItemData GetOrAddUserData(string userId) { - if (UserDataList == null) - { - UserDataList = new List(); - } + UserDataList ??= new List(); UserItemData userData = null; diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index ee2e5fcdee..2e96f8cb0f 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1187,43 +1187,28 @@ namespace MediaBrowser.MediaEncoding.Probing FetchStudios(audio, tags, "label"); // These support mulitple values, but for now we only store the first. - var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id")); - if (mb == null) - { - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID")); - } + var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id")) + ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID")); audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb); - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id")); - if (mb == null) - { - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID")); - } + mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id")) + ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID")); audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb); - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id")); - if (mb == null) - { - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID")); - } + mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id")) + ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID")); audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb); - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id")); - if (mb == null) - { - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID")); - } + mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id")) + ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID")); audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb); - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id")); - if (mb == null) - { - mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID")); - } + mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id")) + ?? GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID")); audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb); } @@ -1290,15 +1275,7 @@ namespace MediaBrowser.MediaEncoding.Probing private IEnumerable GetSplitWhitelist() { - if (_splitWhiteList == null) - { - _splitWhiteList = new List - { - "AC/DC" - }; - } - - return _splitWhiteList; + return _splitWhiteList ??= new List { "AC/DC" }; } /// diff --git a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs index 09d14dc6a4..ce4b0ec92e 100644 --- a/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs +++ b/MediaBrowser.Model/Entities/ProviderIdsExtensions.cs @@ -123,10 +123,7 @@ namespace MediaBrowser.Model.Entities else { // Ensure it exists - if (instance.ProviderIds == null) - { - instance.ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } + instance.ProviderIds ??= new Dictionary(StringComparer.OrdinalIgnoreCase); instance.ProviderIds[name] = value; } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 74849a5221..f049cc81ff 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -111,10 +111,7 @@ namespace MediaBrowser.Providers.MediaInfo } } - if (streamFileNames == null) - { - streamFileNames = Array.Empty(); - } + streamFileNames ??= Array.Empty(); mediaInfoResult = await GetMediaInfo(item, cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 1f3d9acff2..8d62343cb1 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -256,10 +256,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - if (exceptionToThrow == null) - { - exceptionToThrow = ex; - } + exceptionToThrow ??= ex; } finally { diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 8f1f0fa613..f448ad38bb 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -415,10 +415,7 @@ namespace Rssdp.Infrastructure { lock (_SendSocketSynchroniser) { - if (_sendSockets == null) - { - _sendSockets = CreateSocketAndListenForResponsesAsync(); - } + _sendSockets ??= CreateSocketAndListenForResponsesAsync(); } } } From e432796f6f0f500830b1c90c233c4e4c07287190 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 14:39:50 +0200 Subject: [PATCH 1569/1930] Minor improvements --- .../Probing/ProbeResultNormalizer.cs | 11 ++++------- MediaBrowser.Providers/Subtitles/SubtitleManager.cs | 12 ++++++------ 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 2e96f8cb0f..884ec0a293 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -29,7 +29,7 @@ namespace MediaBrowser.MediaEncoding.Probing private readonly ILogger _logger; private readonly ILocalizationManager _localization; - private List _splitWhiteList = null; + private string[] _splitWhiteList; public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization) { @@ -37,6 +37,8 @@ namespace MediaBrowser.MediaEncoding.Probing _localization = localization; } + private IReadOnlyList SplitWhitelist => _splitWhiteList ??= new string[] { "AC/DC" }; + public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, MediaProtocol protocol) { var info = new MediaInfo @@ -1254,7 +1256,7 @@ namespace MediaBrowser.MediaEncoding.Probing var artistsFound = new List(); - foreach (var whitelistArtist in GetSplitWhitelist()) + foreach (var whitelistArtist in SplitWhitelist) { var originalVal = val; val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase); @@ -1273,11 +1275,6 @@ namespace MediaBrowser.MediaEncoding.Probing return artistsFound; } - private IEnumerable GetSplitWhitelist() - { - return _splitWhiteList ??= new List { "AC/DC" }; - } - /// /// Gets the studios from the tags collection. /// diff --git a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs index 8d62343cb1..bf0c853ae9 100644 --- a/MediaBrowser.Providers/Subtitles/SubtitleManager.cs +++ b/MediaBrowser.Providers/Subtitles/SubtitleManager.cs @@ -207,7 +207,7 @@ namespace MediaBrowser.Providers.Subtitles { var mediaFolderPath = Path.GetFullPath(Path.Combine(video.ContainingFolderPath, saveFileName)); // TODO: Add some error handling to the API user: return BadRequest("Could not save subtitle, bad path."); - if (mediaFolderPath.StartsWith(video.ContainingFolderPath)) + if (mediaFolderPath.StartsWith(video.ContainingFolderPath, StringComparison.Ordinal)) { savePaths.Add(mediaFolderPath); } @@ -216,7 +216,7 @@ namespace MediaBrowser.Providers.Subtitles var internalPath = Path.GetFullPath(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); // TODO: Add some error to the user: return BadRequest("Could not save subtitle, bad path."); - if (internalPath.StartsWith(video.GetInternalMetadataPath())) + if (internalPath.StartsWith(video.GetInternalMetadataPath(), StringComparison.Ordinal)) { savePaths.Add(internalPath); } @@ -234,7 +234,7 @@ namespace MediaBrowser.Providers.Subtitles private async Task TrySaveToFiles(Stream stream, List savePaths) { - Exception exceptionToThrow = null; + List exs = null; foreach (var savePath in savePaths) { @@ -256,7 +256,7 @@ namespace MediaBrowser.Providers.Subtitles } catch (Exception ex) { - exceptionToThrow ??= ex; + (exs ??= new List()).Add(ex); } finally { @@ -266,9 +266,9 @@ namespace MediaBrowser.Providers.Subtitles stream.Position = 0; } - if (exceptionToThrow != null) + if (exs != null) { - throw exceptionToThrow; + throw new AggregateException(exs); } } From 4479713e047f0e51450ed343472d8c43ab57e00f Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 14:44:53 +0200 Subject: [PATCH 1570/1930] MediaStream: Replace string.IndexOf with string.Contains where possible --- MediaBrowser.Model/Entities/MediaStream.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index ade9d7e8dd..e644c9ba72 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -163,7 +163,7 @@ namespace MediaBrowser.Model.Entities foreach (var tag in attributes) { // Keep Tags that are not already in Title. - if (Title.IndexOf(tag, StringComparison.OrdinalIgnoreCase) == -1) + if (!Title.Contains(tag, StringComparison.OrdinalIgnoreCase)) { result.Append(" - ").Append(tag); } @@ -202,7 +202,7 @@ namespace MediaBrowser.Model.Entities foreach (var tag in attributes) { // Keep Tags that are not already in Title. - if (Title.IndexOf(tag, StringComparison.OrdinalIgnoreCase) == -1) + if (!Title.Contains(tag, StringComparison.OrdinalIgnoreCase)) { result.Append(" - ").Append(tag); } @@ -522,9 +522,9 @@ namespace MediaBrowser.Model.Entities // sub = external .sub file - return codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) == -1 && - codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) == -1 && - codec.IndexOf("dvbsub", StringComparison.OrdinalIgnoreCase) == -1 && + return !codec.Contains("pgs", StringComparison.OrdinalIgnoreCase) && + !codec.Contains("dvd", StringComparison.OrdinalIgnoreCase) && + !codec.Contains("dvbsub", StringComparison.OrdinalIgnoreCase) && !string.Equals(codec, "sub", StringComparison.OrdinalIgnoreCase) && !string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase); } From 787bcd4a83ea212e6ba4f93dcc4ce6788b950410 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 14:45:08 +0200 Subject: [PATCH 1571/1930] Remove dead code --- .../Entities/PeopleHelper.cs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/MediaBrowser.Controller/Entities/PeopleHelper.cs b/MediaBrowser.Controller/Entities/PeopleHelper.cs index 1f3758a73a..687ce1ec8d 100644 --- a/MediaBrowser.Controller/Entities/PeopleHelper.cs +++ b/MediaBrowser.Controller/Entities/PeopleHelper.cs @@ -100,23 +100,5 @@ namespace MediaBrowser.Controller.Entities existing.SetProviderId(id.Key, id.Value); } } - - public static bool ContainsPerson(List people, string name) - { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentNullException(nameof(name)); - } - - foreach (var i in people) - { - if (string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; - } } } From bcb4010db615b7c732856629553cba4e7ccc3358 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 15:30:32 +0200 Subject: [PATCH 1572/1930] More improvements --- .../Library/Resolvers/ItemResolver.cs | 12 ++++++------ .../Library/Resolvers/Movies/MovieResolver.cs | 2 +- .../Library/Resolvers/PhotoAlbumResolver.cs | 12 ++++++------ .../Library/Resolvers/PhotoResolver.cs | 2 +- .../Library/Resolvers/TV/SeasonResolver.cs | 2 +- .../Library/Resolvers/TV/SeriesResolver.cs | 18 ++---------------- .../Entities/CollectionFolder.cs | 1 - .../Library/ItemResolveArgs.cs | 18 +++++++++--------- .../Resolvers/BaseItemResolver.cs | 12 ++++++------ 9 files changed, 32 insertions(+), 47 deletions(-) diff --git a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs index 9ca76095b2..92fb2a753a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs @@ -11,6 +11,12 @@ namespace Emby.Server.Implementations.Library.Resolvers public abstract class ItemResolver : IItemResolver where T : BaseItem, new() { + /// + /// Gets the priority. + /// + /// The priority. + public virtual ResolverPriority Priority => ResolverPriority.First; + /// /// Resolves the specified args. /// @@ -21,12 +27,6 @@ namespace Emby.Server.Implementations.Library.Resolvers return null; } - /// - /// Gets the priority. - /// - /// The priority. - public virtual ResolverPriority Priority => ResolverPriority.First; - /// /// Sets initial values on the newly resolved item. /// diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 714bc3a84d..16bf4dc4a0 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -376,7 +376,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies { var multiDiscFolders = new List(); - var libraryOptions = args.GetLibraryOptions(); + var libraryOptions = args.LibraryOptions; var supportPhotos = string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && libraryOptions.EnablePhotos; var photos = new List(); diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 3ac837057a..204c8a62e7 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -13,7 +13,7 @@ namespace Emby.Server.Implementations.Library.Resolvers public class PhotoAlbumResolver : FolderResolver { private readonly IImageProcessor _imageProcessor; - private ILibraryManager _libraryManager; + private readonly ILibraryManager _libraryManager; /// /// Initializes a new instance of the class. @@ -26,6 +26,9 @@ namespace Emby.Server.Implementations.Library.Resolvers _libraryManager = libraryManager; } + /// + public override ResolverPriority Priority => ResolverPriority.Second; + /// /// Resolves the specified args. /// @@ -39,8 +42,8 @@ namespace Emby.Server.Implementations.Library.Resolvers // Must be an image file within a photo collection var collectionType = args.GetCollectionType(); - if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) || - (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.GetLibraryOptions().EnablePhotos)) + if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) + || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.LibraryOptions.EnablePhotos)) { if (HasPhotos(args)) { @@ -84,8 +87,5 @@ namespace Emby.Server.Implementations.Library.Resolvers return false; } - - /// - public override ResolverPriority Priority => ResolverPriority.Second; } } diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index bcfcee9c6d..3cb6542cf7 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.Library.Resolvers var collectionType = args.CollectionType; if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase) - || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.GetLibraryOptions().EnablePhotos)) + || (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) && args.LibraryOptions.EnablePhotos)) { if (IsImageFile(args.Path, _imageProcessor)) { diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 3332e1806c..768e2e4f5b 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -88,7 +88,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV CultureInfo.InvariantCulture, _localization.GetLocalizedString("NameSeasonNumber"), seasonNumber, - args.GetLibraryOptions().PreferredMetadataLanguage); + args.LibraryOptions.PreferredMetadataLanguage); } return season; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 4a9d2cf8ca..8fc3e3e75c 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -19,19 +19,16 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV /// public class SeriesResolver : FolderResolver { - private readonly IFileSystem _fileSystem; private readonly ILogger _logger; private readonly ILibraryManager _libraryManager; /// /// Initializes a new instance of the class. /// - /// The file system. /// The logger. /// The library manager. - public SeriesResolver(IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager) + public SeriesResolver(ILogger logger, ILibraryManager libraryManager) { - _fileSystem = fileSystem; _logger = logger; _libraryManager = libraryManager; } @@ -59,15 +56,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV var collectionType = args.GetCollectionType(); if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)) { - // if (args.ContainsFileSystemEntryByName("tvshow.nfo")) - //{ - // return new Series - // { - // Path = args.Path, - // Name = Path.GetFileName(args.Path) - // }; - //} - var configuredContentType = _libraryManager.GetConfiguredContentType(args.Path); if (!string.Equals(configuredContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)) { @@ -100,7 +88,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV return null; } - if (IsSeriesFolder(args.Path, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager, false)) + if (IsSeriesFolder(args.Path, args.FileSystemChildren, _logger, _libraryManager, false)) { return new Series { @@ -117,8 +105,6 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV public static bool IsSeriesFolder( string path, IEnumerable fileSystemChildren, - IDirectoryService directoryService, - IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager, bool isTvContentType) diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 347d5b73c7..bc5f38256c 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -61,7 +61,6 @@ namespace MediaBrowser.Controller.Entities try { var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions; - if (result == null) { return new LibraryOptions(); diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index f9086066d7..5f9aed3416 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -14,14 +14,14 @@ namespace MediaBrowser.Controller.Library /// These are arguments relating to the file system that are collected once and then referred to /// whenever needed. Primarily for entity resolution. /// - public class ItemResolveArgs : EventArgs + public class ItemResolveArgs { /// /// The _app paths. /// private readonly IServerApplicationPaths _appPaths; - public IDirectoryService DirectoryService { get; private set; } + private LibraryOptions _libraryOptions; /// /// Initializes a new instance of the class. @@ -34,17 +34,18 @@ namespace MediaBrowser.Controller.Library DirectoryService = directoryService; } + public IDirectoryService DirectoryService { get; } + /// /// Gets the file system children. /// /// The file system children. public FileSystemMetadata[] FileSystemChildren { get; set; } - public LibraryOptions LibraryOptions { get; set; } - - public LibraryOptions GetLibraryOptions() + public LibraryOptions LibraryOptions { - return LibraryOptions ?? (LibraryOptions = Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent)); + get => _libraryOptions ??= Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent); + set => _libraryOptions = value; } /// @@ -139,7 +140,7 @@ namespace MediaBrowser.Controller.Library /// Adds the additional location. /// /// The path. - /// + /// is null or empty. public void AddAdditionalLocation(string path) { if (string.IsNullOrEmpty(path)) @@ -148,7 +149,6 @@ namespace MediaBrowser.Controller.Library } AdditionalLocations ??= new List(); - AdditionalLocations.Add(path); } @@ -172,7 +172,7 @@ namespace MediaBrowser.Controller.Library /// /// The name. /// FileSystemInfo. - /// + /// is null or empty. public FileSystemMetadata GetFileSystemEntryByName(string name) { if (string.IsNullOrEmpty(name)) diff --git a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs index 25128a5cd0..a904c74240 100644 --- a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs +++ b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs @@ -10,6 +10,12 @@ namespace MediaBrowser.Controller.Resolvers public abstract class ItemResolver : IItemResolver where T : BaseItem, new() { + /// + /// Gets the priority. + /// + /// The priority. + public virtual ResolverPriority Priority => ResolverPriority.First; + /// /// Resolves the specified args. /// @@ -20,12 +26,6 @@ namespace MediaBrowser.Controller.Resolvers return null; } - /// - /// Gets the priority. - /// - /// The priority. - public virtual ResolverPriority Priority => ResolverPriority.First; - /// /// Sets initial values on the newly resolved item. /// From 47e7c1356c1364e5e834ce37cd4a9ace5e2d838e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Wed, 5 May 2021 16:43:20 +0200 Subject: [PATCH 1573/1930] PathExtensions: Fix index out of bounds in TryReplaceSubPath Fixes #5977 --- Emby.Server.Implementations/Library/PathExtensions.cs | 10 ++++++++-- .../Library/PathExtensionsTests.cs | 1 + 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 770cf6bb02..0de4edb7e7 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -96,8 +96,14 @@ namespace Emby.Server.Implementations.Library // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results // when the sub path matches a similar but in-complete subpath var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar; - if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase) - || (!oldSubPathEndsWithSeparator && path[subPath.Length] != newDirectorySeparatorChar)) + if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + if (path.Length > subPath.Length + && !oldSubPathEndsWithSeparator + && path[subPath.Length] != newDirectorySeparatorChar) { return false; } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs index e5508243f0..c5cc056f5d 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/PathExtensionsTests.cs @@ -33,6 +33,7 @@ namespace Jellyfin.Server.Implementations.Tests.Library [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff", "/home/jeff/", "/home/jeff/myfile.mkv")] [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/home/jeff/", "/home/jeff/myfile.mkv")] [InlineData("C:\\Users\\jeff\\myfile.mkv", "C:\\Users/jeff/", "/", "/myfile.mkv")] + [InlineData("/o", "/o", "/s", "/s")] // regression test for #5977 public void TryReplaceSubPath_ValidArgs_Correct(string path, string subPath, string newSubPath, string? expectedResult) { Assert.True(PathExtensions.TryReplaceSubPath(path, subPath, newSubPath, out var result)); From 81d675990f87586061bdce5d585dad28f7e181fa Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 22:52:39 +0100 Subject: [PATCH 1574/1930] Enable automatic url decoding --- .../ApiApplicationBuilderExtensions.cs | 10 +++ .../QueryStringDecodingMiddleware.cs | 42 +++++++++++ .../Middleware/UrlDecodeQueryFeature.cs | 75 +++++++++++++++++++ Jellyfin.Server/Startup.cs | 1 + 4 files changed, 128 insertions(+) create mode 100644 Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs create mode 100644 Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 88e2b4152b..e291677475 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -78,6 +78,16 @@ namespace Jellyfin.Server.Extensions return appBuilder.UseMiddleware(); } + /// + /// Enables url decoding before binding to the application pipeline. + /// + /// The . + /// The updated application builder. + public static IApplicationBuilder UseQueryStringDecoding(this IApplicationBuilder appBuilder) + { + return appBuilder.UseMiddleware(); + } + /// /// Adds base url redirection to the application pipeline. /// diff --git a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs new file mode 100644 index 0000000000..954dc4ccd9 --- /dev/null +++ b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Middleware +{ + /// + /// URL decodes the querystring before binding. + /// + public class QueryStringDecodingMiddleware + { + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The next delegate in the pipeline. + /// The logger. + public QueryStringDecodingMiddleware( + RequestDelegate next, + ILogger logger) + { + _next = next; + _logger = logger; + } + + /// + /// Executes the middleware action. + /// + /// The current HTTP context. + /// The async task. + public async Task Invoke(HttpContext httpContext) + { + httpContext.Features.Set(new UrlDecodeQueryFeature(httpContext.Features.Get())); + + await _next(httpContext).ConfigureAwait(false); + } + } +} diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs new file mode 100644 index 0000000000..0232b89ce1 --- /dev/null +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using System.Linq; +using System.Web; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Primitives; + +namespace Jellyfin.Server.Middleware +{ + /// + /// Defines the . + /// + public class UrlDecodeQueryFeature : IQueryFeature + { + private IQueryCollection? _store; + + /// + /// Initializes a new instance of the class. + /// + /// The instance. + public UrlDecodeQueryFeature(IQueryFeature feature) + { + Query = feature.Query; + } + + /// + /// Gets or sets a value indicating the url decoded . + /// + public IQueryCollection Query + { + get + { + return _store ?? QueryCollection.Empty; + } + + set + { + // Only interested in where the querystring is encoded which shows up as one key with everything else in the value. + if (value.Count != 1) + { + _store = value; + return; + } + + // Encoded querystrings have no value, so don't process anything if a values is present. + var kvp = value.First(); + if (!string.IsNullOrEmpty(kvp.Value)) + { + _store = value; + return; + } + + // Unencode and re-parse querystring. + var unencodedKey = HttpUtility.UrlDecode(kvp.Key); + + if (string.Equals(unencodedKey, kvp.Key, System.StringComparison.Ordinal)) + { + _store = value; + return; + } + + var pairs = new Dictionary(); + var queryString = unencodedKey.Split('&', System.StringSplitOptions.RemoveEmptyEntries); + + foreach (var pair in queryString) + { + var item = pair.Split('=', System.StringSplitOptions.RemoveEmptyEntries); + pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty)); + } + + _store = new QueryCollection(pairs); + } + } + } +} diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index e56e61092b..f27d286584 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -150,6 +150,7 @@ namespace Jellyfin.Server mainApp.UseAuthentication(); mainApp.UseJellyfinApiSwagger(_serverConfigurationManager); + mainApp.UseQueryStringDecoding(); mainApp.UseRouting(); mainApp.UseAuthorization(); From a7bccd4fe0a1c046e335a91e85b8e806b50d58bc Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 23:09:04 +0100 Subject: [PATCH 1575/1930] removed unneeded logger. --- Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs index 954dc4ccd9..d6d955c4f1 100644 --- a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs +++ b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs @@ -12,19 +12,15 @@ namespace Jellyfin.Server.Middleware public class QueryStringDecodingMiddleware { private readonly RequestDelegate _next; - private readonly ILogger _logger; /// /// Initializes a new instance of the class. /// /// The next delegate in the pipeline. - /// The logger. public QueryStringDecodingMiddleware( - RequestDelegate next, - ILogger logger) + RequestDelegate next) { _next = next; - _logger = logger; } /// From dabeabc553afc4551356566f9184e6659f604cee Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 23:14:05 +0100 Subject: [PATCH 1576/1930] corrected comments --- Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index 0232b89ce1..b18ba70512 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -35,14 +35,14 @@ namespace Jellyfin.Server.Middleware set { - // Only interested in where the querystring is encoded which shows up as one key with everything else in the value. + // Only interested in where the querystring is encoded which shows up as one key with nothing in the value. if (value.Count != 1) { _store = value; return; } - // Encoded querystrings have no value, so don't process anything if a values is present. + // Encoded querystrings have no value, so don't process anything if a value is present. var kvp = value.First(); if (!string.IsNullOrEmpty(kvp.Value)) { @@ -55,6 +55,7 @@ namespace Jellyfin.Server.Middleware if (string.Equals(unencodedKey, kvp.Key, System.StringComparison.Ordinal)) { + // Don't do anything if it's not encoded. _store = value; return; } From c8061f92bec0d1e12e2b57012c6c72c629374327 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 5 May 2021 23:15:24 +0100 Subject: [PATCH 1577/1930] slight format correction. --- Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs index d6d955c4f1..08fbbce0b2 100644 --- a/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs +++ b/Jellyfin.Server/Middleware/QueryStringDecodingMiddleware.cs @@ -17,8 +17,7 @@ namespace Jellyfin.Server.Middleware /// Initializes a new instance of the class. /// /// The next delegate in the pipeline. - public QueryStringDecodingMiddleware( - RequestDelegate next) + public QueryStringDecodingMiddleware(RequestDelegate next) { _next = next; } From ddb04dc12b8bdf33c2020cb1c539664463e61bc3 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 8 Jan 2021 23:57:27 +0100 Subject: [PATCH 1578/1930] Use new ReadAllLines extensions --- .../LiveTv/EmbyTV/EncodedRecorder.cs | 7 ++-- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 14 ++++---- .../LiveTv/TunerHosts/M3uParser.cs | 34 +++++++------------ .../Localization/LocalizationManager.cs | 10 +++--- Jellyfin.Api/Helpers/HlsHelpers.cs | 5 +-- .../Extensions/StreamExtensions.cs | 20 +++++++++-- .../Studios/StudiosImageProvider.cs | 9 +++-- 7 files changed, 48 insertions(+), 51 deletions(-) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 44a8cdee49..9372b0f6c3 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -10,6 +10,7 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; @@ -307,13 +308,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV { using (var reader = new StreamReader(source)) { - while (!reader.EndOfStream) + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) { - var line = await reader.ReadLineAsync().ConfigureAwait(false); - var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line); - await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + await target.WriteAsync(bytes.AsMemory()).ConfigureAwait(false); await target.FlushAsync().ConfigureAwait(false); } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 4aa5832b18..324109bcfe 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -182,16 +182,16 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var sr = new StreamReader(stream, System.Text.Encoding.UTF8); var tuners = new List(); - while (!sr.EndOfStream) + await foreach (var line in sr.ReadAllLinesAsync().ConfigureAwait(false)) { - string line = StripXML(sr.ReadLine()); - if (line.Contains("Channel", StringComparison.Ordinal)) + string stripedLine = StripXML(line); + if (stripedLine.Contains("Channel", StringComparison.Ordinal)) { LiveTvTunerStatus status; - var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase); - var name = line.Substring(0, index - 1); - var currentChannel = line.Substring(index + 7); - if (currentChannel != "none") + var index = stripedLine.IndexOf("Channel", StringComparison.OrdinalIgnoreCase); + var name = stripedLine.Substring(0, index - 1); + var currentChannel = stripedLine.Substring(index + 7); + if (string.Equals(currentChannel, "none", StringComparison.Ordinal)) { status = LiveTvTunerStatus.LiveTv; } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index cc30a516d6..84d4161499 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -35,16 +35,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts // Read the file and display it line by line. using (var reader = new StreamReader(await GetListingsStream(info, cancellationToken).ConfigureAwait(false))) { - return GetChannels(reader, channelIdPrefix, info.Id); - } - } - - public List ParseString(string text, string channelIdPrefix, string tunerHostId) - { - // Read the file and display it line by line. - using (var reader = new StringReader(text)) - { - return GetChannels(reader, channelIdPrefix, tunerHostId); + return await GetChannelsAsync(reader, channelIdPrefix, info.Id).ConfigureAwait(false); } } @@ -70,43 +61,42 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts private const string ExtInfPrefix = "#EXTINF:"; - private List GetChannels(TextReader reader, string channelIdPrefix, string tunerHostId) + private async Task> GetChannelsAsync(TextReader reader, string channelIdPrefix, string tunerHostId) { var channels = new List(); - string line; string extInf = string.Empty; - while ((line = reader.ReadLine()) != null) + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) { - line = line.Trim(); - if (string.IsNullOrWhiteSpace(line)) + var trimmedLine = line.Trim(); + if (string.IsNullOrWhiteSpace(trimmedLine)) { continue; } - if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase)) + if (trimmedLine.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase)) { continue; } - if (line.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase)) + if (trimmedLine.StartsWith(ExtInfPrefix, StringComparison.OrdinalIgnoreCase)) { - extInf = line.Substring(ExtInfPrefix.Length).Trim(); + extInf = trimmedLine.Substring(ExtInfPrefix.Length).Trim(); _logger.LogInformation("Found m3u channel: {0}", extInf); } - else if (!string.IsNullOrWhiteSpace(extInf) && !line.StartsWith('#')) + else if (!string.IsNullOrWhiteSpace(extInf) && !trimmedLine.StartsWith('#')) { - var channel = GetChannelnfo(extInf, tunerHostId, line); + var channel = GetChannelnfo(extInf, tunerHostId, trimmedLine); if (string.IsNullOrWhiteSpace(channel.Id)) { - channel.Id = channelIdPrefix + line.GetMD5().ToString("N", CultureInfo.InvariantCulture); + channel.Id = channelIdPrefix + trimmedLine.GetMD5().ToString("N", CultureInfo.InvariantCulture); } else { channel.Id = channelIdPrefix + channel.Id.GetMD5().ToString("N", CultureInfo.InvariantCulture); } - channel.Path = line; + channel.Path = trimmedLine; channels.Add(channel); extInf = string.Empty; } diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 46858b4fb5..220e423bf5 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Reflection; using System.Text.Json; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Json; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Entities; @@ -72,8 +73,7 @@ namespace Emby.Server.Implementations.Localization using (var str = _assembly.GetManifestResourceStream(resource)) using (var reader = new StreamReader(str)) { - string line; - while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) { if (string.IsNullOrWhiteSpace(line)) { @@ -118,10 +118,8 @@ namespace Emby.Server.Implementations.Localization using (var stream = _assembly.GetManifestResourceStream(ResourcePath)) using (var reader = new StreamReader(stream)) { - while (!reader.EndOfStream) + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) { - var line = await reader.ReadLineAsync().ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(line)) { continue; @@ -179,7 +177,7 @@ namespace Emby.Server.Implementations.Localization /// public IEnumerable GetCountries() { - StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json")); + using StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json")); return JsonSerializer.Deserialize>(reader.ReadToEnd(), _jsonOptions); } diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 18e23fb5c8..d0666034e9 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -118,10 +118,7 @@ namespace Jellyfin.Api.Helpers /// The playlist text as a string. public static string GetLivePlaylistText(string path, StreamState state) { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - using var reader = new StreamReader(stream); - - var text = reader.ReadToEnd(); + var text = File.ReadAllText(path); var segmentFormat = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) diff --git a/MediaBrowser.Common/Extensions/StreamExtensions.cs b/MediaBrowser.Common/Extensions/StreamExtensions.cs index cd77be7b2b..d49bf1d469 100644 --- a/MediaBrowser.Common/Extensions/StreamExtensions.cs +++ b/MediaBrowser.Common/Extensions/StreamExtensions.cs @@ -35,11 +35,11 @@ namespace MediaBrowser.Common.Extensions } /// - /// Reads all lines in the . + /// Reads all lines in the . /// - /// The to read from. + /// The to read from. /// All lines in the stream. - public static IEnumerable ReadAllLines(this StreamReader reader) + public static IEnumerable ReadAllLines(this TextReader reader) { string? line; while ((line = reader.ReadLine()) != null) @@ -47,5 +47,19 @@ namespace MediaBrowser.Common.Extensions yield return line; } } + + /// + /// Reads all lines in the . + /// + /// The to read from. + /// All lines in the stream. + public static async IAsyncEnumerable ReadAllLinesAsync(this TextReader reader) + { + string? line; + while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null) + { + yield return line; + } + } } } diff --git a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs index 5fcf6d9aa1..5ec9a02cbd 100644 --- a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs +++ b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -177,13 +178,11 @@ namespace MediaBrowser.Providers.Studios { var lines = new List(); - while (!reader.EndOfStream) + foreach (var line in reader.ReadAllLines()) { - var text = reader.ReadLine(); - - if (!string.IsNullOrWhiteSpace(text)) + if (!string.IsNullOrWhiteSpace(line)) { - lines.Add(text); + lines.Add(line); } } From 8eee32c8c2835382c2f7c7d959dd034a50f86e02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Kr=C3=B6nke?= Date: Thu, 6 May 2021 18:56:13 +0200 Subject: [PATCH 1579/1930] Respect configured JELLYFIN_USER in Debian's postinst In my setup I configured a different user. But updates keep "stealing" file permissions for my `$PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA` directories. --- debian/postinst | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/debian/postinst b/debian/postinst index 860222e051..2f9c4cffbf 100644 --- a/debian/postinst +++ b/debian/postinst @@ -9,6 +9,8 @@ if [[ -f $DEFAULT_FILE ]]; then . $DEFAULT_FILE fi +JELLYFIN_USER=${JELLYFIN_USER:-jellyfin} + # Data directories for program data (cache, db), configs, and logs PROGRAMDATA=${JELLYFIN_DATA_DIRECTORY-/var/lib/$NAME} CONFIGDATA=${JELLYFIN_CONFIG_DIRECTORY-/etc/$NAME} @@ -18,12 +20,12 @@ CACHEDATA=${JELLYFIN_CACHE_DIRECTORY-/var/cache/$NAME} case "$1" in configure) # create jellyfin group if it does not exist - if [[ -z "$(getent group jellyfin)" ]]; then - addgroup --quiet --system jellyfin > /dev/null 2>&1 + if [[ -z "$(getent group ${JELLYFIN_USER})" ]]; then + addgroup --quiet --system ${JELLYFIN_USER} > /dev/null 2>&1 fi # create jellyfin user if it does not exist - if [[ -z "$(getent passwd jellyfin)" ]]; then - adduser --system --ingroup jellyfin --shell /bin/false jellyfin --no-create-home --home ${PROGRAMDATA} \ + if [[ -z "$(getent passwd ${JELLYFIN_USER})" ]]; then + adduser --system --ingroup ${JELLYFIN_USER} --shell /bin/false ${JELLYFIN_USER} --no-create-home --home ${PROGRAMDATA} \ --gecos "Jellyfin default user" > /dev/null 2>&1 fi # ensure $PROGRAMDATA exists @@ -43,7 +45,7 @@ case "$1" in mkdir $CACHEDATA fi # Ensure permissions are correct on all config directories - chown -R jellyfin $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA + chown -R ${JELLYFIN_USER} $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA chgrp adm $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA chmod 0750 $PROGRAMDATA $CONFIGDATA $LOGDATA $CACHEDATA From 3cd57cb28703a078cc4c03e0af53a6b2e166a679 Mon Sep 17 00:00:00 2001 From: Jake King Date: Thu, 6 May 2021 19:50:00 +0100 Subject: [PATCH 1580/1930] Fixes for Book Progress - Ignore Books when checking for minium progress --- Emby.Server.Implementations/Library/UserDataManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 827e3c64b3..d7e4e2af7f 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -220,7 +220,7 @@ namespace Emby.Server.Implementations.Library var hasRuntime = runtimeTicks > 0; // If a position has been reported, and if we know the duration - if (positionTicks > 0 && hasRuntime && !(item is AudioBook)) + if (positionTicks > 0 && hasRuntime && !(item is AudioBook) && !(item is Book)) { var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100; @@ -239,7 +239,7 @@ namespace Emby.Server.Implementations.Library { // Enforce MinResumeDuration var durationSeconds = TimeSpan.FromTicks(runtimeTicks).TotalSeconds; - if (durationSeconds < _config.Configuration.MinResumeDurationSeconds && !(item is Book)) + if (durationSeconds < _config.Configuration.MinResumeDurationSeconds) { positionTicks = 0; data.Played = playedToCompletion = true; From ad1d9d9a23c4bff7a485a61fe41639a7d1b3491e Mon Sep 17 00:00:00 2001 From: wehrstedt Date: Thu, 6 May 2021 23:07:32 +0200 Subject: [PATCH 1581/1930] fixed no channel icons when using tvheadend (#5996) Co-authored-by: Cody Robibero Co-authored-by: Maximilian Wehrstedt --- MediaBrowser.Providers/Manager/ProviderManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 08c92e15a0..dd497845d1 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -167,7 +167,7 @@ namespace MediaBrowser.Providers.Manager throw new HttpRequestException("Invalid image received.", null, response.StatusCode); } - var contentType = response.Content.Headers.ContentType.MediaType; + var contentType = response.Content.Headers.ContentType?.MediaType; // Workaround for tvheadend channel icons // TODO: Isolate this hack into the tvh plugin From 4b9a64c18cff58938dab0c0770147a5e48c833f9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 6 May 2021 23:16:52 +0200 Subject: [PATCH 1582/1930] Abstract JsonDelimitedArrayConverter --- .../JsonCommaDelimitedArrayConverter.cs | 63 +-------------- .../Converters/JsonDelimitedArrayConverter.cs | 81 +++++++++++++++++++ .../JsonPipeDelimitedArrayConverter.cs | 64 +-------------- 3 files changed, 87 insertions(+), 121 deletions(-) create mode 100644 MediaBrowser.Common/Json/Converters/JsonDelimitedArrayConverter.cs diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs index 55c4665e83..127a41a06b 100644 --- a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs @@ -9,73 +9,16 @@ namespace MediaBrowser.Common.Json.Converters /// Convert comma delimited string to array of type. /// /// Type to convert to. - public class JsonCommaDelimitedArrayConverter : JsonConverter + public sealed class JsonCommaDelimitedArrayConverter : JsonDelimitedArrayConverter { - private readonly TypeConverter _typeConverter; - /// /// Initializes a new instance of the class. /// - public JsonCommaDelimitedArrayConverter() + public JsonCommaDelimitedArrayConverter() : base() { - _typeConverter = TypeDescriptor.GetConverter(typeof(T)); } /// - public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType == JsonTokenType.Null) - { - return null; - } - - if (reader.TokenType == JsonTokenType.String) - { - // GetString can't return null here because we already handled it above - var stringEntries = reader.GetString()!.Split(',', StringSplitOptions.RemoveEmptyEntries); - if (stringEntries.Length == 0) - { - return Array.Empty(); - } - - var parsedValues = new object[stringEntries.Length]; - var convertedCount = 0; - for (var i = 0; i < stringEntries.Length; i++) - { - try - { - parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim()); - convertedCount++; - } - catch (FormatException) - { - // TODO log when upgraded to .Net6 - // https://github.com/dotnet/runtime/issues/42975 - // _logger.LogDebug(e, "Error converting value."); - } - } - - var typedValues = new T[convertedCount]; - var typedValueIndex = 0; - for (var i = 0; i < stringEntries.Length; i++) - { - if (parsedValues[i] != null) - { - typedValues.SetValue(parsedValues[i], typedValueIndex); - typedValueIndex++; - } - } - - return typedValues; - } - - return JsonSerializer.Deserialize(ref reader, options); - } - - /// - public override void Write(Utf8JsonWriter writer, T[]? value, JsonSerializerOptions options) - { - throw new NotImplementedException(); - } + protected override char Delimiter => ','; } } diff --git a/MediaBrowser.Common/Json/Converters/JsonDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonDelimitedArrayConverter.cs new file mode 100644 index 0000000000..b691798c98 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonDelimitedArrayConverter.cs @@ -0,0 +1,81 @@ +using System; +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// + /// Convert delimited string to array of type. + /// + /// Type to convert to. + public abstract class JsonDelimitedArrayConverter : JsonConverter + { + private readonly TypeConverter _typeConverter; + + /// + /// Initializes a new instance of the class. + /// + protected JsonDelimitedArrayConverter() + { + _typeConverter = TypeDescriptor.GetConverter(typeof(T)); + } + + /// + /// Gets the array delimiter. + /// + protected virtual char Delimiter { get; } + + /// + public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + // GetString can't return null here because we already handled it above + var stringEntries = reader.GetString()?.Split(Delimiter, StringSplitOptions.RemoveEmptyEntries); + if (stringEntries == null || stringEntries.Length == 0) + { + return Array.Empty(); + } + + var parsedValues = new object[stringEntries.Length]; + var convertedCount = 0; + for (var i = 0; i < stringEntries.Length; i++) + { + try + { + parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim()); + convertedCount++; + } + catch (FormatException) + { + // TODO log when upgraded to .Net6 + // https://github.com/dotnet/runtime/issues/42975 + // _logger.LogDebug(e, "Error converting value."); + } + } + + var typedValues = new T[convertedCount]; + var typedValueIndex = 0; + for (var i = 0; i < stringEntries.Length; i++) + { + if (parsedValues[i] != null) + { + typedValues.SetValue(parsedValues[i], typedValueIndex); + typedValueIndex++; + } + } + + return typedValues; + } + + return JsonSerializer.Deserialize(ref reader, options); + } + + /// + public override void Write(Utf8JsonWriter writer, T[]? value, JsonSerializerOptions options) + { + throw new NotImplementedException(); + } + } +} diff --git a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs index c83657b5f9..a8f6cfbecf 100644 --- a/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs +++ b/MediaBrowser.Common/Json/Converters/JsonPipeDelimitedArrayConverter.cs @@ -9,74 +9,16 @@ namespace MediaBrowser.Common.Json.Converters /// Convert Pipe delimited string to array of type. /// /// Type to convert to. - public class JsonPipeDelimitedArrayConverter : JsonConverter + public sealed class JsonPipeDelimitedArrayConverter : JsonDelimitedArrayConverter { - private readonly TypeConverter _typeConverter; - /// /// Initializes a new instance of the class. /// - public JsonPipeDelimitedArrayConverter() + public JsonPipeDelimitedArrayConverter() : base() { - _typeConverter = TypeDescriptor.GetConverter(typeof(T)); } /// - public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType == JsonTokenType.Null) - { - return Array.Empty(); - } - - if (reader.TokenType == JsonTokenType.String) - { - // GetString can't return null here because we already handled it above - var stringEntries = reader.GetString()!.Split('|', StringSplitOptions.RemoveEmptyEntries); - if (stringEntries.Length == 0) - { - return Array.Empty(); - } - - var parsedValues = new object[stringEntries.Length]; - var convertedCount = 0; - for (var i = 0; i < stringEntries.Length; i++) - { - try - { - parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim()); - convertedCount++; - } - catch (FormatException) - { - // TODO log when upgraded to .Net6 - // https://github.com/dotnet/runtime/issues/42975 - // _logger.LogDebug(e, "Error converting value."); - } - } - - var typedValues = new T[convertedCount]; - var typedValueIndex = 0; - for (var i = 0; i < stringEntries.Length; i++) - { - if (parsedValues[i] != null) - { - typedValues.SetValue(parsedValues[i], typedValueIndex); - typedValueIndex++; - } - } - - return typedValues; - } - - // can't return null here because we already handled it above - return JsonSerializer.Deserialize(ref reader, options)!; - } - - /// - public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options) - { - throw new NotImplementedException(); - } + protected override char Delimiter => '|'; } } From ead4e1e977b086ea70db0214a3714268547e8102 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 6 May 2021 23:54:29 +0200 Subject: [PATCH 1583/1930] Add support for legacy HDhomerun DUAl --- .../TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- .../LiveTv/HdHomerunHostTests.cs | 47 +++++++++++++++---- .../LiveTv/10.10.10.100/discover.json | 1 + .../Test Data/LiveTv/10.10.10.100/lineup.json | 1 + .../LiveTv/{ => 192.168.1.182}/discover.json | 0 .../LiveTv/{ => 192.168.1.182}/lineup.json | 0 6 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json rename tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/{ => 192.168.1.182}/discover.json (100%) rename tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/{ => 192.168.1.182}/lineup.json (100%) diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 4aa5832b18..b6124753f2 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -74,7 +74,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false); - using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL ?? model.BaseURL + "/lineup.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var lineup = await JsonSerializer.DeserializeAsync>(stream, _jsonOptions, cancellationToken) .ConfigureAwait(false) ?? new List(); diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs index 8847239d90..c859d11c69 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/HdHomerunHostTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Net.Http; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using AutoFixture; @@ -15,8 +16,6 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { public class HdHomerunHostTests { - private const string TestIp = "http://192.168.1.182"; - private readonly Fixture _fixture; private readonly HdHomerunHost _hdHomerunHost; @@ -30,7 +29,7 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { return Task.FromResult(new HttpResponseMessage() { - Content = new StreamContent(File.OpenRead("Test Data/LiveTv/" + m.RequestUri?.Segments[^1])) + Content = new StreamContent(File.OpenRead(Path.Combine("Test Data/LiveTv", m.RequestUri!.Host, m.RequestUri.Segments[^1]))) }); }); @@ -50,7 +49,7 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { var host = new TunerHostInfo() { - Url = TestIp + Url = "192.168.1.182" }; var modelInfo = await _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None).ConfigureAwait(false); @@ -65,6 +64,26 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.Equal("http://192.168.1.182:80/lineup.json", modelInfo.LineupURL); } + [Fact] + public async Task GetModelInfo_Legacy_Success() + { + var host = new TunerHostInfo() + { + Url = "10.10.10.100" + }; + + var modelInfo = await _hdHomerunHost.GetModelInfo(host, true, CancellationToken.None).ConfigureAwait(false); + Assert.Equal("HDHomeRun DUAL", modelInfo.FriendlyName); + Assert.Equal("HDHR3-US", modelInfo.ModelNumber); + Assert.Equal("hdhomerun3_atsc", modelInfo.FirmwareName); + Assert.Equal("20200225", modelInfo.FirmwareVersion); + Assert.Equal("10xxxxx5", modelInfo.DeviceID); + Assert.Null(modelInfo.DeviceAuth); + Assert.Equal(2, modelInfo.TunerCount); + Assert.Equal("http://10.10.10.100:80", modelInfo.BaseURL); + Assert.Null(modelInfo.LineupURL); + } + [Fact] public async Task GetModelInfo_EmptyUrl_ArgumentException() { @@ -81,7 +100,7 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv { var host = new TunerHostInfo() { - Url = TestIp + Url = "192.168.1.182" }; var channels = await _hdHomerunHost.GetLineup(host, CancellationToken.None).ConfigureAwait(false); @@ -93,12 +112,24 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv Assert.Equal("http://192.168.1.111:5004/auto/v4.1", channels[0].URL); } + [Fact] + public async Task GetLineup_Legacy_Success() + { + var host = new TunerHostInfo() + { + Url = "10.10.10.100" + }; + + // Placeholder json is invalid, just need to make sure we can reach it + await Assert.ThrowsAsync(() => _hdHomerunHost.GetLineup(host, CancellationToken.None)); + } + [Fact] public async Task GetLineup_ImportFavoritesOnly_Success() { var host = new TunerHostInfo() { - Url = TestIp, + Url = "192.168.1.182", ImportFavoritesOnly = true }; @@ -114,9 +145,9 @@ namespace Jellyfin.Server.Implementations.Tests.LiveTv [Fact] public async Task TryGetTunerHostInfo_Valid_Success() { - var host = await _hdHomerunHost.TryGetTunerHostInfo(TestIp, CancellationToken.None).ConfigureAwait(false); + var host = await _hdHomerunHost.TryGetTunerHostInfo("192.168.1.182", CancellationToken.None).ConfigureAwait(false); Assert.Equal(_hdHomerunHost.Type, host.Type); - Assert.Equal(TestIp, host.Url); + Assert.Equal("192.168.1.182", host.Url); Assert.Equal("HDHomeRun PRIME", host.FriendlyName); Assert.Equal("FFFFFFFF", host.DeviceId); Assert.Equal(3, host.TunerCount); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json new file mode 100644 index 0000000000..a4ad4ed444 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/discover.json @@ -0,0 +1 @@ +{"FriendlyName":"HDHomeRun DUAL","ModelNumber":"HDHR3-US","Legacy":1,"FirmwareName":"hdhomerun3_atsc","FirmwareVersion":"20200225","DeviceID":"10xxxxx5","TunerCount":2,"BaseURL":"http://10.10.10.100:80"} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/10.10.10.100/lineup.json @@ -0,0 +1 @@ +{} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/discover.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json similarity index 100% rename from tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/discover.json rename to tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/discover.json diff --git a/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/lineup.json b/tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json similarity index 100% rename from tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/lineup.json rename to tests/Jellyfin.Server.Implementations.Tests/Test Data/LiveTv/192.168.1.182/lineup.json From fb090df0b59b71d7f143d2181d46f18943bbc35e Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 7 May 2021 00:39:20 +0200 Subject: [PATCH 1584/1930] Enable nullable reference types for MediaBrowser.Controller --- Jellyfin.Api/Controllers/LibraryController.cs | 2 +- .../Authentication/AuthenticationResult.cs | 2 ++ .../Authentication/IAuthenticationProvider.cs | 2 ++ .../Authentication/IPasswordResetProvider.cs | 2 ++ .../BaseItemManager/BaseItemManager.cs | 2 ++ .../BaseItemManager/IBaseItemManager.cs | 2 ++ MediaBrowser.Controller/Channels/Channel.cs | 2 ++ .../Channels/ChannelItemInfo.cs | 2 ++ .../Channels/ChannelItemResult.cs | 2 ++ .../Channels/ChannelSearchInfo.cs | 2 ++ MediaBrowser.Controller/Channels/IChannel.cs | 2 ++ .../Channels/IChannelManager.cs | 2 ++ .../Channels/IHasCacheKey.cs | 2 ++ .../Channels/ISearchableChannel.cs | 2 ++ .../Channels/InternalChannelFeatures.cs | 2 ++ .../Channels/InternalChannelItemQuery.cs | 2 ++ .../Collections/CollectionCreationOptions.cs | 2 ++ .../Collections/CollectionEvents.cs | 2 ++ .../Collections/ICollectionManager.cs | 2 ++ .../IServerConfigurationManager.cs | 2 ++ .../Devices/IDeviceManager.cs | 2 ++ MediaBrowser.Controller/Dlna/IDlnaManager.cs | 2 ++ .../Drawing/IImageEncoder.cs | 2 ++ .../Drawing/IImageProcessor.cs | 2 ++ .../Drawing/ImageCollageOptions.cs | 2 ++ .../Drawing/ImageHelper.cs | 2 ++ .../Drawing/ImageProcessingOptions.cs | 2 ++ .../Drawing/ImageProcessorExtensions.cs | 2 ++ .../Drawing/ImageStream.cs | 2 +- MediaBrowser.Controller/Dto/DtoOptions.cs | 2 ++ MediaBrowser.Controller/Dto/IDtoService.cs | 2 ++ .../Entities/AggregateFolder.cs | 2 ++ .../Entities/Audio/Audio.cs | 2 ++ .../Entities/Audio/IHasAlbumArtist.cs | 2 ++ .../Entities/Audio/IHasMusicGenres.cs | 2 ++ .../Entities/Audio/MusicAlbum.cs | 2 ++ .../Entities/Audio/MusicArtist.cs | 2 ++ .../Entities/Audio/MusicGenre.cs | 2 ++ MediaBrowser.Controller/Entities/AudioBook.cs | 2 ++ MediaBrowser.Controller/Entities/BaseItem.cs | 2 ++ .../Entities/BaseItemExtensions.cs | 2 ++ .../Entities/BasePluginFolder.cs | 2 ++ MediaBrowser.Controller/Entities/Book.cs | 2 ++ .../Entities/CollectionFolder.cs | 2 ++ .../Entities/Extensions.cs | 2 ++ MediaBrowser.Controller/Entities/Folder.cs | 2 ++ MediaBrowser.Controller/Entities/Genre.cs | 2 ++ .../Entities/ICollectionFolder.cs | 2 ++ .../Entities/IHasAspectRatio.cs | 2 ++ .../Entities/IHasDisplayOrder.cs | 2 ++ .../Entities/IHasMediaSources.cs | 2 ++ .../Entities/IHasProgramAttributes.cs | 2 ++ .../Entities/IHasSeries.cs | 2 ++ .../Entities/IHasSpecialFeatures.cs | 2 ++ .../Entities/IHasTrailers.cs | 2 ++ .../Entities/InternalItemsQuery.cs | 2 ++ .../Entities/InternalPeopleQuery.cs | 2 ++ .../Entities/ItemImageInfo.cs | 2 ++ .../Entities/LinkedChild.cs | 2 ++ .../Entities/Movies/BoxSet.cs | 2 ++ .../Entities/Movies/Movie.cs | 2 ++ .../Entities/MusicVideo.cs | 2 ++ MediaBrowser.Controller/Entities/Person.cs | 2 ++ .../Entities/PersonInfo.cs | 2 ++ MediaBrowser.Controller/Entities/Photo.cs | 2 ++ MediaBrowser.Controller/Entities/Share.cs | 2 ++ MediaBrowser.Controller/Entities/Studio.cs | 2 ++ .../Entities/TV/Episode.cs | 2 ++ MediaBrowser.Controller/Entities/TV/Season.cs | 2 ++ MediaBrowser.Controller/Entities/TV/Series.cs | 2 ++ MediaBrowser.Controller/Entities/Trailer.cs | 2 ++ .../Entities/UserItemData.cs | 2 ++ .../Entities/UserRootFolder.cs | 2 ++ MediaBrowser.Controller/Entities/UserView.cs | 2 ++ .../Entities/UserViewBuilder.cs | 2 ++ MediaBrowser.Controller/Entities/Video.cs | 2 ++ MediaBrowser.Controller/Entities/Year.cs | 2 ++ .../Events/IEventConsumer.cs | 2 +- .../Events/IEventManager.cs | 2 +- .../Events/Session/SessionEndedEventArgs.cs | 2 +- .../Events/Session/SessionStartedEventArgs.cs | 2 +- .../PluginInstallationCancelledEventArgs.cs | 2 +- .../Updates/PluginInstalledEventArgs.cs | 2 +- .../Updates/PluginInstallingEventArgs.cs | 2 +- .../Events/Updates/PluginUpdatedEventArgs.cs | 2 +- .../Extensions/StringExtensions.cs | 1 - .../IDisplayPreferencesManager.cs | 2 ++ .../IServerApplicationHost.cs | 2 ++ .../IServerApplicationPaths.cs | 2 ++ .../Library/IIntroProvider.cs | 2 ++ .../Library/ILibraryManager.cs | 2 ++ .../Library/ILiveStream.cs | 2 ++ .../Library/IMediaSourceManager.cs | 2 ++ .../Library/IMetadataSaver.cs | 2 ++ .../Library/IMusicManager.cs | 2 ++ .../Library/IUserDataManager.cs | 2 ++ .../Library/IUserManager.cs | 2 ++ .../Library/IUserViewManager.cs | 2 ++ MediaBrowser.Controller/Library/IntroInfo.cs | 2 ++ .../Library/ItemChangeEventArgs.cs | 2 ++ .../Library/ItemResolveArgs.cs | 2 ++ .../Library/LibraryManagerExtensions.cs | 2 ++ .../MetadataConfigurationExtensions.cs | 2 ++ .../Library/NameExtensions.cs | 1 - .../Library/PlaybackProgressEventArgs.cs | 2 ++ .../Library/PlaybackStartEventArgs.cs | 2 +- MediaBrowser.Controller/Library/Profiler.cs | 2 ++ .../Library/SearchHintInfo.cs | 2 ++ MediaBrowser.Controller/Library/TVUtils.cs | 4 +++- .../Library/UserDataSaveEventArgs.cs | 2 ++ MediaBrowser.Controller/LiveTv/ChannelInfo.cs | 2 ++ .../LiveTv/IListingsProvider.cs | 2 ++ .../LiveTv/ILiveTvManager.cs | 2 ++ .../LiveTv/ILiveTvService.cs | 2 ++ MediaBrowser.Controller/LiveTv/ITunerHost.cs | 2 ++ .../LiveTv/LiveTvChannel.cs | 2 ++ .../LiveTv/LiveTvProgram.cs | 2 ++ .../LiveTv/LiveTvServiceStatusInfo.cs | 2 ++ .../LiveTv/LiveTvTunerInfo.cs | 2 ++ MediaBrowser.Controller/LiveTv/ProgramInfo.cs | 2 ++ .../LiveTv/RecordingInfo.cs | 2 ++ .../LiveTv/RecordingStatusChangedEventArgs.cs | 2 ++ .../LiveTv/SeriesTimerInfo.cs | 2 ++ .../LiveTv/TimerEventInfo.cs | 2 ++ MediaBrowser.Controller/LiveTv/TimerInfo.cs | 2 ++ .../LiveTv/TunerChannelMapping.cs | 2 ++ .../MediaBrowser.Controller.csproj | 1 + .../MediaEncoding/EncodingHelper.cs | 2 ++ .../MediaEncoding/EncodingJobInfo.cs | 2 ++ .../MediaEncoding/EncodingJobOptions.cs | 2 ++ .../MediaEncoding/IAttachmentExtractor.cs | 2 ++ .../MediaEncoding/IEncodingManager.cs | 2 ++ .../MediaEncoding/IMediaEncoder.cs | 2 ++ .../MediaEncoding/ISubtitleEncoder.cs | 2 ++ .../MediaEncoding/ImageEncodingOptions.cs | 2 ++ .../MediaEncoding/JobLogger.cs | 2 ++ .../MediaEncoding/MediaEncoderHelpers.cs | 1 - .../MediaEncoding/MediaInfoRequest.cs | 2 ++ .../Net/AuthorizationInfo.cs | 2 ++ .../Net/BasePeriodicWebSocketListener.cs | 2 ++ MediaBrowser.Controller/Net/IAuthService.cs | 2 -- .../Net/IWebSocketConnection.cs | 2 ++ .../Net/SecurityException.cs | 2 -- .../Net/WebSocketMessageInfo.cs | 2 ++ .../Notifications/INotificationManager.cs | 2 +- .../Notifications/INotificationService.cs | 2 ++ .../Notifications/UserNotification.cs | 2 ++ .../Persistence/IItemRepository.cs | 2 ++ .../Persistence/IUserDataRepository.cs | 2 ++ MediaBrowser.Controller/Playlists/Playlist.cs | 2 ++ .../Plugins/ILocalizablePlugin.cs | 22 ------------------- MediaBrowser.Controller/Providers/BookInfo.cs | 2 ++ .../Providers/DynamicImageResponse.cs | 2 ++ .../Providers/EpisodeInfo.cs | 2 ++ .../Providers/IExternalId.cs | 2 ++ .../Providers/IProviderManager.cs | 2 ++ .../Providers/ImageRefreshOptions.cs | 2 ++ MediaBrowser.Controller/Providers/ItemInfo.cs | 2 ++ .../Providers/ItemLookupInfo.cs | 2 ++ .../Providers/LocalImageInfo.cs | 2 ++ .../Providers/MetadataRefreshOptions.cs | 2 ++ .../Providers/MetadataResult.cs | 2 ++ .../Providers/MusicVideoInfo.cs | 2 ++ .../Providers/RemoteSearchQuery.cs | 2 ++ MediaBrowser.Controller/Providers/SongInfo.cs | 2 ++ .../QuickConnect/IQuickConnect.cs | 2 ++ .../Resolvers/BaseItemResolver.cs | 2 ++ .../Security/AuthenticationInfo.cs | 2 ++ .../Security/AuthenticationInfoQuery.cs | 2 ++ .../Security/IAuthenticationRepository.cs | 2 ++ .../Session/AuthenticationRequest.cs | 2 ++ .../Session/ISessionController.cs | 2 ++ .../Session/ISessionManager.cs | 2 ++ .../Session/SessionEventArgs.cs | 2 ++ .../Session/SessionInfo.cs | 2 ++ .../Sorting/AlphanumComparator.cs | 2 -- .../Sorting/IUserBaseItemComparer.cs | 2 ++ .../Sorting/SortExtensions.cs | 2 ++ .../Subtitles/ISubtitleManager.cs | 2 ++ .../Subtitles/ISubtitleProvider.cs | 2 ++ .../SubtitleDownloadFailureEventArgs.cs | 2 ++ .../Subtitles/SubtitleResponse.cs | 2 ++ .../Subtitles/SubtitleSearchRequest.cs | 2 ++ .../Sync/IHasDynamicAccess.cs | 2 ++ .../Sync/IServerSyncProvider.cs | 2 ++ MediaBrowser.Controller/Sync/ISyncProvider.cs | 2 ++ .../Sync/SyncedFileInfo.cs | 2 ++ .../SyncPlay/GroupMember.cs | 2 ++ .../GroupStates/AbstractGroupState.cs | 2 ++ .../SyncPlay/GroupStates/IdleGroupState.cs | 2 ++ .../SyncPlay/GroupStates/PausedGroupState.cs | 2 ++ .../SyncPlay/GroupStates/PlayingGroupState.cs | 2 ++ .../SyncPlay/GroupStates/WaitingGroupState.cs | 2 ++ .../SyncPlay/IGroupPlaybackRequest.cs | 2 ++ .../SyncPlay/IGroupState.cs | 2 ++ .../SyncPlay/IGroupStateContext.cs | 2 ++ .../SyncPlay/ISyncPlayManager.cs | 2 ++ .../AbstractPlaybackRequest.cs | 2 ++ .../PlaybackRequests/BufferGroupRequest.cs | 2 ++ .../IgnoreWaitGroupRequest.cs | 2 ++ .../MovePlaylistItemGroupRequest.cs | 2 ++ .../PlaybackRequests/NextItemGroupRequest.cs | 2 ++ .../PlaybackRequests/PauseGroupRequest.cs | 2 ++ .../PlaybackRequests/PingGroupRequest.cs | 2 ++ .../PlaybackRequests/PlayGroupRequest.cs | 2 ++ .../PreviousItemGroupRequest.cs | 2 ++ .../PlaybackRequests/QueueGroupRequest.cs | 2 ++ .../PlaybackRequests/ReadyGroupRequest.cs | 2 ++ .../RemoveFromPlaylistGroupRequest.cs | 2 ++ .../PlaybackRequests/SeekGroupRequest.cs | 2 ++ .../SetPlaylistItemGroupRequest.cs | 2 ++ .../SetRepeatModeGroupRequest.cs | 2 ++ .../SetShuffleModeGroupRequest.cs | 2 ++ .../SyncPlay/Queue/PlayQueueManager.cs | 2 ++ .../Images/EpisodeLocalImageProvider.cs | 4 ++++ 215 files changed, 406 insertions(+), 44 deletions(-) delete mode 100644 MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs diff --git a/Jellyfin.Api/Controllers/LibraryController.cs b/Jellyfin.Api/Controllers/LibraryController.cs index 1d4bbe61e8..4ed15e1d51 100644 --- a/Jellyfin.Api/Controllers/LibraryController.cs +++ b/Jellyfin.Api/Controllers/LibraryController.cs @@ -600,7 +600,7 @@ namespace Jellyfin.Api.Controllers { foreach (var item in dto.Updates) { - _libraryMonitor.ReportFileSystemChanged(item.Path); + _libraryMonitor.ReportFileSystemChanged(item.Path ?? throw new ArgumentException("Item path can't be null.")); } return NoContent(); diff --git a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs index 4249a9a667..635e4eb3d7 100644 --- a/MediaBrowser.Controller/Authentication/AuthenticationResult.cs +++ b/MediaBrowser.Controller/Authentication/AuthenticationResult.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs index ecdffa2ebe..a56d3c8223 100644 --- a/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs +++ b/MediaBrowser.Controller/Authentication/IAuthenticationProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Threading.Tasks; diff --git a/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs b/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs index 6729b91157..8c9d1baf88 100644 --- a/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs +++ b/MediaBrowser.Controller/Authentication/IPasswordResetProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index a233c358e4..68119cfed6 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Linq; using System.Threading; diff --git a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs index 8a87364270..b2b36c040b 100644 --- a/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/IBaseItemManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Configuration; diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs index b2315bda47..26c64e0da6 100644 --- a/MediaBrowser.Controller/Channels/Channel.cs +++ b/MediaBrowser.Controller/Channels/Channel.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs index 476992cbd4..fa7aff647b 100644 --- a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs +++ b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Channels/ChannelItemResult.cs b/MediaBrowser.Controller/Channels/ChannelItemResult.cs index cee7b20039..8e937852f1 100644 --- a/MediaBrowser.Controller/Channels/ChannelItemResult.cs +++ b/MediaBrowser.Controller/Channels/ChannelItemResult.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs index 32469d4d7b..53a73d62a9 100644 --- a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs +++ b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Channels diff --git a/MediaBrowser.Controller/Channels/IChannel.cs b/MediaBrowser.Controller/Channels/IChannel.cs index 2c0eadf950..01bf8d5c85 100644 --- a/MediaBrowser.Controller/Channels/IChannel.cs +++ b/MediaBrowser.Controller/Channels/IChannel.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs index ddae7dbd3e..4c5626338e 100644 --- a/MediaBrowser.Controller/Channels/IChannelManager.cs +++ b/MediaBrowser.Controller/Channels/IChannelManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Channels/IHasCacheKey.cs b/MediaBrowser.Controller/Channels/IHasCacheKey.cs index bf895a0eca..9fae43033e 100644 --- a/MediaBrowser.Controller/Channels/IHasCacheKey.cs +++ b/MediaBrowser.Controller/Channels/IHasCacheKey.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Channels diff --git a/MediaBrowser.Controller/Channels/ISearchableChannel.cs b/MediaBrowser.Controller/Channels/ISearchableChannel.cs index b627ca1c25..b58446fc43 100644 --- a/MediaBrowser.Controller/Channels/ISearchableChannel.cs +++ b/MediaBrowser.Controller/Channels/ISearchableChannel.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs index 137f5d095b..152c653dc4 100644 --- a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs +++ b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs b/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs index 7e9bb28ed6..0d837faca2 100644 --- a/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs +++ b/MediaBrowser.Controller/Channels/InternalChannelItemQuery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs index f6037d05e1..94e7541f87 100644 --- a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs +++ b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Collections/CollectionEvents.cs b/MediaBrowser.Controller/Collections/CollectionEvents.cs index ce59b4ada2..821318ffcb 100644 --- a/MediaBrowser.Controller/Collections/CollectionEvents.cs +++ b/MediaBrowser.Controller/Collections/CollectionEvents.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Collections/ICollectionManager.cs b/MediaBrowser.Controller/Collections/ICollectionManager.cs index a6991e2eac..46bc37e7f6 100644 --- a/MediaBrowser.Controller/Collections/ICollectionManager.cs +++ b/MediaBrowser.Controller/Collections/ICollectionManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs b/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs index 43ad04dbac..44e2c45dd4 100644 --- a/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs +++ b/MediaBrowser.Controller/Configuration/IServerConfigurationManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Common.Configuration; using MediaBrowser.Model.Configuration; diff --git a/MediaBrowser.Controller/Devices/IDeviceManager.cs b/MediaBrowser.Controller/Devices/IDeviceManager.cs index 8f0872dba9..ef17c8fb37 100644 --- a/MediaBrowser.Controller/Devices/IDeviceManager.cs +++ b/MediaBrowser.Controller/Devices/IDeviceManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Dlna/IDlnaManager.cs b/MediaBrowser.Controller/Dlna/IDlnaManager.cs index dc2d5a356a..b51dc255ce 100644 --- a/MediaBrowser.Controller/Dlna/IDlnaManager.cs +++ b/MediaBrowser.Controller/Dlna/IDlnaManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Drawing/IImageEncoder.cs b/MediaBrowser.Controller/Drawing/IImageEncoder.cs index 770c6dc2d2..800f7a8bb9 100644 --- a/MediaBrowser.Controller/Drawing/IImageEncoder.cs +++ b/MediaBrowser.Controller/Drawing/IImageEncoder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 #nullable enable diff --git a/MediaBrowser.Controller/Drawing/IImageProcessor.cs b/MediaBrowser.Controller/Drawing/IImageProcessor.cs index 142cebd0c0..9bfead8b3b 100644 --- a/MediaBrowser.Controller/Drawing/IImageProcessor.cs +++ b/MediaBrowser.Controller/Drawing/IImageProcessor.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 #nullable enable diff --git a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs index fe0465d0d7..f06bbe4d0d 100644 --- a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Drawing diff --git a/MediaBrowser.Controller/Drawing/ImageHelper.cs b/MediaBrowser.Controller/Drawing/ImageHelper.cs index 596fcbc8cf..204175ed5a 100644 --- a/MediaBrowser.Controller/Drawing/ImageHelper.cs +++ b/MediaBrowser.Controller/Drawing/ImageHelper.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 #nullable enable diff --git a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs index 230a0af60c..11e6633011 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessingOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs b/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs index d3a2b4dbf2..b036425ab3 100644 --- a/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs +++ b/MediaBrowser.Controller/Drawing/ImageProcessorExtensions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Drawing/ImageStream.cs b/MediaBrowser.Controller/Drawing/ImageStream.cs index 46f58ec159..591cc53d10 100644 --- a/MediaBrowser.Controller/Drawing/ImageStream.cs +++ b/MediaBrowser.Controller/Drawing/ImageStream.cs @@ -12,7 +12,7 @@ namespace MediaBrowser.Controller.Drawing /// Gets or sets the stream. ///
/// The stream. - public Stream Stream { get; set; } + public Stream? Stream { get; set; } /// /// Gets or sets the format. diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs index 3567837507..758e841a7f 100644 --- a/MediaBrowser.Controller/Dto/DtoOptions.cs +++ b/MediaBrowser.Controller/Dto/DtoOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs index 988557f42c..7f4bbead0f 100644 --- a/MediaBrowser.Controller/Dto/IDtoService.cs +++ b/MediaBrowser.Controller/Dto/IDtoService.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index 6a92200dd1..f1944a7d3d 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index 8220464b39..4c2b7cb7c7 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs index 20fad4cb0e..1625c748a8 100644 --- a/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/IHasAlbumArtist.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs b/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs index ac4dd1688b..db60c3071d 100644 --- a/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs +++ b/MediaBrowser.Controller/Entities/Audio/IHasMusicGenres.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Entities.Audio diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index 9a33ad9d74..610bce4f5f 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 8a9bb12c7b..6101d30169 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index f0c076108e..b07d47ffdd 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/AudioBook.cs b/MediaBrowser.Controller/Entities/AudioBook.cs index f4bd851e1b..4052846228 100644 --- a/MediaBrowser.Controller/Entities/AudioBook.cs +++ b/MediaBrowser.Controller/Entities/AudioBook.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 32ae154983..ca52132735 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs index 157ed83328..c39b18891f 100644 --- a/MediaBrowser.Controller/Entities/BaseItemExtensions.cs +++ b/MediaBrowser.Controller/Entities/BaseItemExtensions.cs @@ -1,3 +1,5 @@ +#nullable disable + #nullable enable #pragma warning disable CS1591 diff --git a/MediaBrowser.Controller/Entities/BasePluginFolder.cs b/MediaBrowser.Controller/Entities/BasePluginFolder.cs index ef5a5a734c..1bd25042f2 100644 --- a/MediaBrowser.Controller/Entities/BasePluginFolder.cs +++ b/MediaBrowser.Controller/Entities/BasePluginFolder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Text.Json.Serialization; diff --git a/MediaBrowser.Controller/Entities/Book.cs b/MediaBrowser.Controller/Entities/Book.cs index 55945283c9..3d0370248e 100644 --- a/MediaBrowser.Controller/Entities/Book.cs +++ b/MediaBrowser.Controller/Entities/Book.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index bc5f38256c..a86da29ce4 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Extensions.cs b/MediaBrowser.Controller/Entities/Extensions.cs index 3a34c668cf..244cc00bea 100644 --- a/MediaBrowser.Controller/Entities/Extensions.cs +++ b/MediaBrowser.Controller/Entities/Extensions.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Linq; using MediaBrowser.Common.Extensions; diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index d74e6f9d8c..a59f5c6e4b 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 74a1702040..7987f38a07 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/ICollectionFolder.cs b/MediaBrowser.Controller/Entities/ICollectionFolder.cs index b84a9fa6f1..2304570fd7 100644 --- a/MediaBrowser.Controller/Entities/ICollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/ICollectionFolder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/IHasAspectRatio.cs b/MediaBrowser.Controller/Entities/IHasAspectRatio.cs index d7d0076681..3aeb7468f2 100644 --- a/MediaBrowser.Controller/Entities/IHasAspectRatio.cs +++ b/MediaBrowser.Controller/Entities/IHasAspectRatio.cs @@ -1,3 +1,5 @@ +#nullable disable + namespace MediaBrowser.Controller.Entities { /// diff --git a/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs b/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs index 13226b2346..14459624e9 100644 --- a/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs +++ b/MediaBrowser.Controller/Entities/IHasDisplayOrder.cs @@ -1,3 +1,5 @@ +#nullable disable + namespace MediaBrowser.Controller.Entities { /// diff --git a/MediaBrowser.Controller/Entities/IHasMediaSources.cs b/MediaBrowser.Controller/Entities/IHasMediaSources.cs index 0f612262a8..98c3b3edf6 100644 --- a/MediaBrowser.Controller/Entities/IHasMediaSources.cs +++ b/MediaBrowser.Controller/Entities/IHasMediaSources.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs b/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs index f747b5149a..f80f7c304c 100644 --- a/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs +++ b/MediaBrowser.Controller/Entities/IHasProgramAttributes.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.LiveTv; diff --git a/MediaBrowser.Controller/Entities/IHasSeries.cs b/MediaBrowser.Controller/Entities/IHasSeries.cs index 5444f1f523..64d769d5ba 100644 --- a/MediaBrowser.Controller/Entities/IHasSeries.cs +++ b/MediaBrowser.Controller/Entities/IHasSeries.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs b/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs index 6a350212b1..f317a02ff3 100644 --- a/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs +++ b/MediaBrowser.Controller/Entities/IHasSpecialFeatures.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/IHasTrailers.cs b/MediaBrowser.Controller/Entities/IHasTrailers.cs index d1f6f2b7e2..2bd9ded337 100644 --- a/MediaBrowser.Controller/Entities/IHasTrailers.cs +++ b/MediaBrowser.Controller/Entities/IHasTrailers.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 270217356f..c060210296 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs index 5b96a5af65..b2d6a46091 100644 --- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/ItemImageInfo.cs b/MediaBrowser.Controller/Entities/ItemImageInfo.cs index 570d8eec0c..ea8555dbfe 100644 --- a/MediaBrowser.Controller/Entities/ItemImageInfo.cs +++ b/MediaBrowser.Controller/Entities/ItemImageInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/LinkedChild.cs b/MediaBrowser.Controller/Entities/LinkedChild.cs index 8e0f721e77..01c0a93393 100644 --- a/MediaBrowser.Controller/Entities/LinkedChild.cs +++ b/MediaBrowser.Controller/Entities/LinkedChild.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index 507f400f12..74e84288d1 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 8b67aaccc6..64d60c2e90 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index b278a01423..f42e7723c3 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index c4fcb0267a..d9ff55362c 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/PersonInfo.cs b/MediaBrowser.Controller/Entities/PersonInfo.cs index 4ff9b0955c..fb79323f8f 100644 --- a/MediaBrowser.Controller/Entities/PersonInfo.cs +++ b/MediaBrowser.Controller/Entities/PersonInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Photo.cs b/MediaBrowser.Controller/Entities/Photo.cs index 0f82f742fd..3312a0e3e2 100644 --- a/MediaBrowser.Controller/Entities/Photo.cs +++ b/MediaBrowser.Controller/Entities/Photo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Text.Json.Serialization; diff --git a/MediaBrowser.Controller/Entities/Share.cs b/MediaBrowser.Controller/Entities/Share.cs index 50f1655f39..7e4ec18307 100644 --- a/MediaBrowser.Controller/Entities/Share.cs +++ b/MediaBrowser.Controller/Entities/Share.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Entities diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index 9018ddb75e..ae1d10447b 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 70663ef478..2724bd9b3d 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index 5b8168d3d6..ad3e0fe8d6 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 06a405121c..ded825abc0 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs index 9ae8ad7087..b086b5906b 100644 --- a/MediaBrowser.Controller/Entities/Trailer.cs +++ b/MediaBrowser.Controller/Entities/Trailer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/UserItemData.cs b/MediaBrowser.Controller/Entities/UserItemData.cs index db63c42e4c..f60359c014 100644 --- a/MediaBrowser.Controller/Entities/UserItemData.cs +++ b/MediaBrowser.Controller/Entities/UserItemData.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs index 7f7224ae07..e492740ed0 100644 --- a/MediaBrowser.Controller/Entities/UserRootFolder.cs +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index fec83dd941..0dfde27667 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 78a64d8c95..15a4573c2e 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 6320b01b87..723027a883 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index b2e4d307a6..4d84a151a7 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Events/IEventConsumer.cs b/MediaBrowser.Controller/Events/IEventConsumer.cs index 5c4ab5d8dd..93005134a7 100644 --- a/MediaBrowser.Controller/Events/IEventConsumer.cs +++ b/MediaBrowser.Controller/Events/IEventConsumer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; namespace MediaBrowser.Controller.Events diff --git a/MediaBrowser.Controller/Events/IEventManager.cs b/MediaBrowser.Controller/Events/IEventManager.cs index a1f40b3a6d..074e3f1fe4 100644 --- a/MediaBrowser.Controller/Events/IEventManager.cs +++ b/MediaBrowser.Controller/Events/IEventManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; namespace MediaBrowser.Controller.Events diff --git a/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs b/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs index 46d7e5a17a..3a331ad00f 100644 --- a/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs +++ b/MediaBrowser.Controller/Events/Session/SessionEndedEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.Events.Session diff --git a/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs b/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs index aab19cc46a..deeaaf55de 100644 --- a/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs +++ b/MediaBrowser.Controller/Events/Session/SessionStartedEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.Events.Session diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs index b06046c05a..0dd8b0dbfd 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginInstallationCancelledEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Model.Updates; namespace MediaBrowser.Controller.Events.Updates diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs index dfadc9f61f..c1d503a7eb 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginInstalledEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Model.Updates; namespace MediaBrowser.Controller.Events.Updates diff --git a/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs index 045a600272..7a9866834a 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginInstallingEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Model.Updates; namespace MediaBrowser.Controller.Events.Updates diff --git a/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs b/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs index 661ca066a8..b078e06dc8 100644 --- a/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs +++ b/MediaBrowser.Controller/Events/Updates/PluginUpdatedEventArgs.cs @@ -1,4 +1,4 @@ -using Jellyfin.Data.Events; +using Jellyfin.Data.Events; using MediaBrowser.Model.Updates; namespace MediaBrowser.Controller.Events.Updates diff --git a/MediaBrowser.Controller/Extensions/StringExtensions.cs b/MediaBrowser.Controller/Extensions/StringExtensions.cs index 182c8ef658..8441a31713 100644 --- a/MediaBrowser.Controller/Extensions/StringExtensions.cs +++ b/MediaBrowser.Controller/Extensions/StringExtensions.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/IDisplayPreferencesManager.cs b/MediaBrowser.Controller/IDisplayPreferencesManager.cs index be1d974a47..1678d50675 100644 --- a/MediaBrowser.Controller/IDisplayPreferencesManager.cs +++ b/MediaBrowser.Controller/IDisplayPreferencesManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using Jellyfin.Data.Entities; diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 6a65a8e47a..0949238426 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/IServerApplicationPaths.cs b/MediaBrowser.Controller/IServerApplicationPaths.cs index be57d6bcae..1890dbb360 100644 --- a/MediaBrowser.Controller/IServerApplicationPaths.cs +++ b/MediaBrowser.Controller/IServerApplicationPaths.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Common.Configuration; diff --git a/MediaBrowser.Controller/Library/IIntroProvider.cs b/MediaBrowser.Controller/Library/IIntroProvider.cs index d45493d404..3bb1bd9a09 100644 --- a/MediaBrowser.Controller/Library/IIntroProvider.cs +++ b/MediaBrowser.Controller/Library/IIntroProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using System.Threading.Tasks; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 6d9b568da8..782e153982 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/ILiveStream.cs b/MediaBrowser.Controller/Library/ILiveStream.cs index ff25be6577..85d866de5c 100644 --- a/MediaBrowser.Controller/Library/ILiveStream.cs +++ b/MediaBrowser.Controller/Library/ILiveStream.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Threading; diff --git a/MediaBrowser.Controller/Library/IMediaSourceManager.cs b/MediaBrowser.Controller/Library/IMediaSourceManager.cs index 21c6ef2af1..d3d85a0563 100644 --- a/MediaBrowser.Controller/Library/IMediaSourceManager.cs +++ b/MediaBrowser.Controller/Library/IMediaSourceManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/IMetadataSaver.cs b/MediaBrowser.Controller/Library/IMetadataSaver.cs index 027cc5b40e..5fbfad8814 100644 --- a/MediaBrowser.Controller/Library/IMetadataSaver.cs +++ b/MediaBrowser.Controller/Library/IMetadataSaver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Library/IMusicManager.cs b/MediaBrowser.Controller/Library/IMusicManager.cs index d12f008e77..5329841bf5 100644 --- a/MediaBrowser.Controller/Library/IMusicManager.cs +++ b/MediaBrowser.Controller/Library/IMusicManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Library/IUserDataManager.cs b/MediaBrowser.Controller/Library/IUserDataManager.cs index c6a83e4dc4..58499e8531 100644 --- a/MediaBrowser.Controller/Library/IUserDataManager.cs +++ b/MediaBrowser.Controller/Library/IUserDataManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/IUserManager.cs b/MediaBrowser.Controller/Library/IUserManager.cs index 6e267834b0..c95b0ea321 100644 --- a/MediaBrowser.Controller/Library/IUserManager.cs +++ b/MediaBrowser.Controller/Library/IUserManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/IUserViewManager.cs b/MediaBrowser.Controller/Library/IUserViewManager.cs index 8d541e8b68..46004e42f7 100644 --- a/MediaBrowser.Controller/Library/IUserViewManager.cs +++ b/MediaBrowser.Controller/Library/IUserViewManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/IntroInfo.cs b/MediaBrowser.Controller/Library/IntroInfo.cs index 283cc631ca..90786786b2 100644 --- a/MediaBrowser.Controller/Library/IntroInfo.cs +++ b/MediaBrowser.Controller/Library/IntroInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs b/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs index 1798a4fada..a37dc7af11 100644 --- a/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs +++ b/MediaBrowser.Controller/Library/ItemChangeEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Library/ItemResolveArgs.cs b/MediaBrowser.Controller/Library/ItemResolveArgs.cs index 5f9aed3416..0e2d8fb021 100644 --- a/MediaBrowser.Controller/Library/ItemResolveArgs.cs +++ b/MediaBrowser.Controller/Library/ItemResolveArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs b/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs index 9581603f04..7bc8fa5abd 100644 --- a/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs +++ b/MediaBrowser.Controller/Library/LibraryManagerExtensions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs index 884f9e7735..41cfcae163 100644 --- a/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs +++ b/MediaBrowser.Controller/Library/MetadataConfigurationExtensions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Common.Configuration; diff --git a/MediaBrowser.Controller/Library/NameExtensions.cs b/MediaBrowser.Controller/Library/NameExtensions.cs index 6e79dc8ddf..29bfeca097 100644 --- a/MediaBrowser.Controller/Library/NameExtensions.cs +++ b/MediaBrowser.Controller/Library/NameExtensions.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs b/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs index a2be3a42ab..609336ec4d 100644 --- a/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs +++ b/MediaBrowser.Controller/Library/PlaybackProgressEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs b/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs index ac372bceba..2138fef580 100644 --- a/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs +++ b/MediaBrowser.Controller/Library/PlaybackStartEventArgs.cs @@ -1,4 +1,4 @@ -namespace MediaBrowser.Controller.Library +namespace MediaBrowser.Controller.Library { /// /// An event that occurs when playback is started. diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs index 5efdc6a481..8f42d37061 100644 --- a/MediaBrowser.Controller/Library/Profiler.cs +++ b/MediaBrowser.Controller/Library/Profiler.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Diagnostics; using System.Globalization; diff --git a/MediaBrowser.Controller/Library/SearchHintInfo.cs b/MediaBrowser.Controller/Library/SearchHintInfo.cs index 897c2b7f49..de7806adc3 100644 --- a/MediaBrowser.Controller/Library/SearchHintInfo.cs +++ b/MediaBrowser.Controller/Library/SearchHintInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Entities; namespace MediaBrowser.Controller.Library diff --git a/MediaBrowser.Controller/Library/TVUtils.cs b/MediaBrowser.Controller/Library/TVUtils.cs index a3aa6019ec..8cbfc78aad 100644 --- a/MediaBrowser.Controller/Library/TVUtils.cs +++ b/MediaBrowser.Controller/Library/TVUtils.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace MediaBrowser.Controller.Library { @@ -12,7 +13,8 @@ namespace MediaBrowser.Controller.Library /// /// The day. /// List{DayOfWeek}. - public static DayOfWeek[] GetAirDays(string day) + [return: NotNullIfNotNull("day")] + public static DayOfWeek[] GetAirDays(string? day) { if (!string.IsNullOrEmpty(day)) { diff --git a/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs b/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs index cd91097535..bfe433c971 100644 --- a/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs +++ b/MediaBrowser.Controller/Library/UserDataSaveEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs index 166c4d77c0..a55fd670d5 100644 --- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.LiveTv; diff --git a/MediaBrowser.Controller/LiveTv/IListingsProvider.cs b/MediaBrowser.Controller/LiveTv/IListingsProvider.cs index 038ff2eaeb..2bd4b20e8c 100644 --- a/MediaBrowser.Controller/LiveTv/IListingsProvider.cs +++ b/MediaBrowser.Controller/LiveTv/IListingsProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs index 54495c1c40..c28e0426b5 100644 --- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs +++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvService.cs b/MediaBrowser.Controller/LiveTv/ILiveTvService.cs index 3ca1d165ef..897f263f3d 100644 --- a/MediaBrowser.Controller/LiveTv/ILiveTvService.cs +++ b/MediaBrowser.Controller/LiveTv/ILiveTvService.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/ITunerHost.cs b/MediaBrowser.Controller/LiveTv/ITunerHost.cs index abca8f2390..7dced9f5ef 100644 --- a/MediaBrowser.Controller/LiveTv/ITunerHost.cs +++ b/MediaBrowser.Controller/LiveTv/ITunerHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs index ec933caf34..51e56f4b5e 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index 43af495dd6..d9634a731f 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs index b629749049..eb3babc180 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvServiceStatusInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs b/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs index 739978e7ce..aa5eb59d16 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvTunerInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs index f9f559ee96..4a977c5cc3 100644 --- a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs index 69190694ff..00135afa81 100644 --- a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs +++ b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs b/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs index 847c0ea8c0..0b943c9396 100644 --- a/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs +++ b/MediaBrowser.Controller/LiveTv/RecordingStatusChangedEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs index 1343ecd982..1bb649a991 100644 --- a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs b/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs index 1b8f41db69..728387c56d 100644 --- a/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs +++ b/MediaBrowser.Controller/LiveTv/TimerEventInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #nullable enable #pragma warning disable CS1591 diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs index aa5170617d..e54dc967ca 100644 --- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs b/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs index 2759b314f5..1c1a4417dc 100644 --- a/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs +++ b/MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.LiveTv diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 8c68b47dd7..37ce35fc27 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -34,6 +34,7 @@ false true true + enable AllEnabledByDefault ../jellyfin.ruleset true diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 2b53647758..97cb8d63ba 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index d47a689f47..1e13382b75 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs index 1f3abe8f43..88de5b2925 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs index fbc8275341..c38e7ec3b3 100644 --- a/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs +++ b/MediaBrowser.Controller/MediaEncoding/IAttachmentExtractor.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.IO; diff --git a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs index 15a2580afd..773547872c 100644 --- a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs +++ b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 05dd1a69b1..d3260280a5 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs b/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs index 6ebf7f159b..3fb2c47e13 100644 --- a/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/ISubtitleEncoder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.IO; diff --git a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs index e7b4c8c15c..044ba6d331 100644 --- a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.MediaEncoding diff --git a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs index 227c5f2587..aa5e2c4038 100644 --- a/MediaBrowser.Controller/MediaEncoding/JobLogger.cs +++ b/MediaBrowser.Controller/MediaEncoding/JobLogger.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs index 89e01c08b6..841e7b2872 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 - namespace MediaBrowser.Controller.MediaEncoding { /// diff --git a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs index 2cb04bdc4f..1dd8bcf31b 100644 --- a/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs +++ b/MediaBrowser.Controller/MediaEncoding/MediaInfoRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.Dlna; diff --git a/MediaBrowser.Controller/Net/AuthorizationInfo.cs b/MediaBrowser.Controller/Net/AuthorizationInfo.cs index 93573e08e2..2452b25ab1 100644 --- a/MediaBrowser.Controller/Net/AuthorizationInfo.cs +++ b/MediaBrowser.Controller/Net/AuthorizationInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using Jellyfin.Data.Entities; diff --git a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs index 163a9c8f86..855467e8e3 100644 --- a/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs +++ b/MediaBrowser.Controller/Net/BasePeriodicWebSocketListener.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Net/IAuthService.cs b/MediaBrowser.Controller/Net/IAuthService.cs index 04b2e13e8c..d15c6d3183 100644 --- a/MediaBrowser.Controller/Net/IAuthService.cs +++ b/MediaBrowser.Controller/Net/IAuthService.cs @@ -1,5 +1,3 @@ -#nullable enable - using Microsoft.AspNetCore.Http; namespace MediaBrowser.Controller.Net diff --git a/MediaBrowser.Controller/Net/IWebSocketConnection.cs b/MediaBrowser.Controller/Net/IWebSocketConnection.cs index e87f3bca68..5e9fce5503 100644 --- a/MediaBrowser.Controller/Net/IWebSocketConnection.cs +++ b/MediaBrowser.Controller/Net/IWebSocketConnection.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 #nullable enable diff --git a/MediaBrowser.Controller/Net/SecurityException.cs b/MediaBrowser.Controller/Net/SecurityException.cs index c6347133a8..f0d0b45a0a 100644 --- a/MediaBrowser.Controller/Net/SecurityException.cs +++ b/MediaBrowser.Controller/Net/SecurityException.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; namespace MediaBrowser.Controller.Net diff --git a/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs b/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs index be0b3ddc3f..6f7ebf1565 100644 --- a/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs +++ b/MediaBrowser.Controller/Net/WebSocketMessageInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Model.Net; namespace MediaBrowser.Controller.Net diff --git a/MediaBrowser.Controller/Notifications/INotificationManager.cs b/MediaBrowser.Controller/Notifications/INotificationManager.cs index 08d9bc12a2..7caba1097a 100644 --- a/MediaBrowser.Controller/Notifications/INotificationManager.cs +++ b/MediaBrowser.Controller/Notifications/INotificationManager.cs @@ -19,7 +19,7 @@ namespace MediaBrowser.Controller.Notifications /// Task. Task SendNotification(NotificationRequest request, CancellationToken cancellationToken); - Task SendNotification(NotificationRequest request, BaseItem relatedItem, CancellationToken cancellationToken); + Task SendNotification(NotificationRequest request, BaseItem? relatedItem, CancellationToken cancellationToken); /// /// Adds the parts. diff --git a/MediaBrowser.Controller/Notifications/INotificationService.cs b/MediaBrowser.Controller/Notifications/INotificationService.cs index fa947220ad..535c08795b 100644 --- a/MediaBrowser.Controller/Notifications/INotificationService.cs +++ b/MediaBrowser.Controller/Notifications/INotificationService.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Threading; diff --git a/MediaBrowser.Controller/Notifications/UserNotification.cs b/MediaBrowser.Controller/Notifications/UserNotification.cs index d768abfe73..4be0e09ae7 100644 --- a/MediaBrowser.Controller/Notifications/UserNotification.cs +++ b/MediaBrowser.Controller/Notifications/UserNotification.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs index ed473c7492..56fb36af2a 100644 --- a/MediaBrowser.Controller/Persistence/IItemRepository.cs +++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Persistence/IUserDataRepository.cs b/MediaBrowser.Controller/Persistence/IUserDataRepository.cs index 81ba513cef..6f5f02123e 100644 --- a/MediaBrowser.Controller/Persistence/IUserDataRepository.cs +++ b/MediaBrowser.Controller/Persistence/IUserDataRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using System.Threading; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index 3c93cfc79c..a80c116439 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs b/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs deleted file mode 100644 index bf15fe0407..0000000000 --- a/MediaBrowser.Controller/Plugins/ILocalizablePlugin.cs +++ /dev/null @@ -1,22 +0,0 @@ -#pragma warning disable CS1591 - -using System.IO; -using System.Reflection; - -namespace MediaBrowser.Controller.Plugins -{ - public interface ILocalizablePlugin - { - Stream GetDictionary(string culture); - } - - public static class LocalizablePluginHelper - { - public static Stream GetDictionary(Assembly assembly, string manifestPrefix, string culture) - { - // Find all dictionaries using GetManifestResourceNames, start start with the prefix - // Return the one for the culture if exists, otherwise return the default - return null; - } - } -} diff --git a/MediaBrowser.Controller/Providers/BookInfo.cs b/MediaBrowser.Controller/Providers/BookInfo.cs index cce0a25fcb..3055c5d871 100644 --- a/MediaBrowser.Controller/Providers/BookInfo.cs +++ b/MediaBrowser.Controller/Providers/BookInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Providers diff --git a/MediaBrowser.Controller/Providers/DynamicImageResponse.cs b/MediaBrowser.Controller/Providers/DynamicImageResponse.cs index 006174be8c..66fddb0e38 100644 --- a/MediaBrowser.Controller/Providers/DynamicImageResponse.cs +++ b/MediaBrowser.Controller/Providers/DynamicImageResponse.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/EpisodeInfo.cs b/MediaBrowser.Controller/Providers/EpisodeInfo.cs index a4c8dab7ea..341bf69361 100644 --- a/MediaBrowser.Controller/Providers/EpisodeInfo.cs +++ b/MediaBrowser.Controller/Providers/EpisodeInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/IExternalId.cs b/MediaBrowser.Controller/Providers/IExternalId.cs index 5e38446bc9..e2dbef2bc1 100644 --- a/MediaBrowser.Controller/Providers/IExternalId.cs +++ b/MediaBrowser.Controller/Providers/IExternalId.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Model.Entities; using MediaBrowser.Model.Providers; diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 7bc56c82ad..b4d91f396f 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs index 9fc379f045..81a22affb0 100644 --- a/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/ImageRefreshOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/ItemInfo.cs b/MediaBrowser.Controller/Providers/ItemInfo.cs index 3a97127eaa..b8dd416a2d 100644 --- a/MediaBrowser.Controller/Providers/ItemInfo.cs +++ b/MediaBrowser.Controller/Providers/ItemInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs index b777cc1d31..f16669a781 100644 --- a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs +++ b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/LocalImageInfo.cs b/MediaBrowser.Controller/Providers/LocalImageInfo.cs index 41801862fd..a8e70e6d08 100644 --- a/MediaBrowser.Controller/Providers/LocalImageInfo.cs +++ b/MediaBrowser.Controller/Providers/LocalImageInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.Entities; diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index db0ef70728..5afc358ba7 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/MetadataResult.cs b/MediaBrowser.Controller/Providers/MetadataResult.cs index 98c7eadfe0..8b0967a6e6 100644 --- a/MediaBrowser.Controller/Providers/MetadataResult.cs +++ b/MediaBrowser.Controller/Providers/MetadataResult.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/MusicVideoInfo.cs b/MediaBrowser.Controller/Providers/MusicVideoInfo.cs index 0b927f6eb0..322320abdf 100644 --- a/MediaBrowser.Controller/Providers/MusicVideoInfo.cs +++ b/MediaBrowser.Controller/Providers/MusicVideoInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs index 9653bc1c4a..d830231cfb 100644 --- a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs +++ b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Providers/SongInfo.cs b/MediaBrowser.Controller/Providers/SongInfo.cs index 58f76dca91..c90717a2e1 100644 --- a/MediaBrowser.Controller/Providers/SongInfo.cs +++ b/MediaBrowser.Controller/Providers/SongInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs b/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs index 959a2d7712..c4e709c245 100644 --- a/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs +++ b/MediaBrowser.Controller/QuickConnect/IQuickConnect.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Model.QuickConnect; diff --git a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs index a904c74240..e77593a036 100644 --- a/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs +++ b/MediaBrowser.Controller/Resolvers/BaseItemResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; diff --git a/MediaBrowser.Controller/Security/AuthenticationInfo.cs b/MediaBrowser.Controller/Security/AuthenticationInfo.cs index efac9273ec..b4b242f1b2 100644 --- a/MediaBrowser.Controller/Security/AuthenticationInfo.cs +++ b/MediaBrowser.Controller/Security/AuthenticationInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs b/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs index c5f3da0b1b..3af6a525c7 100644 --- a/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs +++ b/MediaBrowser.Controller/Security/AuthenticationInfoQuery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Security/IAuthenticationRepository.cs b/MediaBrowser.Controller/Security/IAuthenticationRepository.cs index 883b74165c..1dd69ccd85 100644 --- a/MediaBrowser.Controller/Security/IAuthenticationRepository.cs +++ b/MediaBrowser.Controller/Security/IAuthenticationRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.Devices; diff --git a/MediaBrowser.Controller/Session/AuthenticationRequest.cs b/MediaBrowser.Controller/Session/AuthenticationRequest.cs index 8c3ac58f2b..647c75e66e 100644 --- a/MediaBrowser.Controller/Session/AuthenticationRequest.cs +++ b/MediaBrowser.Controller/Session/AuthenticationRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Session/ISessionController.cs b/MediaBrowser.Controller/Session/ISessionController.cs index bc4ccd44ca..6bc39d6f4e 100644 --- a/MediaBrowser.Controller/Session/ISessionController.cs +++ b/MediaBrowser.Controller/Session/ISessionController.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 6c06dcad58..7eda49c602 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Session/SessionEventArgs.cs b/MediaBrowser.Controller/Session/SessionEventArgs.cs index 097e32eaec..269fe7dc4d 100644 --- a/MediaBrowser.Controller/Session/SessionEventArgs.cs +++ b/MediaBrowser.Controller/Session/SessionEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index d09852870e..5da3783bf8 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Sorting/AlphanumComparator.cs b/MediaBrowser.Controller/Sorting/AlphanumComparator.cs index 70cb9eebe0..4d9b98889f 100644 --- a/MediaBrowser.Controller/Sorting/AlphanumComparator.cs +++ b/MediaBrowser.Controller/Sorting/AlphanumComparator.cs @@ -1,7 +1,5 @@ #pragma warning disable CS1591 -#nullable enable - using System; using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs index 6d03d97ae3..bd47db39a6 100644 --- a/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs +++ b/MediaBrowser.Controller/Sorting/IUserBaseItemComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Library; namespace MediaBrowser.Controller.Sorting diff --git a/MediaBrowser.Controller/Sorting/SortExtensions.cs b/MediaBrowser.Controller/Sorting/SortExtensions.cs index 88467814cd..aa6ec513f3 100644 --- a/MediaBrowser.Controller/Sorting/SortExtensions.cs +++ b/MediaBrowser.Controller/Sorting/SortExtensions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs index 6d63286ef5..9e661cbe42 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs b/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs index a633262de9..326348d583 100644 --- a/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs +++ b/MediaBrowser.Controller/Subtitles/ISubtitleProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs b/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs index ce8141219a..c782f57961 100644 --- a/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs +++ b/MediaBrowser.Controller/Subtitles/SubtitleDownloadFailureEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Controller.Entities; diff --git a/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs b/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs index a86b057783..85b3e6fbd7 100644 --- a/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs +++ b/MediaBrowser.Controller/Subtitles/SubtitleResponse.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.IO; diff --git a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs index 7d3c20e8f1..0f7c47e767 100644 --- a/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs +++ b/MediaBrowser.Controller/Subtitles/SubtitleSearchRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs b/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs index e7395b136d..3d3e44da01 100644 --- a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs +++ b/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Threading; diff --git a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs b/MediaBrowser.Controller/Sync/IServerSyncProvider.cs index c97fd70442..3891ac0a66 100644 --- a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs +++ b/MediaBrowser.Controller/Sync/IServerSyncProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.Controller/Sync/ISyncProvider.cs b/MediaBrowser.Controller/Sync/ISyncProvider.cs index 950cc73e85..ea20014c79 100644 --- a/MediaBrowser.Controller/Sync/ISyncProvider.cs +++ b/MediaBrowser.Controller/Sync/ISyncProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs b/MediaBrowser.Controller/Sync/SyncedFileInfo.cs index a626738fb2..7eac52299b 100644 --- a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs +++ b/MediaBrowser.Controller/Sync/SyncedFileInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.Controller/SyncPlay/GroupMember.cs b/MediaBrowser.Controller/SyncPlay/GroupMember.cs index 5fb982e85a..7e7e759a51 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupMember.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupMember.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Session; namespace MediaBrowser.Controller.SyncPlay diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs index e3de22db38..91a13fb28e 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/AbstractGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs index 12ce6c8f82..6b5a7cdf9a 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/IdleGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs index fba8ba9e2e..b9786ddb08 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PausedGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs index 9797b247ce..cb1cadf0bc 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/PlayingGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs index 507573653f..a0c38b3097 100644 --- a/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/GroupStates/WaitingGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs index 201f29952f..9045063eed 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupPlaybackRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/IGroupState.cs b/MediaBrowser.Controller/SyncPlay/IGroupState.cs index 95ee09985f..0666a62a85 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupState.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupState.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Controller.SyncPlay.PlaybackRequests; diff --git a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs index aa263638aa..de26c7d9ef 100644 --- a/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs +++ b/MediaBrowser.Controller/SyncPlay/IGroupStateContext.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs index 1c954828c3..a6999a12c9 100644 --- a/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs +++ b/MediaBrowser.Controller/SyncPlay/ISyncPlayManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs index 4090f65b9c..ef496c1038 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/AbstractPlaybackRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs index 11cc99fcda..d188114c34 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/BufferGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs index 64ef791ed7..464c81dfd2 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/IgnoreWaitGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs index 9cd8da5668..be314e807b 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/MovePlaylistItemGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs index e0ae0deb76..679076239e 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/NextItemGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs index 2869b35f77..7ee18a3666 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PauseGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs index 8ef3b20303..beab655c59 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PingGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs index 16f9b40874..05ff262c1e 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PlayGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs index 166ee08007..3e34b6ce46 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/PreviousItemGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs index d4af63b6d4..0f91476de1 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/QueueGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs index 74f01cbeaf..b1f0bd3602 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/ReadyGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs index 47c06c2227..6891452934 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/RemoveFromPlaylistGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Threading; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs index ecaa689ae3..1961133749 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SeekGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs index c3451703ed..44df127a6f 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetPlaylistItemGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Controller.Session; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs index 51011672ea..d250eab56e 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetRepeatModeGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs index d7b2504b4b..5034e992eb 100644 --- a/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs +++ b/MediaBrowser.Controller/SyncPlay/PlaybackRequests/SetShuffleModeGroupRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Threading; using MediaBrowser.Controller.Session; using MediaBrowser.Model.SyncPlay; diff --git a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs index fdec29417e..b8ae9f3ff6 100644 --- a/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs +++ b/MediaBrowser.Controller/SyncPlay/Queue/PlayQueueManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Linq; diff --git a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs index 2d3b2d889c..bc62ca4d53 100644 --- a/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/EpisodeLocalImageProvider.cs @@ -42,6 +42,10 @@ namespace MediaBrowser.LocalMetadata.Images public IEnumerable GetImages(BaseItem item, IDirectoryService directoryService) { var parentPath = Path.GetDirectoryName(item.Path); + if (parentPath == null) + { + return Enumerable.Empty(); + } var parentPathFiles = directoryService.GetFiles(parentPath); From 4367b97a54f31233e242ef1afe6714b934ecf4d9 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 7 May 2021 00:52:06 +0200 Subject: [PATCH 1585/1930] Fix build --- .../Library/ResolverHelper.cs | 5 +++++ MediaBrowser.Controller/Library/TVUtils.cs | 2 +- .../Providers/DirectoryService.cs | 19 +++++++++---------- .../Providers/IDirectoryService.cs | 2 +- MediaBrowser.LocalMetadata/BaseXmlProvider.cs | 2 +- .../Providers/BoxSetXmlProvider.cs | 2 +- .../Providers/PlaylistXmlProvider.cs | 2 +- .../Providers/AlbumNfoProvider.cs | 2 +- .../Providers/ArtistNfoProvider.cs | 2 +- .../Providers/EpisodeNfoProvider.cs | 2 +- .../Providers/SeasonNfoProvider.cs | 2 +- .../Providers/SeriesNfoProvider.cs | 2 +- 12 files changed, 24 insertions(+), 20 deletions(-) diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs index b1a2e92847..1d9b448741 100644 --- a/Emby.Server.Implementations/Library/ResolverHelper.cs +++ b/Emby.Server.Implementations/Library/ResolverHelper.cs @@ -44,6 +44,11 @@ namespace Emby.Server.Implementations.Library // Make sure DateCreated and DateModified have values var fileInfo = directoryService.GetFile(item.Path); + if (fileInfo == null) + { + throw new FileNotFoundException("Can't find item path.", item.Path); + } + SetDateCreated(item, fileInfo); EnsureName(item, fileInfo); diff --git a/MediaBrowser.Controller/Library/TVUtils.cs b/MediaBrowser.Controller/Library/TVUtils.cs index 8cbfc78aad..968338dc6a 100644 --- a/MediaBrowser.Controller/Library/TVUtils.cs +++ b/MediaBrowser.Controller/Library/TVUtils.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Controller.Library /// The day. /// List{DayOfWeek}. [return: NotNullIfNotNull("day")] - public static DayOfWeek[] GetAirDays(string? day) + public static DayOfWeek[]? GetAirDays(string? day) { if (!string.IsNullOrEmpty(day)) { diff --git a/MediaBrowser.Controller/Providers/DirectoryService.cs b/MediaBrowser.Controller/Providers/DirectoryService.cs index 5c92069b44..291a268830 100644 --- a/MediaBrowser.Controller/Providers/DirectoryService.cs +++ b/MediaBrowser.Controller/Providers/DirectoryService.cs @@ -43,18 +43,17 @@ namespace MediaBrowser.Controller.Providers return list; } - public FileSystemMetadata GetFile(string path) + public FileSystemMetadata? GetFile(string path) { - var result = _fileCache.GetOrAdd(path, p => + if (!_fileCache.TryGetValue(path, out var result)) { - var file = _fileSystem.GetFileInfo(p); - return file != null && file.Exists ? file : null; - }); - - if (result == null) - { - // lets not store null results in the cache - _fileCache.TryRemove(path, out _); + var file = _fileSystem.GetFileInfo(path); + var res = file != null && file.Exists ? file : null; + if (res != null) + { + result = res; + _fileCache.TryAdd(path, result); + } } return result; diff --git a/MediaBrowser.Controller/Providers/IDirectoryService.cs b/MediaBrowser.Controller/Providers/IDirectoryService.cs index f06481c7a9..9cee06a4c6 100644 --- a/MediaBrowser.Controller/Providers/IDirectoryService.cs +++ b/MediaBrowser.Controller/Providers/IDirectoryService.cs @@ -11,7 +11,7 @@ namespace MediaBrowser.Controller.Providers List GetFiles(string path); - FileSystemMetadata GetFile(string path); + FileSystemMetadata? GetFile(string path); IReadOnlyList GetFilePaths(string path); diff --git a/MediaBrowser.LocalMetadata/BaseXmlProvider.cs b/MediaBrowser.LocalMetadata/BaseXmlProvider.cs index b036a2cc84..9f8e921b4b 100644 --- a/MediaBrowser.LocalMetadata/BaseXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/BaseXmlProvider.cs @@ -91,7 +91,7 @@ namespace MediaBrowser.LocalMetadata /// Item inf. /// Instance of the interface. /// The file system metadata. - protected abstract FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService); + protected abstract FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService); /// public bool HasChanged(BaseItem item, IDirectoryService directoryService) diff --git a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs index cc705a9dfa..ea123bbf22 100644 --- a/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/BoxSetXmlProvider.cs @@ -36,7 +36,7 @@ namespace MediaBrowser.LocalMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) { return directoryService.GetFile(Path.Combine(info.Path, "collection.xml")); } diff --git a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs index 36f3048ad5..8990356521 100644 --- a/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs +++ b/MediaBrowser.LocalMetadata/Providers/PlaylistXmlProvider.cs @@ -39,7 +39,7 @@ namespace MediaBrowser.LocalMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) { return directoryService.GetFile(PlaylistXmlSaver.GetSavePath(info.Path)); } diff --git a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs index bd557d783c..f7a85a07e6 100644 --- a/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/AlbumNfoProvider.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) => directoryService.GetFile(Path.Combine(info.Path, "album.nfo")); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs index 54bb83114b..2b563b7fa6 100644 --- a/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/ArtistNfoProvider.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) => directoryService.GetFile(Path.Combine(info.Path, "artist.nfo")); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs index 64b208345e..f6c5877b40 100644 --- a/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/EpisodeNfoProvider.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) { var path = Path.ChangeExtension(info.Path, ".nfo"); diff --git a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs index 97220cf7ea..d01abadf67 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeasonNfoProvider.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) => directoryService.GetFile(Path.Combine(info.Path, "season.nfo")); } } diff --git a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs index 9a9b941236..002b944631 100644 --- a/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs +++ b/MediaBrowser.XbmcMetadata/Providers/SeriesNfoProvider.cs @@ -57,7 +57,7 @@ namespace MediaBrowser.XbmcMetadata.Providers } /// - protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService) + protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) => directoryService.GetFile(Path.Combine(info.Path, "tvshow.nfo")); } } From bc017737e678c62a1573fa9c8820fc4fd2b97405 Mon Sep 17 00:00:00 2001 From: Jake King Date: Fri, 7 May 2021 10:35:03 +0100 Subject: [PATCH 1586/1930] Changed condition for readbility - Refactored check if item is not audio book or book to be more readable --- Emby.Server.Implementations/Library/UserDataManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index d7e4e2af7f..47f881f73b 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -220,7 +220,7 @@ namespace Emby.Server.Implementations.Library var hasRuntime = runtimeTicks > 0; // If a position has been reported, and if we know the duration - if (positionTicks > 0 && hasRuntime && !(item is AudioBook) && !(item is Book)) + if (positionTicks > 0 && hasRuntime && item is not AudioBook && item is not Book) { var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100; From 06caee28b7f81fb6898a771df5a5064fdf94891d Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 7 May 2021 14:43:50 +0200 Subject: [PATCH 1587/1930] Enable nullable reference types for Emby.Dlna --- Emby.Dlna/Configuration/DlnaOptions.cs | 2 ++ Emby.Dlna/ConfigurationExtension.cs | 1 - .../ContentDirectory/ContentDirectoryService.cs | 2 ++ Emby.Dlna/ContentDirectory/ControlHandler.cs | 2 ++ Emby.Dlna/ControlRequest.cs | 2 ++ Emby.Dlna/ControlResponse.cs | 2 ++ Emby.Dlna/Didl/DidlBuilder.cs | 2 ++ Emby.Dlna/Didl/StringWriterWithEncoding.cs | 2 +- Emby.Dlna/DlnaConfigurationFactory.cs | 1 - Emby.Dlna/DlnaManager.cs | 2 ++ Emby.Dlna/Emby.Dlna.csproj | 1 + Emby.Dlna/EventSubscriptionResponse.cs | 2 ++ Emby.Dlna/Eventing/DlnaEventManager.cs | 2 ++ Emby.Dlna/Eventing/EventSubscription.cs | 2 ++ Emby.Dlna/Main/DlnaEntryPoint.cs | 2 ++ Emby.Dlna/PlayTo/Device.cs | 2 ++ Emby.Dlna/PlayTo/DeviceInfo.cs | 2 ++ Emby.Dlna/PlayTo/MediaChangedEventArgs.cs | 2 ++ Emby.Dlna/PlayTo/PlayToController.cs | 2 ++ Emby.Dlna/PlayTo/PlayToManager.cs | 2 ++ Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs | 2 ++ Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs | 2 ++ Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs | 2 ++ Emby.Dlna/PlayTo/PlaylistItem.cs | 2 ++ Emby.Dlna/PlayTo/PlaylistItemFactory.cs | 2 ++ Emby.Dlna/PlayTo/SsdpHttpClient.cs | 2 ++ Emby.Dlna/PlayTo/TransportCommands.cs | 14 +++++++------- Emby.Dlna/PlayTo/uBaseObject.cs | 2 ++ Emby.Dlna/Server/DescriptionXmlBuilder.cs | 3 ++- Emby.Dlna/Service/BaseControlHandler.cs | 4 ++-- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 ++ Emby.Dlna/Ssdp/SsdpExtensions.cs | 6 +++--- 32 files changed, 64 insertions(+), 16 deletions(-) diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index e63a858605..5ceeb55300 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 namespace Emby.Dlna.Configuration diff --git a/Emby.Dlna/ConfigurationExtension.cs b/Emby.Dlna/ConfigurationExtension.cs index fc02e17515..3ca43052a4 100644 --- a/Emby.Dlna/ConfigurationExtension.cs +++ b/Emby.Dlna/ConfigurationExtension.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 using Emby.Dlna.Configuration; diff --git a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs index 2f3107450c..7b8c504409 100644 --- a/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs +++ b/Emby.Dlna/ContentDirectory/ContentDirectoryService.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/ContentDirectory/ControlHandler.cs b/Emby.Dlna/ContentDirectory/ControlHandler.cs index 90ba601b4a..27c5b22680 100644 --- a/Emby.Dlna/ContentDirectory/ControlHandler.cs +++ b/Emby.Dlna/ContentDirectory/ControlHandler.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Dlna/ControlRequest.cs b/Emby.Dlna/ControlRequest.cs index 4ea4e4e48c..8ee6325e9e 100644 --- a/Emby.Dlna/ControlRequest.cs +++ b/Emby.Dlna/ControlRequest.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.IO; diff --git a/Emby.Dlna/ControlResponse.cs b/Emby.Dlna/ControlResponse.cs index d827eef26c..a7f2d4a73b 100644 --- a/Emby.Dlna/ControlResponse.cs +++ b/Emby.Dlna/ControlResponse.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Dlna/Didl/DidlBuilder.cs b/Emby.Dlna/Didl/DidlBuilder.cs index c66bdbf22c..2982ce97e1 100644 --- a/Emby.Dlna/Didl/DidlBuilder.cs +++ b/Emby.Dlna/Didl/DidlBuilder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Didl/StringWriterWithEncoding.cs b/Emby.Dlna/Didl/StringWriterWithEncoding.cs index 2b86ea333f..b66f53ece2 100644 --- a/Emby.Dlna/Didl/StringWriterWithEncoding.cs +++ b/Emby.Dlna/Didl/StringWriterWithEncoding.cs @@ -9,7 +9,7 @@ namespace Emby.Dlna.Didl { public class StringWriterWithEncoding : StringWriter { - private readonly Encoding _encoding; + private readonly Encoding? _encoding; public StringWriterWithEncoding() { diff --git a/Emby.Dlna/DlnaConfigurationFactory.cs b/Emby.Dlna/DlnaConfigurationFactory.cs index 4c6ca869aa..6cc6b73a0c 100644 --- a/Emby.Dlna/DlnaConfigurationFactory.cs +++ b/Emby.Dlna/DlnaConfigurationFactory.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Dlna/DlnaManager.cs b/Emby.Dlna/DlnaManager.cs index 5f2be07cf3..a1b1067040 100644 --- a/Emby.Dlna/DlnaManager.cs +++ b/Emby.Dlna/DlnaManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Emby.Dlna.csproj b/Emby.Dlna/Emby.Dlna.csproj index 480621dd70..a40578e403 100644 --- a/Emby.Dlna/Emby.Dlna.csproj +++ b/Emby.Dlna/Emby.Dlna.csproj @@ -21,6 +21,7 @@ false true true + enable diff --git a/Emby.Dlna/EventSubscriptionResponse.cs b/Emby.Dlna/EventSubscriptionResponse.cs index 1b1bd426c5..8c82dcbf68 100644 --- a/Emby.Dlna/EventSubscriptionResponse.cs +++ b/Emby.Dlna/EventSubscriptionResponse.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Dlna/Eventing/DlnaEventManager.cs b/Emby.Dlna/Eventing/DlnaEventManager.cs index ff81e83b5e..2e672b886b 100644 --- a/Emby.Dlna/Eventing/DlnaEventManager.cs +++ b/Emby.Dlna/Eventing/DlnaEventManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Eventing/EventSubscription.cs b/Emby.Dlna/Eventing/EventSubscription.cs index 40d73ee0e5..4fd7f81695 100644 --- a/Emby.Dlna/Eventing/EventSubscription.cs +++ b/Emby.Dlna/Eventing/EventSubscription.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index bdfe430cf3..0309926abb 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/Device.cs b/Emby.Dlna/PlayTo/Device.cs index abd99bbc3c..5fa1fd5896 100644 --- a/Emby.Dlna/PlayTo/Device.cs +++ b/Emby.Dlna/PlayTo/Device.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/DeviceInfo.cs b/Emby.Dlna/PlayTo/DeviceInfo.cs index d3daab9e0a..2acfff4eb6 100644 --- a/Emby.Dlna/PlayTo/DeviceInfo.cs +++ b/Emby.Dlna/PlayTo/DeviceInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs b/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs index dabd079afd..2bc4d8cc24 100644 --- a/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs +++ b/Emby.Dlna/PlayTo/MediaChangedEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlayToController.cs b/Emby.Dlna/PlayTo/PlayToController.cs index ee09cc65a9..1e6a5fadbf 100644 --- a/Emby.Dlna/PlayTo/PlayToController.cs +++ b/Emby.Dlna/PlayTo/PlayToController.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index f2f5262214..35bf5927c4 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs index d14617c8a0..c7d2b28df8 100644 --- a/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackProgressEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs index 3f8d552636..f8a14f411f 100644 --- a/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStartEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs index deeb47918d..6661f92ac7 100644 --- a/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs +++ b/Emby.Dlna/PlayTo/PlaybackStoppedEventArgs.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/PlaylistItem.cs b/Emby.Dlna/PlayTo/PlaylistItem.cs index 85846166cf..5056e69ae7 100644 --- a/Emby.Dlna/PlayTo/PlaylistItem.cs +++ b/Emby.Dlna/PlayTo/PlaylistItem.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Model.Dlna; diff --git a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs index e28840a896..6574913032 100644 --- a/Emby.Dlna/PlayTo/PlaylistItemFactory.cs +++ b/Emby.Dlna/PlayTo/PlaylistItemFactory.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.IO; diff --git a/Emby.Dlna/PlayTo/SsdpHttpClient.cs b/Emby.Dlna/PlayTo/SsdpHttpClient.cs index d9f1ce4907..f14f73bb6f 100644 --- a/Emby.Dlna/PlayTo/SsdpHttpClient.cs +++ b/Emby.Dlna/PlayTo/SsdpHttpClient.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/PlayTo/TransportCommands.cs b/Emby.Dlna/PlayTo/TransportCommands.cs index cbcf66e45c..b58669355d 100644 --- a/Emby.Dlna/PlayTo/TransportCommands.cs +++ b/Emby.Dlna/PlayTo/TransportCommands.cs @@ -46,7 +46,7 @@ namespace Emby.Dlna.PlayTo { var serviceAction = new ServiceAction { - Name = container.GetValue(UPnpNamespaces.Svc + "name"), + Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty, }; var argumentList = serviceAction.ArgumentList; @@ -68,9 +68,9 @@ namespace Emby.Dlna.PlayTo return new Argument { - Name = container.GetValue(UPnpNamespaces.Svc + "name"), - Direction = container.GetValue(UPnpNamespaces.Svc + "direction"), - RelatedStateVariable = container.GetValue(UPnpNamespaces.Svc + "relatedStateVariable") + Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty, + Direction = container.GetValue(UPnpNamespaces.Svc + "direction") ?? string.Empty, + RelatedStateVariable = container.GetValue(UPnpNamespaces.Svc + "relatedStateVariable") ?? string.Empty }; } @@ -89,8 +89,8 @@ namespace Emby.Dlna.PlayTo return new StateVariable { - Name = container.GetValue(UPnpNamespaces.Svc + "name"), - DataType = container.GetValue(UPnpNamespaces.Svc + "dataType"), + Name = container.GetValue(UPnpNamespaces.Svc + "name") ?? string.Empty, + DataType = container.GetValue(UPnpNamespaces.Svc + "dataType") ?? string.Empty, AllowedValues = allowedValues }; } @@ -166,7 +166,7 @@ namespace Emby.Dlna.PlayTo return string.Format(CultureInfo.InvariantCulture, CommandBase, action.Name, xmlNamesapce, stateString); } - private string BuildArgumentXml(Argument argument, string value, string commandParameter = "") + private string BuildArgumentXml(Argument argument, string? value, string commandParameter = "") { var state = StateVariables.FirstOrDefault(a => string.Equals(a.Name, argument.RelatedStateVariable, StringComparison.OrdinalIgnoreCase)); diff --git a/Emby.Dlna/PlayTo/uBaseObject.cs b/Emby.Dlna/PlayTo/uBaseObject.cs index 0d9478e42e..02d2da58d6 100644 --- a/Emby.Dlna/PlayTo/uBaseObject.cs +++ b/Emby.Dlna/PlayTo/uBaseObject.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Server/DescriptionXmlBuilder.cs b/Emby.Dlna/Server/DescriptionXmlBuilder.cs index 09525aae4e..3f3dfccd3a 100644 --- a/Emby.Dlna/Server/DescriptionXmlBuilder.cs +++ b/Emby.Dlna/Server/DescriptionXmlBuilder.cs @@ -250,7 +250,8 @@ namespace Emby.Dlna.Server url = _serverAddress.TrimEnd('/') + "/dlna/" + _serverUdn + "/" + url.TrimStart('/'); - return SecurityElement.Escape(url); + // TODO: @bond remove null-coalescing operator when https://github.com/dotnet/runtime/pull/52442 is merged/released + return SecurityElement.Escape(url) ?? string.Empty; } private IEnumerable GetIcons() diff --git a/Emby.Dlna/Service/BaseControlHandler.cs b/Emby.Dlna/Service/BaseControlHandler.cs index fda8346f9e..904c23d997 100644 --- a/Emby.Dlna/Service/BaseControlHandler.cs +++ b/Emby.Dlna/Service/BaseControlHandler.cs @@ -47,7 +47,7 @@ namespace Emby.Dlna.Service private async Task ProcessControlRequestInternalAsync(ControlRequest request) { - ControlRequestInfo requestInfo = null; + ControlRequestInfo? requestInfo = null; using (var streamReader = new StreamReader(request.InputXml, Encoding.UTF8)) { @@ -151,7 +151,7 @@ namespace Emby.Dlna.Service private async Task ParseBodyTagAsync(XmlReader reader) { - string namespaceURI = null, localName = null; + string? namespaceURI = null, localName = null; await reader.MoveToContentAsync().ConfigureAwait(false); await reader.ReadAsync().ConfigureAwait(false); diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index d9c6a93c7e..391dda1479 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Dlna/Ssdp/SsdpExtensions.cs b/Emby.Dlna/Ssdp/SsdpExtensions.cs index e7a52f168f..d00eb02b46 100644 --- a/Emby.Dlna/Ssdp/SsdpExtensions.cs +++ b/Emby.Dlna/Ssdp/SsdpExtensions.cs @@ -7,21 +7,21 @@ namespace Emby.Dlna.Ssdp { public static class SsdpExtensions { - public static string GetValue(this XElement container, XName name) + public static string? GetValue(this XElement container, XName name) { var node = container.Element(name); return node?.Value; } - public static string GetAttributeValue(this XElement container, XName name) + public static string? GetAttributeValue(this XElement container, XName name) { var node = container.Attribute(name); return node?.Value; } - public static string GetDescendantValue(this XElement container, XName name) + public static string? GetDescendantValue(this XElement container, XName name) => container.Descendants(name).FirstOrDefault()?.Value; } } From 4f5c9e95041a39ae549bfa3f36bbeda054bce3ca Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 14:02:42 +0100 Subject: [PATCH 1588/1930] tests and small fix. --- Jellyfin.Api/Controllers/SystemController.cs | 8 +++- .../Middleware/UrlDecodeQueryFeature.cs | 9 +++- .../Controllers/EncodedQueryStringTest.cs | 47 +++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index bbbe5fb8da..5c64d731b6 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -84,13 +84,19 @@ namespace Jellyfin.Api.Controllers /// /// Pings the system. /// + /// Optional: Parameters to echo back in the response. /// Information retrieved. /// The server name. [HttpGet("Ping", Name = "GetPingSystem")] [HttpPost("Ping", Name = "PostPingSystem")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult PingSystem() + public ActionResult PingSystem([FromQuery]Dictionary? @params = null) { + if (@params != null && @params.Count > 0) + { + Response.Headers.Add("querystring", string.Join("&", @params.Select(x => x.Key + "=" + x.Value))); + } + return _appHost.Name; } diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index b18ba70512..44b30baac0 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -66,7 +66,14 @@ namespace Jellyfin.Server.Middleware foreach (var pair in queryString) { var item = pair.Split('=', System.StringSplitOptions.RemoveEmptyEntries); - pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty)); + if (item.Length > 0) + { + pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty)); + } + else + { + pairs.Add(pair, string.Empty); + } } _store = new QueryCollection(pairs); diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs new file mode 100644 index 0000000000..ce5ac11ea5 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs @@ -0,0 +1,47 @@ +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace Jellyfin.Api.Tests.Controllers +{ + /// + /// Defines the test for encoded querystrings in the url. + /// + public class EncodedQueryStringTest : IClassFixture + { + private readonly JellyfinApplicationFactory _factory; + + public EncodedQueryStringTest(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public async Task Ensure_Ping_Working() + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("system/ping").ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Theory] + [InlineData("a=1&b=2&c=3", "a=1&b=2&c=3")] // won't be processed as there is more than 1. + [InlineData("a=1", "a=1")] // won't be processed as it has a value + [InlineData("%3D", "==")] // will decode with an empty string value '=' = ''. + [InlineData("a%3D1%26b%3D2%26c%3D3", "a=1&b=2&c=3")] // will be processed. + + public async Task Ensure_Decoding_Of_Urls_Is_Working(string sourceUrl, string unencodedUrl) + { + var client = _factory.CreateClient(); + + var response = await client.GetAsync("system/ping?" + sourceUrl).ConfigureAwait(false); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(unencodedUrl, response.Headers.GetValues("querystring").First()); + } + } +} From af1fe1af6fee7f4e5cf73d92266df21b291169d9 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 14:37:26 +0100 Subject: [PATCH 1589/1930] Moved into test controller. --- Jellyfin.Api/Controllers/SystemController.cs | 8 +--- Jellyfin.Api/Controllers/TestController.cs | 41 +++++++++++++++++++ .../Controllers/EncodedQueryStringTest.cs | 2 +- 3 files changed, 43 insertions(+), 8 deletions(-) create mode 100644 Jellyfin.Api/Controllers/TestController.cs diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 5c64d731b6..bbbe5fb8da 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -84,19 +84,13 @@ namespace Jellyfin.Api.Controllers /// /// Pings the system. /// - /// Optional: Parameters to echo back in the response. /// Information retrieved. /// The server name. [HttpGet("Ping", Name = "GetPingSystem")] [HttpPost("Ping", Name = "PostPingSystem")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult PingSystem([FromQuery]Dictionary? @params = null) + public ActionResult PingSystem() { - if (@params != null && @params.Count > 0) - { - Response.Headers.Add("querystring", string.Join("&", @params.Select(x => x.Key + "=" + x.Value))); - } - return _appHost.Name; } diff --git a/Jellyfin.Api/Controllers/TestController.cs b/Jellyfin.Api/Controllers/TestController.cs new file mode 100644 index 0000000000..b76895696a --- /dev/null +++ b/Jellyfin.Api/Controllers/TestController.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Linq; +using Jellyfin.Api.Constants; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api.Controllers +{ + /// + /// Controller for testing. + /// + [Route("Tests")] + public class TestController : BaseJellyfinApiController + { + /// + /// Initializes a new instance of the class. + /// + public TestController() + { + } + + /// + /// Tests the url decoding. + /// + /// Parameters to echo back in the response. + /// An . + /// Information retrieved. + [HttpGet("Decoding", Name = "TestUrlDecoding")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult TestUrlDecoding([FromQuery]Dictionary? @params = null) + { + if (@params != null && @params.Count > 0) + { + Response.Headers.Add("querystring", string.Join("&", @params.Select(x => x.Key + "=" + x.Value))); + } + + return Ok(); + } + } +} diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs index ce5ac11ea5..212fb118cb 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs @@ -39,7 +39,7 @@ namespace Jellyfin.Api.Tests.Controllers { var client = _factory.CreateClient(); - var response = await client.GetAsync("system/ping?" + sourceUrl).ConfigureAwait(false); + var response = await client.GetAsync("Tests/Decoding?" + sourceUrl).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(unencodedUrl, response.Headers.GetValues("querystring").First()); } From 043e69d252d5862ec5466ad037fea05f5aaef40f Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 18:49:57 +0100 Subject: [PATCH 1590/1930] Update tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs Co-authored-by: Cody Robibero --- tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs index 212fb118cb..dd81ad1346 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs @@ -34,7 +34,6 @@ namespace Jellyfin.Api.Tests.Controllers [InlineData("a=1", "a=1")] // won't be processed as it has a value [InlineData("%3D", "==")] // will decode with an empty string value '=' = ''. [InlineData("a%3D1%26b%3D2%26c%3D3", "a=1&b=2&c=3")] // will be processed. - public async Task Ensure_Decoding_Of_Urls_Is_Working(string sourceUrl, string unencodedUrl) { var client = _factory.CreateClient(); From 5f70b4ead16965acf4dbaf7bb486ecf072fb2a1b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 18:50:38 +0100 Subject: [PATCH 1591/1930] Update tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs Co-authored-by: Cody Robibero --- .../Controllers/EncodedQueryStringTest.cs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs index dd81ad1346..80175039ea 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs @@ -20,15 +20,6 @@ namespace Jellyfin.Api.Tests.Controllers _factory = factory; } - [Fact] - public async Task Ensure_Ping_Working() - { - var client = _factory.CreateClient(); - - var response = await client.GetAsync("system/ping").ConfigureAwait(false); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - } - [Theory] [InlineData("a=1&b=2&c=3", "a=1&b=2&c=3")] // won't be processed as there is more than 1. [InlineData("a=1", "a=1")] // won't be processed as it has a value From 5ad8b53f5d1a540453d897cddf924aa6fee46570 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 18:51:04 +0100 Subject: [PATCH 1592/1930] Update Jellyfin.Api/Controllers/TestController.cs Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/TestController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/TestController.cs b/Jellyfin.Api/Controllers/TestController.cs index b76895696a..a960bb24f5 100644 --- a/Jellyfin.Api/Controllers/TestController.cs +++ b/Jellyfin.Api/Controllers/TestController.cs @@ -26,7 +26,7 @@ namespace Jellyfin.Api.Controllers /// Parameters to echo back in the response. /// An . /// Information retrieved. - [HttpGet("Decoding", Name = "TestUrlDecoding")] + [HttpGet("UrlDecode")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult TestUrlDecoding([FromQuery]Dictionary? @params = null) { From 4c8cfaa61c513e51aab4440244a067ca39175dd5 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 18:51:15 +0100 Subject: [PATCH 1593/1930] Update Jellyfin.Api/Controllers/TestController.cs Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/TestController.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Jellyfin.Api/Controllers/TestController.cs b/Jellyfin.Api/Controllers/TestController.cs index a960bb24f5..1685045750 100644 --- a/Jellyfin.Api/Controllers/TestController.cs +++ b/Jellyfin.Api/Controllers/TestController.cs @@ -10,8 +10,7 @@ namespace Jellyfin.Api.Controllers /// /// Controller for testing. /// - [Route("Tests")] - public class TestController : BaseJellyfinApiController + public class TestsController : BaseJellyfinApiController { /// /// Initializes a new instance of the class. From 8b34f76b63dca54d59b4f3db2f5b485c32bd8e36 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 18:51:31 +0100 Subject: [PATCH 1594/1930] Update Jellyfin.Api/Controllers/TestController.cs Co-authored-by: Cody Robibero --- Jellyfin.Api/Controllers/TestController.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Jellyfin.Api/Controllers/TestController.cs b/Jellyfin.Api/Controllers/TestController.cs index 1685045750..487a99fcbd 100644 --- a/Jellyfin.Api/Controllers/TestController.cs +++ b/Jellyfin.Api/Controllers/TestController.cs @@ -12,13 +12,6 @@ namespace Jellyfin.Api.Controllers /// public class TestsController : BaseJellyfinApiController { - /// - /// Initializes a new instance of the class. - /// - public TestController() - { - } - /// /// Tests the url decoding. /// From d21d1978a3fce65a0af144d4293ce92bbf1f5b86 Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Fri, 7 May 2021 21:09:05 +0200 Subject: [PATCH 1595/1930] Disable automation CI on issues --- .github/workflows/automation.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index a203e66956..2529d80994 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -2,8 +2,6 @@ name: Automation on: pull_request: - issues: - issue_comment: jobs: main: From dca02987106d0433ee4139fb380dd78d92921dae Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Fri, 7 May 2021 20:11:32 +0100 Subject: [PATCH 1596/1930] changed --- .../{TestController.cs => TestsController.cs} | 14 ++++++++------ .../Controllers/EncodedQueryStringTest.cs | 6 ++++-- 2 files changed, 12 insertions(+), 8 deletions(-) rename Jellyfin.Api/Controllers/{TestController.cs => TestsController.cs} (64%) diff --git a/Jellyfin.Api/Controllers/TestController.cs b/Jellyfin.Api/Controllers/TestsController.cs similarity index 64% rename from Jellyfin.Api/Controllers/TestController.cs rename to Jellyfin.Api/Controllers/TestsController.cs index 487a99fcbd..1d1e1899fd 100644 --- a/Jellyfin.Api/Controllers/TestController.cs +++ b/Jellyfin.Api/Controllers/TestsController.cs @@ -20,14 +20,16 @@ namespace Jellyfin.Api.Controllers /// Information retrieved. [HttpGet("UrlDecode")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult TestUrlDecoding([FromQuery]Dictionary? @params = null) + public ContentResult TestUrlDecoding([FromQuery]Dictionary? @params = null) { - if (@params != null && @params.Count > 0) + return new ContentResult() { - Response.Headers.Add("querystring", string.Join("&", @params.Select(x => x.Key + "=" + x.Value))); - } - - return Ok(); + Content = (@params != null && @params.Count > 0) + ? string.Join("&", @params.Select(x => x.Key + "=" + x.Value)) + : string.Empty, + ContentType = "text/plain; charset=utf-8", + StatusCode = 200 + }; } } } diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs index 80175039ea..d6a423dcdd 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using System.Linq; using System.Net; @@ -29,9 +30,10 @@ namespace Jellyfin.Api.Tests.Controllers { var client = _factory.CreateClient(); - var response = await client.GetAsync("Tests/Decoding?" + sourceUrl).ConfigureAwait(false); + var response = await client.GetAsync("Tests/UrlDecode?" + sourceUrl).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(unencodedUrl, response.Headers.GetValues("querystring").First()); + string reply = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + Assert.Equal(unencodedUrl, reply); } } } From ce0e890d8d365e2b2f73645156adb9730caf1ce2 Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 7 May 2021 13:39:38 -0600 Subject: [PATCH 1597/1930] Mooooove the label commenter config --- .github/{workflows => }/label-commenter-config.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/{workflows => }/label-commenter-config.yml (100%) diff --git a/.github/workflows/label-commenter-config.yml b/.github/label-commenter-config.yml similarity index 100% rename from .github/workflows/label-commenter-config.yml rename to .github/label-commenter-config.yml From 56ac64e70a5cd4b4b4de78a0fc22c8bfe96a3677 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 8 May 2021 00:33:24 +0200 Subject: [PATCH 1598/1930] Minor improvements * properly dispose CancellationTokenSource * rewrite DynamicHlsController.GetSegmentLengths * remove dead code --- .../Controllers/DynamicHlsController.cs | 56 +++++++++--------- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 1 - .../MediaEncoding/EncodingJobOptions.cs | 49 ---------------- .../Controllers/DynamicHlsControllerTests.cs | 58 +++++++++++++++++++ 4 files changed, 85 insertions(+), 79 deletions(-) create mode 100644 tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index b4154b361e..9f3216de34 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -28,7 +28,6 @@ using MediaBrowser.Model.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; @@ -545,7 +544,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var streamingRequest = new VideoRequestDto { Id = itemId, @@ -710,7 +709,7 @@ namespace Jellyfin.Api.Controllers [FromQuery] EncodingContext? context, [FromQuery] Dictionary streamOptions) { - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var streamingRequest = new StreamingRequestDto { Id = itemId, @@ -1138,7 +1137,7 @@ namespace Jellyfin.Api.Controllers var isHlsInFmp4 = string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase); var hlsVersion = isHlsInFmp4 ? "7" : "3"; - var builder = new StringBuilder(); + var builder = new StringBuilder(128); builder.AppendLine("#EXTM3U") .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD") @@ -1191,7 +1190,7 @@ namespace Jellyfin.Api.Controllers throw new ArgumentException("StartTimeTicks is not allowed."); } - var cancellationTokenSource = new CancellationTokenSource(); + using var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; using var state = await StreamingHelpers.GetStreamingState( @@ -1208,7 +1207,7 @@ namespace Jellyfin.Api.Controllers _deviceManager, _transcodingJobHelper, TranscodingJobType, - cancellationTokenSource.Token) + cancellationToken) .ConfigureAwait(false); var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8"); @@ -1227,7 +1226,7 @@ namespace Jellyfin.Api.Controllers } var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlistPath); - await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false); + await transcodingLock.WaitAsync(cancellationToken).ConfigureAwait(false); var released = false; var startTranscoding = false; @@ -1323,24 +1322,28 @@ namespace Jellyfin.Api.Controllers return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); } - private double[] GetSegmentLengths(StreamState state) + private static double[] GetSegmentLengths(StreamState state) + => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength); + + internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength) { - var result = new List(); + var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks; + var wholeSegments = runtimeTicks / segmentLengthTicks; + var remainingTicks = runtimeTicks % segmentLengthTicks; - var ticks = state.RunTimeTicks ?? 0; - - var segmentLengthTicks = TimeSpan.FromSeconds(state.SegmentLength).Ticks; - - while (ticks > 0) + var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1); + var segments = new double[segmentsLen]; + for (int i = 0; i < wholeSegments; i++) { - var length = ticks >= segmentLengthTicks ? segmentLengthTicks : ticks; - - result.Add(TimeSpan.FromTicks(length).TotalSeconds); - - ticks -= length; + segments[i] = segmentlength; } - return result.ToArray(); + if (remainingTicks != 0) + { + segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds; + } + + return segments; } private string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding, int startNumber) @@ -1376,18 +1379,13 @@ namespace Jellyfin.Api.Controllers } else if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) { - var outputFmp4HeaderArg = string.Empty; - var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - if (isWindows) + var outputFmp4HeaderArg = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) switch { // on Windows, the path of fmp4 header file needs to be configured - outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\""; - } - else - { + true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"", // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder - outputFmp4HeaderArg = " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""; - } + false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\"" + }; segmentFormat = "fmp4" + outputFmp4HeaderArg; } diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 0879cbd18f..5770c13d7e 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -22,7 +22,6 @@ using MediaBrowser.Model.IO; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.Session; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Jellyfin.Api.Helpers diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs index 88de5b2925..61f3bc7711 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs @@ -4,59 +4,10 @@ using System; using System.Collections.Generic; -using System.Linq; using MediaBrowser.Model.Dlna; namespace MediaBrowser.Controller.MediaEncoding { - public class EncodingJobOptions : BaseEncodingJobOptions - { - public string OutputDirectory { get; set; } - - public string ItemId { get; set; } - - public string TempDirectory { get; set; } - - public bool ReadInputAtNativeFramerate { get; set; } - - /// - /// Gets a value indicating whether this instance has fixed resolution. - /// - /// true if this instance has fixed resolution; otherwise, false. - public bool HasFixedResolution => Width.HasValue || Height.HasValue; - - public DeviceProfile DeviceProfile { get; set; } - - public EncodingJobOptions(StreamInfo info, DeviceProfile deviceProfile) - { - Container = info.Container; - StartTimeTicks = info.StartPositionTicks; - MaxWidth = info.MaxWidth; - MaxHeight = info.MaxHeight; - MaxFramerate = info.MaxFramerate; - Id = info.ItemId; - MediaSourceId = info.MediaSourceId; - AudioCodec = info.TargetAudioCodec.FirstOrDefault(); - MaxAudioChannels = info.GlobalMaxAudioChannels; - AudioBitRate = info.AudioBitrate; - AudioSampleRate = info.TargetAudioSampleRate; - DeviceProfile = deviceProfile; - VideoCodec = info.TargetVideoCodec.FirstOrDefault(); - VideoBitRate = info.VideoBitrate; - AudioStreamIndex = info.AudioStreamIndex; - SubtitleMethod = info.SubtitleDeliveryMethod; - Context = info.Context; - TranscodingMaxAudioChannels = info.TranscodingMaxAudioChannels; - - if (info.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External) - { - SubtitleStreamIndex = info.SubtitleStreamIndex; - } - - StreamOptions = info.StreamOptions; - } - } - // For now until api and media encoding layers are unified public class BaseEncodingJobOptions { diff --git a/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs new file mode 100644 index 0000000000..1170838156 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsControllerTests.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Controllers; +using Jellyfin.Api.Helpers; +using Jellyfin.Api.Models.StreamingDtos; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.MediaEncoding; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Controllers +{ + public class DynamicHlsControllerTests + { + [Theory] + [MemberData(nameof(GetSegmentLengths_Success_TestData))] + public void GetSegmentLengths_Success(long runtimeTicks, int segmentlength, double[] expected) + { + var res = DynamicHlsController.GetSegmentLengthsInternal(runtimeTicks, segmentlength); + Assert.Equal(expected.Length, res.Length); + for (int i = 0; i < expected.Length; i++) + { + Assert.Equal(expected[i], res[i]); + } + } + + public static IEnumerable GetSegmentLengths_Success_TestData() + { + yield return new object[] { 0, 6, Array.Empty() }; + yield return new object[] + { + TimeSpan.FromSeconds(3).Ticks, + 6, + new double[] { 3 } + }; + yield return new object[] + { + TimeSpan.FromSeconds(6).Ticks, + 6, + new double[] { 6 } + }; + yield return new object[] + { + TimeSpan.FromSeconds(3.3333333).Ticks, + 6, + new double[] { 3.3333333 } + }; + yield return new object[] + { + TimeSpan.FromSeconds(9.3333333).Ticks, + 6, + new double[] { 6, 3.3333333 } + }; + } + } +} From bd71de131c384765b9240b7a54649e2c9258b133 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 8 May 2021 12:52:25 +0100 Subject: [PATCH 1599/1930] Changed to use span --- .../Middleware/UrlDecodeQueryFeature.cs | 21 ++++++++++++------- .../Jellyfin.Api.Tests.csproj | 1 + ...llyfin.Server.Implementations.Tests.csproj | 1 + .../Middleware}/EncodedQueryStringTest.cs | 3 ++- 4 files changed, 17 insertions(+), 9 deletions(-) rename tests/{Jellyfin.Api.Tests/Controllers => Jellyfin.Server.Implementations.Tests/Middleware}/EncodedQueryStringTest.cs (93%) diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index 44b30baac0..c89a318e16 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Web; +using MediaBrowser.Common.Extensions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Primitives; @@ -61,19 +62,23 @@ namespace Jellyfin.Server.Middleware } var pairs = new Dictionary(); - var queryString = unencodedKey.Split('&', System.StringSplitOptions.RemoveEmptyEntries); + var queryString = unencodedKey.SpanSplit('&'); foreach (var pair in queryString) { - var item = pair.Split('=', System.StringSplitOptions.RemoveEmptyEntries); - if (item.Length > 0) + var item = pair.Split('='); + item.MoveNext(); + + var key = item.Current; + var val = item.MoveNext() ? item.Current : string.Empty; + if (key.Length == 0 && val.Length == 0) { - pairs.Add(item[0], new StringValues(item.Length == 2 ? item[1] : string.Empty)); - } - else - { - pairs.Add(pair, string.Empty); + // encoded is an equals. + pairs.Add(pair.ToString(), new StringValues(string.Empty)); + continue; } + + pairs.Add(key.ToString(), new StringValues(val.ToString())); } _store = new QueryCollection(pairs); diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 397b863b70..e3577caeee 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -37,6 +37,7 @@ + diff --git a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj index 27713d58a3..ccc18d6869 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj +++ b/tests/Jellyfin.Server.Implementations.Tests/Jellyfin.Server.Implementations.Tests.csproj @@ -42,6 +42,7 @@ + diff --git a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs similarity index 93% rename from tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs rename to tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs index d6a423dcdd..e5865fb5ac 100644 --- a/tests/Jellyfin.Api.Tests/Controllers/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs @@ -5,9 +5,10 @@ using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; +using Jellyfin.Server.Integration.Tests; using Xunit; -namespace Jellyfin.Api.Tests.Controllers +namespace Jellyfin.Server.Implementations.Tests.Middleware { /// /// Defines the test for encoded querystrings in the url. From cb74a8697554008d37ae9359794b132c4945746b Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 8 May 2021 13:33:47 +0100 Subject: [PATCH 1600/1930] Moved test --- .../EncodedQueryStringTest.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) rename tests/{Jellyfin.Server.Implementations.Tests/Middleware => Jellyfin.Server.Integration.Tests}/EncodedQueryStringTest.cs (87%) diff --git a/tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs similarity index 87% rename from tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs rename to tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs index e5865fb5ac..a89d6e86f7 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Middleware/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs @@ -1,14 +1,8 @@ -using System; -using System.IO; -using System.Linq; using System.Net; -using System.Net.Http; -using System.Text; using System.Threading.Tasks; -using Jellyfin.Server.Integration.Tests; using Xunit; -namespace Jellyfin.Server.Implementations.Tests.Middleware +namespace Jellyfin.Server.Integration.Tests { /// /// Defines the test for encoded querystrings in the url. From 903bf2a086c49266c010f947180bd660b2c58931 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 8 May 2021 16:00:41 +0100 Subject: [PATCH 1601/1930] changed to use index --- Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index c89a318e16..dd05f7bc5c 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -66,19 +66,17 @@ namespace Jellyfin.Server.Middleware foreach (var pair in queryString) { - var item = pair.Split('='); - item.MoveNext(); + var section = pair.ToString(); + var i = section.IndexOf('=', System.StringComparison.Ordinal); - var key = item.Current; - var val = item.MoveNext() ? item.Current : string.Empty; - if (key.Length == 0 && val.Length == 0) + if (i == -1) { // encoded is an equals. - pairs.Add(pair.ToString(), new StringValues(string.Empty)); + pairs.Add(section, new StringValues(string.Empty)); continue; } - pairs.Add(key.ToString(), new StringValues(val.ToString())); + pairs.Add(section[0..i], new StringValues(section[(i + 1)..])); } _store = new QueryCollection(pairs); From 62a93d494b1970f67c60984ebbd554c19184fa2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 May 2021 12:19:21 +0000 Subject: [PATCH 1602/1930] Bump prometheus-net.DotNetRuntime from 4.0.0 to 4.1.0 Bumps [prometheus-net.DotNetRuntime](https://github.com/djluck/prometheus-net.DotNetRuntime) from 4.0.0 to 4.1.0. - [Release notes](https://github.com/djluck/prometheus-net.DotNetRuntime/releases) - [Commits](https://github.com/djluck/prometheus-net.DotNetRuntime/compare/4.0.0...4.1.0) Signed-off-by: dependabot[bot] --- Emby.Server.Implementations/Emby.Server.Implementations.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index b8a544b8c3..8ea98f454f 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -29,7 +29,7 @@ - + From 7ebe30f0abf674020d6801ab6bd1b4594390b5ed Mon Sep 17 00:00:00 2001 From: bvd13 Date: Tue, 23 Mar 2021 17:23:29 +0000 Subject: [PATCH 1603/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index ffc329e35b..ab1546a294 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -3,9 +3,9 @@ "AppDeviceValues": "App: {0}, Apparaat: {1}", "Application": "Applicatie", "Artists": "Artiesten", - "AuthenticationSucceededWithUserName": "{0} is succesvol geverifieerd", + "AuthenticationSucceededWithUserName": "{0} is succesvol geauthenticeerd", "Books": "Boeken", - "CameraImageUploadedFrom": "Er is een nieuwe camera afbeelding toegevoegd via {0}", + "CameraImageUploadedFrom": "Er is een nieuwe camera afbeelding toegevoegd vanaf {0}", "Channels": "Kanalen", "ChapterNameValue": "Hoofdstuk {0}", "Collections": "Verzamelingen", From c78f584a99d810167fe64d0451bf86b277112448 Mon Sep 17 00:00:00 2001 From: Baptiste Date: Wed, 24 Mar 2021 00:47:31 +0000 Subject: [PATCH 1604/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 1e195378ff..56fd9d4523 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -99,7 +99,7 @@ "TaskRefreshChannels": "Rafraîchir les chaines", "TaskCleanTranscodeDescription": "Supprime les fichiers transcodés de plus d'un jour.", "TaskCleanTranscode": "Nettoyer les dossier des transcodages", - "TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurés pour être mises à jour automatiquement.", + "TaskUpdatePluginsDescription": "Télécharge et installe les mises à jours des extensions configurées pour être mises à jour automatiquement.", "TaskUpdatePlugins": "Mettre à jour les extensions", "TaskRefreshPeopleDescription": "Met à jour les métadonnées pour les acteurs et réalisateurs dans votre bibliothèque.", "TaskRefreshPeople": "Rafraîchir les acteurs", From c5783da4f6b68680b111a6781c6f2f25a223b676 Mon Sep 17 00:00:00 2001 From: Csaba Date: Mon, 29 Mar 2021 04:43:25 +0000 Subject: [PATCH 1605/1930] Translated using Weblate (Hungarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hu/ --- Emby.Server.Implementations/Localization/Core/hu.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index ef80705031..c73cb9c72b 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -39,7 +39,7 @@ "MixedContent": "Vegyes tartalom", "Movies": "Filmek", "Music": "Zene", - "MusicVideos": "Zenei videók", + "MusicVideos": "Zenei videóklippek", "NameInstallFailed": "{0} sikertelen telepítés", "NameSeasonNumber": "{0}. évad", "NameSeasonUnknown": "Ismeretlen évad", From 2c66d36f10948285a3abf8dc941a5248aa5f05ad Mon Sep 17 00:00:00 2001 From: WWWesten Date: Mon, 29 Mar 2021 12:45:20 +0000 Subject: [PATCH 1606/1930] Translated using Weblate (Russian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ru/ --- Emby.Server.Implementations/Localization/Core/ru.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ru.json b/Emby.Server.Implementations/Localization/Core/ru.json index 46b47cf4a8..e58f8c39d0 100644 --- a/Emby.Server.Implementations/Localization/Core/ru.json +++ b/Emby.Server.Implementations/Localization/Core/ru.json @@ -39,7 +39,7 @@ "MixedContent": "Смешанное содержимое", "Movies": "Кино", "Music": "Музыка", - "MusicVideos": "Музыкальные клипы", + "MusicVideos": "Муз. видео", "NameInstallFailed": "Установка {0} неудачна", "NameSeasonNumber": "Сезон {0}", "NameSeasonUnknown": "Сезон неопознан", @@ -75,7 +75,7 @@ "StartupEmbyServerIsLoading": "Jellyfin Server загружается. Повторите попытку в ближайшее время.", "SubtitleDownloadFailureForItem": "Субтитры к {0} не удалось загрузить", "SubtitleDownloadFailureFromForItem": "Субтитры к {1} не удалось загрузить с {0}", - "Sync": "Синхронизация", + "Sync": "Синхро", "System": "Система", "TvShows": "ТВ", "User": "Пользователь", From f56898a563875f3a32fd83c9fe0aeaf071eee30b Mon Sep 17 00:00:00 2001 From: Oatavandi Date: Mon, 29 Mar 2021 16:47:06 +0000 Subject: [PATCH 1607/1930] Translated using Weblate (Tamil) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ta/ --- Emby.Server.Implementations/Localization/Core/ta.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ta.json b/Emby.Server.Implementations/Localization/Core/ta.json index c737ba42b8..129986ed0e 100644 --- a/Emby.Server.Implementations/Localization/Core/ta.json +++ b/Emby.Server.Implementations/Localization/Core/ta.json @@ -69,7 +69,7 @@ "NameSeasonUnknown": "அறியப்படாத பருவம்", "NameSeasonNumber": "பருவம் {0}", "NameInstallFailed": "{0} நிறுவல் தோல்வியடைந்தது", - "MusicVideos": "இசைப்படங்கள்", + "MusicVideos": "இசை கானொளி", "Music": "இசை", "Movies": "திரைப்படங்கள்", "Latest": "புதியவை", From 55f3dd4f2cd6920f633e2204d7e3783b2bd58d62 Mon Sep 17 00:00:00 2001 From: millallo Date: Thu, 1 Apr 2021 10:08:05 +0000 Subject: [PATCH 1608/1930] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 110f8043d7..90d7d742f5 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -87,7 +87,7 @@ "UserOnlineFromDevice": "{0} è online su {1}", "UserPasswordChangedWithName": "La password è stata cambiata per l'utente {0}", "UserPolicyUpdatedWithName": "La policy dell'utente è stata aggiornata per {0}", - "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1} su {2}", + "UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di \"{1}\" su {2}", "UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1} su {2}", "ValueHasBeenAddedToLibrary": "{0} è stato aggiunto alla tua libreria multimediale", "ValueSpecialEpisodeName": "Speciale - {0}", From 95f25467c8092a041c425dc5abbd74e54325edb4 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Tue, 6 Apr 2021 06:02:56 +0000 Subject: [PATCH 1609/1930] Translated using Weblate (Persian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fa/ --- Emby.Server.Implementations/Localization/Core/fa.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fa.json b/Emby.Server.Implementations/Localization/Core/fa.json index e9e4f61b8c..8ab657e5b8 100644 --- a/Emby.Server.Implementations/Localization/Core/fa.json +++ b/Emby.Server.Implementations/Localization/Core/fa.json @@ -34,7 +34,7 @@ "Latest": "جدیدترین‌ها", "MessageApplicationUpdated": "سرور Jellyfin بروزرسانی شد", "MessageApplicationUpdatedTo": "سرور Jellyfin به نسخه {0} بروزرسانی شد", - "MessageNamedServerConfigurationUpdatedWithValue": "پکربندی بخش {0} سرور بروزرسانی شد", + "MessageNamedServerConfigurationUpdatedWithValue": "پکربندی بخش {0} سرور بروزرسانی شد", "MessageServerConfigurationUpdated": "پیکربندی سرور بروزرسانی شد", "MixedContent": "محتوای مخلوط", "Movies": "فیلم‌ها", From da5ca3f76980ec870e5ad11149a1b841e5473d2e Mon Sep 17 00:00:00 2001 From: Csaba Date: Tue, 6 Apr 2021 05:53:44 +0000 Subject: [PATCH 1610/1930] Translated using Weblate (Hungarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hu/ --- Emby.Server.Implementations/Localization/Core/hu.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/hu.json b/Emby.Server.Implementations/Localization/Core/hu.json index c73cb9c72b..85848fed60 100644 --- a/Emby.Server.Implementations/Localization/Core/hu.json +++ b/Emby.Server.Implementations/Localization/Core/hu.json @@ -74,7 +74,7 @@ "Songs": "Dalok", "StartupEmbyServerIsLoading": "A Jellyfin Szerver betöltődik. Kérlek, próbáld újra hamarosan.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", - "SubtitleDownloadFailureFromForItem": "Nem sikerült a felirat letöltése innen: {0} ehhez: {1}", + "SubtitleDownloadFailureFromForItem": "Nem sikerült a felirat letöltése innen: {0} ehhez: {1}", "Sync": "Szinkronizál", "System": "Rendszer", "TvShows": "TV műsorok", @@ -82,12 +82,12 @@ "UserCreatedWithName": "{0} felhasználó létrehozva", "UserDeletedWithName": "{0} felhasználó törölve", "UserDownloadingItemWithValues": "{0} letölti {1}", - "UserLockedOutWithName": "{0} felhasználó zárolva van", - "UserOfflineFromDevice": "{0} kijelentkezett innen: {1}", + "UserLockedOutWithName": "{0} felhasználó zárolva van", + "UserOfflineFromDevice": "{0} kijelentkezett innen: {1}", "UserOnlineFromDevice": "{0} online innen: {1}", "UserPasswordChangedWithName": "Jelszó megváltozott a következő felhasználó számára: {0}", "UserPolicyUpdatedWithName": "A felhasználói házirend frissítve lett neki: {0}", - "UserStartedPlayingItemWithValues": "{0} elkezdte játszani a következőt: {1} itt: {2}", + "UserStartedPlayingItemWithValues": "{0} elkezdte játszani a következőt: {1} itt: {2}", "UserStoppedPlayingItemWithValues": "{0} befejezte {1} lejátászását itt: {2}", "ValueHasBeenAddedToLibrary": "{0} hozzáadva a médiatárhoz", "ValueSpecialEpisodeName": "Special - {0}", From 90a8cd83f48a3b5fc2b1661ab5588ed361debef3 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Tue, 6 Apr 2021 06:02:27 +0000 Subject: [PATCH 1611/1930] =?UTF-8?q?Translated=20using=20Weblate=20(Norwe?= =?UTF-8?q?gian=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Transl?= =?UTF-8?q?ate-URL:=20https://translate.jellyfin.org/projects/jellyfin/jel?= =?UTF-8?q?lyfin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Emby.Server.Implementations/Localization/Core/nb.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index d5bca9f6c9..a4f957a3a6 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -88,7 +88,7 @@ "UserPasswordChangedWithName": "Passordet for {0} er oppdatert", "UserPolicyUpdatedWithName": "Brukerpolicyen har blitt oppdatert for {0}", "UserStartedPlayingItemWithValues": "{0} har startet avspilling {1} på {2}", - "UserStoppedPlayingItemWithValues": "{0} har stoppet avspilling {1}", + "UserStoppedPlayingItemWithValues": "{0} har stoppet avspilling {1}", "ValueHasBeenAddedToLibrary": "{0} har blitt lagt til i mediebiblioteket ditt", "ValueSpecialEpisodeName": "Spesialepisode - {0}", "VersionNumber": "Versjon {0}", From eaa102fc7400ebebb86d24d42d1311bb8cceec7b Mon Sep 17 00:00:00 2001 From: WWWesten Date: Tue, 6 Apr 2021 06:03:33 +0000 Subject: [PATCH 1612/1930] Translated using Weblate (Bengali) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bn/ --- Emby.Server.Implementations/Localization/Core/bn.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json index a23037af8e..556591a229 100644 --- a/Emby.Server.Implementations/Localization/Core/bn.json +++ b/Emby.Server.Implementations/Localization/Core/bn.json @@ -115,7 +115,7 @@ "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।", "Undefined": "অসঙ্গায়িত", "Forced": "জোরকরে", - "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন", + "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন", "TaskCleanActivityLog": "কাজের ফাইল খালি করুন", "Default": "প্রাথমিক" } From b5bde8d46e087fd101311c717b67245b79390552 Mon Sep 17 00:00:00 2001 From: flackseven Date: Sun, 4 Apr 2021 23:53:40 +0000 Subject: [PATCH 1613/1930] Translated using Weblate (Ukrainian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/uk/ --- Emby.Server.Implementations/Localization/Core/uk.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/uk.json b/Emby.Server.Implementations/Localization/Core/uk.json index b6073bf6a8..5a2069df56 100644 --- a/Emby.Server.Implementations/Localization/Core/uk.json +++ b/Emby.Server.Implementations/Localization/Core/uk.json @@ -1,5 +1,5 @@ { - "MusicVideos": "Музичні кліпи", + "MusicVideos": "Музичні відеокліпи", "Music": "Музика", "Movies": "Фільми", "MessageApplicationUpdatedTo": "Jellyfin Server оновлено до версії {0}", @@ -113,7 +113,7 @@ "MessageNamedServerConfigurationUpdatedWithValue": "Розділ конфігурації сервера {0} оновлено", "Inherit": "Успадкувати", "HeaderRecordingGroups": "Групи запису", - "Forced": "Примусово", + "Forced": "Форсовані", "TaskCleanActivityLogDescription": "Видаляє старші за встановлений термін записи з журналу активності.", "TaskCleanActivityLog": "Очистити журнал активності", "Undefined": "Не визначено", From 0158f74d3798fcfc84b237726e8d888e528ce65d Mon Sep 17 00:00:00 2001 From: Manjot Singh Date: Mon, 5 Apr 2021 06:24:22 +0000 Subject: [PATCH 1614/1930] Translated using Weblate (Punjabi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/pa/ --- Emby.Server.Implementations/Localization/Core/pa.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/pa.json b/Emby.Server.Implementations/Localization/Core/pa.json index 469fa89b6e..d1db09232e 100644 --- a/Emby.Server.Implementations/Localization/Core/pa.json +++ b/Emby.Server.Implementations/Localization/Core/pa.json @@ -1,5 +1,5 @@ { - "TaskRefreshChapterImages": "ਐਬਸਟਰੈਕਟ ਅਧਿਆਇ ਅਧਿਆਇ", + "TaskRefreshChapterImages": "ਐਕਸਟਰੈਕਟ ਚੈਪਟਰ ਚਿੱਤਰ", "TaskDownloadMissingSubtitlesDescription": "ਮੈਟਾਡੇਟਾ ਕੌਂਫਿਗਰੇਸ਼ਨ ਦੇ ਅਧਾਰ ਤੇ ਗਾਇਬ ਉਪਸਿਰਲੇਖਾਂ ਲਈ ਇੰਟਰਨੈਟ ਦੀ ਭਾਲ ਕਰਦਾ ਹੈ.", "TaskDownloadMissingSubtitles": "ਗਾਇਬ ਉਪਸਿਰਲੇਖ ਡਾ Download ਨਲੋਡ ਕਰੋ", "TaskRefreshChannelsDescription": "ਇੰਟਰਨੈੱਟ ਚੈਨਲ ਦੀ ਜਾਣਕਾਰੀ ਨੂੰ ਤਾਜ਼ਾ ਕਰਦਾ ਹੈ.", From 061016a2a939c0a47634ef22251467260486c718 Mon Sep 17 00:00:00 2001 From: Robolov Date: Wed, 7 Apr 2021 14:35:57 +0000 Subject: [PATCH 1615/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index 56fd9d4523..d12c1ddec7 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -39,7 +39,7 @@ "MixedContent": "Contenu mixte", "Movies": "Films", "Music": "Musique", - "MusicVideos": "Vidéos musicales", + "MusicVideos": "Clips musicaux", "NameInstallFailed": "{0} échec de l'installation", "NameSeasonNumber": "Saison {0}", "NameSeasonUnknown": "Saison Inconnue", From dc15cc1370d06a44a4d4f824b3a9d62ae6aa86cd Mon Sep 17 00:00:00 2001 From: WWWesten Date: Thu, 8 Apr 2021 14:15:05 +0000 Subject: [PATCH 1616/1930] Translated using Weblate (Bengali) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bn/ --- Emby.Server.Implementations/Localization/Core/bn.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json index 556591a229..f0e42a052b 100644 --- a/Emby.Server.Implementations/Localization/Core/bn.json +++ b/Emby.Server.Implementations/Localization/Core/bn.json @@ -115,7 +115,7 @@ "TaskRefreshLibraryDescription": "নতুন ফাইলের জন্য মিডিয়া লাইব্রেরি স্ক্যান এবং মেটাডাটা রিফ্রেশ করুন।", "Undefined": "অসঙ্গায়িত", "Forced": "জোরকরে", - "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন", + "TaskCleanActivityLogDescription": "নির্ধারিত সময়ের আগের কাজের হিসাব মুছে দিন খালি করুন.", "TaskCleanActivityLog": "কাজের ফাইল খালি করুন", "Default": "প্রাথমিক" } From 1237a7b82a3adb92f905fc693fe263ec1aaaab81 Mon Sep 17 00:00:00 2001 From: Koos van Riemsdijk Date: Sun, 11 Apr 2021 08:21:12 +0000 Subject: [PATCH 1617/1930] Translated using Weblate (Dutch) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nl/ --- Emby.Server.Implementations/Localization/Core/nl.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/nl.json b/Emby.Server.Implementations/Localization/Core/nl.json index ab1546a294..2973c8c6ea 100644 --- a/Emby.Server.Implementations/Localization/Core/nl.json +++ b/Emby.Server.Implementations/Localization/Core/nl.json @@ -5,7 +5,7 @@ "Artists": "Artiesten", "AuthenticationSucceededWithUserName": "{0} is succesvol geauthenticeerd", "Books": "Boeken", - "CameraImageUploadedFrom": "Er is een nieuwe camera afbeelding toegevoegd vanaf {0}", + "CameraImageUploadedFrom": "Nieuwe camera afbeelding toegevoegd vanaf {0}", "Channels": "Kanalen", "ChapterNameValue": "Hoofdstuk {0}", "Collections": "Verzamelingen", From 2bf27462317979b7e80718b703b501e871813497 Mon Sep 17 00:00:00 2001 From: radiusgreenhill Date: Wed, 14 Apr 2021 21:41:38 +0000 Subject: [PATCH 1618/1930] Translated using Weblate (Thai) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/th/ --- Emby.Server.Implementations/Localization/Core/th.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/th.json b/Emby.Server.Implementations/Localization/Core/th.json index 5bf58baf8c..e260104236 100644 --- a/Emby.Server.Implementations/Localization/Core/th.json +++ b/Emby.Server.Implementations/Localization/Core/th.json @@ -113,5 +113,9 @@ "Sync": "ซิงค์", "SubtitleDownloadFailureFromForItem": "ไม่สามารถดาวน์โหลดคำบรรยายจาก {0} สำหรับ {1} ได้", "StartupEmbyServerIsLoading": "กำลังโหลดเซิร์ฟเวอร์ Jellyfin โปรดลองอีกครั้งในอีกสักครู่", - "Default": "ค่าเริ่มต้น" + "Default": "ค่าเริ่มต้น", + "TaskCleanActivityLogDescription": "ลบบันทึกกิจกรรมที่เก่ากว่าค่าที่กำหนดไว้", + "TaskCleanActivityLog": "ล้างบันทึกกิจกรรม", + "Undefined": "ไม่ได้กำหนด", + "Forced": "บังคับใช้" } From 7dc721923ee94a2cbc8029e9eeb5557af01704f6 Mon Sep 17 00:00:00 2001 From: Federico Antoniazzi Date: Fri, 16 Apr 2021 22:17:18 +0000 Subject: [PATCH 1619/1930] Translated using Weblate (Italian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/it/ --- Emby.Server.Implementations/Localization/Core/it.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/it.json b/Emby.Server.Implementations/Localization/Core/it.json index 90d7d742f5..bd06f0a258 100644 --- a/Emby.Server.Implementations/Localization/Core/it.json +++ b/Emby.Server.Implementations/Localization/Core/it.json @@ -62,7 +62,7 @@ "NotificationOptionVideoPlaybackStopped": "La riproduzione video è stata interrotta", "Photos": "Foto", "Playlists": "Playlist", - "Plugin": "Plug-in", + "Plugin": "Plugin", "PluginInstalledWithName": "{0} è stato Installato", "PluginUninstalledWithName": "{0} è stato disinstallato", "PluginUpdatedWithName": "{0} è stato aggiornato", From 9b2a87f981cdb57af39535e97e0a95477faf1bb4 Mon Sep 17 00:00:00 2001 From: Oskari Lavinto Date: Sun, 18 Apr 2021 05:27:57 +0000 Subject: [PATCH 1620/1930] Translated using Weblate (Finnish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fi/ --- Emby.Server.Implementations/Localization/Core/fi.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/fi.json b/Emby.Server.Implementations/Localization/Core/fi.json index fd6148e789..633968d26d 100644 --- a/Emby.Server.Implementations/Localization/Core/fi.json +++ b/Emby.Server.Implementations/Localization/Core/fi.json @@ -1,5 +1,5 @@ { - "HeaderLiveTV": "Live TV", + "HeaderLiveTV": "Suora TV", "NewVersionIsAvailable": "Uusi versio Jellyfin-palvelimesta on ladattavissa.", "NameSeasonUnknown": "Tuntematon kausi", "NameSeasonNumber": "Kausi {0}", From 85c771e64b250339679a438907763e1825e25a0b Mon Sep 17 00:00:00 2001 From: a19guillermobf Date: Fri, 23 Apr 2021 17:39:34 +0000 Subject: [PATCH 1621/1930] Translated using Weblate (Galician) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/gl/ --- Emby.Server.Implementations/Localization/Core/gl.json | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/gl.json b/Emby.Server.Implementations/Localization/Core/gl.json index 11139d32a8..0398e1c9e5 100644 --- a/Emby.Server.Implementations/Localization/Core/gl.json +++ b/Emby.Server.Implementations/Localization/Core/gl.json @@ -79,5 +79,14 @@ "PluginUninstalledWithName": "{0} foi desinstalado", "PluginInstalledWithName": "{0} foi instalado", "Playlists": "Listas de reproducción", - "Photos": "Fotos" + "Photos": "Fotos", + "UserLockedOutWithName": "O usuario {0} foi bloqueado", + "UserDownloadingItemWithValues": "{0} está a ser transferido {1}", + "UserDeletedWithName": "O usuario {0} foi borrado", + "UserCreatedWithName": "O usuario {0} foi creado", + "Plugin": "Plugin", + "NotificationOptionVideoPlaybackStopped": "Reproducción de vídeo parada", + "NotificationOptionVideoPlayback": "Reproducción de vídeo iniciada", + "NotificationOptionUserLockedOut": "Usuario bloqueado", + "NotificationOptionTaskFailed": "Falla na tarefa axendada" } From 07ea5e2472a623e47b64dd60dd284b1ab458587e Mon Sep 17 00:00:00 2001 From: 0TTA Date: Thu, 22 Apr 2021 04:14:53 +0000 Subject: [PATCH 1622/1930] Translated using Weblate (Arabic) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ar/ --- Emby.Server.Implementations/Localization/Core/ar.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ar.json b/Emby.Server.Implementations/Localization/Core/ar.json index 4b898e6fe0..9f84d3a3cf 100644 --- a/Emby.Server.Implementations/Localization/Core/ar.json +++ b/Emby.Server.Implementations/Localization/Core/ar.json @@ -113,5 +113,8 @@ "TaskRefreshPeopleDescription": "تحديث البيانات الوصفية للممثلين والمخرجين في مكتبة الوسائط الخاصة بك.", "TaskRefreshPeople": "إعادة تحميل الأشخاص", "TaskCleanLogsDescription": "حذف السجلات الأقدم من {0} يوم.", - "TaskCleanLogs": "حذف دليل السجل" + "TaskCleanLogs": "حذف دليل السجل", + "TaskCleanActivityLogDescription": "يحذف سجل الأنشطة الأقدم من الوقت الموضوع.", + "TaskCleanActivityLog": "حذف سجل الأنشطة", + "Default": "الإعدادات الافتراضية" } From 7af45a8f01b033ed9fb5069e6ca0ada073bd24e3 Mon Sep 17 00:00:00 2001 From: WWWesten Date: Thu, 22 Apr 2021 18:39:36 +0000 Subject: [PATCH 1623/1930] Translated using Weblate (Kazakh) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/kk/ --- .../Localization/Core/kk.json | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/kk.json b/Emby.Server.Implementations/Localization/Core/kk.json index 829a29ad42..4eee369892 100644 --- a/Emby.Server.Implementations/Localization/Core/kk.json +++ b/Emby.Server.Implementations/Localization/Core/kk.json @@ -5,23 +5,23 @@ "Artists": "Oryndauşylar", "AuthenticationSucceededWithUserName": "{0} tüpnūsqalyq rastaluy sättı aiaqtaldy", "Books": "Kıtaptar", - "CameraImageUploadedFrom": "{0} kamerasynan jaŋa suret jüktep salyndy", + "CameraImageUploadedFrom": "{0} kamerasynan jaña suret jüktep salyndy", "Channels": "Arnalar", "ChapterNameValue": "{0}-sahna", "Collections": "Jiyntyqtar", "DeviceOfflineWithName": "{0} ajyratylğan", "DeviceOnlineWithName": "{0} qosylğan", "FailedLoginAttemptWithUserName": "{0} tarapynan kıru äreketı sätsız aiaqtaldy", - "Favorites": "Taŋdaulylar", + "Favorites": "Tañdaulylar", "Folders": "Qaltalar", "Genres": "Janrlar", "HeaderAlbumArtists": "Älbom oryndauşylary", "HeaderContinueWatching": "Qaraudy jalğastyru", - "HeaderFavoriteAlbums": "Taŋdauly älbomdar", - "HeaderFavoriteArtists": "Taŋdauly oryndauşylar", - "HeaderFavoriteEpisodes": "Taŋdauly telebölımder", - "HeaderFavoriteShows": "Taŋdauly körsetımder", - "HeaderFavoriteSongs": "Taŋdauly äuender", + "HeaderFavoriteAlbums": "Tañdauly älbomdar", + "HeaderFavoriteArtists": "Tañdauly oryndauşylar", + "HeaderFavoriteEpisodes": "Tañdauly telebölımder", + "HeaderFavoriteShows": "Tañdauly körsetımder", + "HeaderFavoriteSongs": "Tañdauly äuender", "HeaderLiveTV": "Efir", "HeaderNextUp": "Kezektı", "HeaderRecordingGroups": "Jazba toptary", @@ -31,11 +31,11 @@ "ItemRemovedWithName": "{0} tasyğyşhanadan alastaldy", "LabelIpAddressValue": "IP-mekenjaiy: {0}", "LabelRunningTimeValue": "Oinatu uaqyty: {0}", - "Latest": "Eŋ keiıngı", - "MessageApplicationUpdated": "Jellyfin Serverı jaŋartyldy", - "MessageApplicationUpdatedTo": "Jellyfin Serverı {0} nūsqasyna jaŋartyldy", - "MessageNamedServerConfigurationUpdatedWithValue": "Server teŋşelımderınıŋ {0} bölımı jaŋartyldy", - "MessageServerConfigurationUpdated": "Server teŋşelımderı jaŋartyldy", + "Latest": "Eñ keiıngı", + "MessageApplicationUpdated": "Jellyfin Serverı jañartyldy", + "MessageApplicationUpdatedTo": "Jellyfin Serverı {0} nūsqasyna jañartyldy", + "MessageNamedServerConfigurationUpdatedWithValue": "Server teñşelımderınıñ {0} bölımı jañartyldy", + "MessageServerConfigurationUpdated": "Server teñşelımderı jañartyldy", "MixedContent": "Aralas mazmūn", "Movies": "Filmder", "Music": "Muzyka", @@ -43,18 +43,18 @@ "NameInstallFailed": "{0} ornatyluy sätsız", "NameSeasonNumber": "{0}-mausym", "NameSeasonUnknown": "Belgısız mausym", - "NewVersionIsAvailable": "Jaŋa Jellyfin Server nūsqasy jüktep aluğa qoljetımdı.", - "NotificationOptionApplicationUpdateAvailable": "Qoldanba jaŋartuy qoljetımdı", - "NotificationOptionApplicationUpdateInstalled": "Qoldanba jaŋartuy ornatyldy", + "NewVersionIsAvailable": "Jaña Jellyfin Server nūsqasy jüktep aluğa qoljetımdı.", + "NotificationOptionApplicationUpdateAvailable": "Qoldanba jañartuy qoljetımdı", + "NotificationOptionApplicationUpdateInstalled": "Qoldanba jañartuy ornatyldy", "NotificationOptionAudioPlayback": "Dybys oinatuy bastaldy", "NotificationOptionAudioPlaybackStopped": "Dybys oinatuy toqtatyldy", "NotificationOptionCameraImageUploaded": "Kameradan fotosuret jüktep salynğan", "NotificationOptionInstallationFailed": "Ornatu sätsızdıgı", - "NotificationOptionNewLibraryContent": "Jaŋa mazmūn üstelıngen", + "NotificationOptionNewLibraryContent": "Jaña mazmūn üstelıngen", "NotificationOptionPluginError": "Plagin sätsızdıgı", "NotificationOptionPluginInstalled": "Plagin ornatyldy", "NotificationOptionPluginUninstalled": "Plagin ornatuy boldyrylmady", - "NotificationOptionPluginUpdateInstalled": "Plagin jaŋartuy ornatyldy", + "NotificationOptionPluginUpdateInstalled": "Plagin jañartuy ornatyldy", "NotificationOptionServerRestartRequired": "Serverdı qaita ıske qosu qajet", "NotificationOptionTaskFailed": "Josparlağan tapsyrma sätsızdıgı", "NotificationOptionUserLockedOut": "Paidalanuşy qūrsauly", @@ -65,14 +65,14 @@ "Plugin": "Plagin", "PluginInstalledWithName": "{0} ornatyldy", "PluginUninstalledWithName": "{0} joiyldy", - "PluginUpdatedWithName": "{0} jaŋartyldy", + "PluginUpdatedWithName": "{0} jañartyldy", "ProviderValue": "Jetkızuşı: {0}", "ScheduledTaskFailedWithName": "{0} sätsız", "ScheduledTaskStartedWithName": "{0} ıske qosyldy", "ServerNameNeedsToBeRestarted": "{0} qaita ıske qosu qajet", "Shows": "Körsetımder", "Songs": "Äuender", - "StartupEmbyServerIsLoading": "Jellyfin Server jüktelude. Ärekettı köp ūzamai qaitalaŋyz.", + "StartupEmbyServerIsLoading": "Jellyfin Server jüktelude. Ärekettı köp ūzamai qaitalañyz.", "SubtitleDownloadFailureForItem": "Субтитрлер {0} үшін жүктеліп алынуы сәтсіз", "SubtitleDownloadFailureFromForItem": "{1} üşın subtitrlerdı {0} közınen jüktep alu sätsız", "Sync": "Ündestıru", @@ -86,7 +86,7 @@ "UserOfflineFromDevice": "{0} — {1} tarapynan ajyratyldy", "UserOnlineFromDevice": "{0} — {1} tarapynan qosyldy", "UserPasswordChangedWithName": "Paidalanuşy {0} üşın paröl özgertıldı", - "UserPolicyUpdatedWithName": "Paidalanuşy {0} üşın saiasattary jaŋartyldy", + "UserPolicyUpdatedWithName": "Paidalanuşy {0} üşın saiasattary jañartyldy", "UserStartedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuda", "UserStoppedPlayingItemWithValues": "{0} — {2} tarapynan {1} oinatuyn toqtatty", "ValueHasBeenAddedToLibrary": "{0} tasyğyşhanağa üstelındı", @@ -94,10 +94,10 @@ "VersionNumber": "Nūsqasy {0}", "Default": "Ädepkı", "TaskDownloadMissingSubtitles": "Joq subtitrlerdı jüktep alu", - "TaskRefreshChannels": "Arnalardy jaŋğyrtu", + "TaskRefreshChannels": "Arnalardy jañğyrtu", "TaskCleanTranscode": "Qaita kodtau katalogyn tazalau", - "TaskUpdatePlugins": "Plaginderdı jaŋartu", - "TaskRefreshPeople": "Adamdardy jaŋğyrtu", + "TaskUpdatePlugins": "Plaginderdı jañartu", + "TaskRefreshPeople": "Adamdardy jañğyrtu", "TaskCleanLogs": "Jūrnal katalogyn tazalau", "TaskRefreshLibrary": "Tasyğyşhanany skanerleu", "TaskRefreshChapterImages": "Sahna suretterın şyğaryp alu", @@ -109,14 +109,14 @@ "TasksMaintenanceCategory": "Qyzmet körsetu", "Undefined": "Anyqtalmağan", "Forced": "Mäjbürlı", - "TaskDownloadMissingSubtitlesDescription": "Metaderekter teŋşelımderı negızınde joq subtitrlerdı İnternetten ızdeidı.", - "TaskRefreshChannelsDescription": "Internet-arnalar mälımetterın jaŋğyrtady.", + "TaskDownloadMissingSubtitlesDescription": "Metaderekter teñşelımderı negızınde joq subtitrlerdı İnternetten ızdeidı.", + "TaskRefreshChannelsDescription": "Internet-arnalar mälımetterın jañğyrtady.", "TaskCleanTranscodeDescription": "Bіr künnen asqan qaita kodtau faildaryn joiady.", - "TaskUpdatePluginsDescription": "Avtomatty türde jaŋartuğa teŋşelgen plaginder üşın jaŋartulardy jüktep alady jäne ornatady.", - "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterın jaŋartady.", + "TaskUpdatePluginsDescription": "Avtomatty türde jañartuğa teñşelgen plaginder üşın jañartulardy jüktep alady jäne ornatady.", + "TaskRefreshPeopleDescription": "Tasyğyşhanadağy aktörler men rejisörler metaderekterın jañartady.", "TaskCleanLogsDescription": "{0} künnen asqan jūrnal faildaryn joiady.", - "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaŋa faildardy skanerleidі jäne metaderekterdı jaŋğyrtady.", + "TaskRefreshLibraryDescription": "Tasyğyşhanadağy jaña faildardy skanerleidі jäne metaderekterdı jañğyrtady.", "TaskRefreshChapterImagesDescription": "Sahnalary bar beineler üşın nobailar jasaidy.", "TaskCleanCacheDescription": "Jüiede qajet emes keştelgen faildardy joiady.", - "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teŋşelgen jasynan asqan jazbalary joiady." + "TaskCleanActivityLogDescription": "Äreket jūrnalyndağy teñşelgen jasynan asqan jazbalary joiady." } From d2e8df1a48be515cbf7c1ec4f88d1133100e1f10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Kucharczyk?= Date: Thu, 29 Apr 2021 17:58:40 +0000 Subject: [PATCH 1624/1930] Translated using Weblate (Czech) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/cs/ --- Emby.Server.Implementations/Localization/Core/cs.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/cs.json b/Emby.Server.Implementations/Localization/Core/cs.json index 7752671837..ff14c1929c 100644 --- a/Emby.Server.Implementations/Localization/Core/cs.json +++ b/Emby.Server.Implementations/Localization/Core/cs.json @@ -39,7 +39,7 @@ "MixedContent": "Smíšený obsah", "Movies": "Filmy", "Music": "Hudba", - "MusicVideos": "Hudební klipy", + "MusicVideos": "Hudební videa", "NameInstallFailed": "Instalace {0} selhala", "NameSeasonNumber": "Sezóna {0}", "NameSeasonUnknown": "Neznámá sezóna", From 566ad0907b9d2331ae004c6702c497b0db8ff433 Mon Sep 17 00:00:00 2001 From: Marcus Hsu Date: Thu, 29 Apr 2021 09:08:31 +0000 Subject: [PATCH 1625/1930] Translated using Weblate (Chinese (Traditional)) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/zh_Hant/ --- Emby.Server.Implementations/Localization/Core/zh-TW.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/zh-TW.json b/Emby.Server.Implementations/Localization/Core/zh-TW.json index affb0e099b..c3b223f631 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-TW.json +++ b/Emby.Server.Implementations/Localization/Core/zh-TW.json @@ -37,7 +37,7 @@ "MixedContent": "混合內容", "Movies": "電影", "Music": "音樂", - "MusicVideos": "音樂MV", + "MusicVideos": "音樂錄影帶", "NameInstallFailed": "{0} 安裝失敗", "NameSeasonNumber": "第 {0} 季", "NameSeasonUnknown": "未知季數", From 9c0d1f676df0d559474e58eeacfadc670f7bcc36 Mon Sep 17 00:00:00 2001 From: Levi Date: Sat, 1 May 2021 11:12:09 +0000 Subject: [PATCH 1626/1930] Translated using Weblate (Swedish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/sv/ --- Emby.Server.Implementations/Localization/Core/sv.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/sv.json b/Emby.Server.Implementations/Localization/Core/sv.json index b5a7fa5b8f..d992bf79b1 100644 --- a/Emby.Server.Implementations/Localization/Core/sv.json +++ b/Emby.Server.Implementations/Localization/Core/sv.json @@ -39,7 +39,7 @@ "MixedContent": "Blandat innehåll", "Movies": "Filmer", "Music": "Musik", - "MusicVideos": "Musikvideos", + "MusicVideos": "Musikvideor", "NameInstallFailed": "{0} installationen misslyckades", "NameSeasonNumber": "Säsong {0}", "NameSeasonUnknown": "Okänd säsong", From 0668ab672182b4ee2e8dded2611d935ef8b7d176 Mon Sep 17 00:00:00 2001 From: Dan Johansen Date: Tue, 4 May 2021 09:42:08 +0000 Subject: [PATCH 1627/1930] Translated using Weblate (Danish) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/da/ --- Emby.Server.Implementations/Localization/Core/da.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/da.json b/Emby.Server.Implementations/Localization/Core/da.json index 051d6d009f..3453507d9e 100644 --- a/Emby.Server.Implementations/Localization/Core/da.json +++ b/Emby.Server.Implementations/Localization/Core/da.json @@ -39,7 +39,7 @@ "MixedContent": "Blandet indhold", "Movies": "Film", "Music": "Musik", - "MusicVideos": "Musikvideoer", + "MusicVideos": "Musik videoer", "NameInstallFailed": "{0} installationen mislykkedes", "NameSeasonNumber": "Sæson {0}", "NameSeasonUnknown": "Ukendt Sæson", From ba8ff2a7bcf49e6441840edf3dc93888ed14b48d Mon Sep 17 00:00:00 2001 From: Benjamin Vraspillai Date: Mon, 3 May 2021 15:35:48 +0000 Subject: [PATCH 1628/1930] Translated using Weblate (Norwegian Nynorsk) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nn/ --- .../Localization/Core/nn.json | 51 ++++++++++--------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json index 6236515b2c..5c0cd5ec50 100644 --- a/Emby.Server.Implementations/Localization/Core/nn.json +++ b/Emby.Server.Implementations/Localization/Core/nn.json @@ -1,25 +1,25 @@ { - "MessageServerConfigurationUpdated": "Tenar konfigurasjonen har blitt oppdatert", + "MessageServerConfigurationUpdated": "Tenarkonfigurasjonen har blitt oppdatert", "MessageNamedServerConfigurationUpdatedWithValue": "Tenar konfigurasjon seksjon {0} har blitt oppdatert", - "MessageApplicationUpdatedTo": "Jellyfin Tenaren har blitt oppdatert til {0}", - "MessageApplicationUpdated": "Jellyfin Tenaren har blitt oppdatert", + "MessageApplicationUpdatedTo": "Jellyfin-tenaren har blitt oppdatert til {0}", + "MessageApplicationUpdated": "Jellyfin-tenaren har blitt oppdatert", "Latest": "Nyaste", "LabelRunningTimeValue": "Speletid: {0}", - "LabelIpAddressValue": "IP adresse: {0}", + "LabelIpAddressValue": "IP-adresse: {0}", "ItemRemovedWithName": "{0} vart fjerna frå biblioteket", "ItemAddedWithName": "{0} vart lagt til i biblioteket", - "Inherit": "Arv", - "HomeVideos": "Heime Videoar", + "Inherit": "Arve", + "HomeVideos": "Heimevideoar", "HeaderRecordingGroups": "Innspelingsgrupper", "HeaderNextUp": "Neste", "HeaderLiveTV": "Direkte TV", - "HeaderFavoriteSongs": "Favoritt Songar", - "HeaderFavoriteShows": "Favoritt Seriar", - "HeaderFavoriteEpisodes": "Favoritt Episodar", - "HeaderFavoriteArtists": "Favoritt Artistar", - "HeaderFavoriteAlbums": "Favoritt Album", + "HeaderFavoriteSongs": "Favorittsongar", + "HeaderFavoriteShows": "Favorittseriar", + "HeaderFavoriteEpisodes": "Favorittepisodar", + "HeaderFavoriteArtists": "Favorittartistar", + "HeaderFavoriteAlbums": "Favorittalbum", "HeaderContinueWatching": "Fortsett å sjå", - "HeaderAlbumArtists": "Album Artist", + "HeaderAlbumArtists": "Albumartistar", "Genres": "Sjangrar", "Folders": "Mapper", "Favorites": "Favorittar", @@ -37,7 +37,7 @@ "AppDeviceValues": "App: {0}, Eining: {1}", "Albums": "Album", "NotificationOptionServerRestartRequired": "Tenaren krev omstart", - "NotificationOptionPluginUpdateInstalled": "Tilleggsprogram-oppdatering vart installert", + "NotificationOptionPluginUpdateInstalled": "Tilleggsprogramoppdatering vart installert", "NotificationOptionPluginUninstalled": "Tilleggsprogram avinstallert", "NotificationOptionPluginInstalled": "Tilleggsprogram installert", "NotificationOptionPluginError": "Tilleggsprogram feila", @@ -48,33 +48,33 @@ "NotificationOptionAudioPlayback": "Lydavspilling påbyrja", "NotificationOptionApplicationUpdateInstalled": "Applikasjonsoppdatering er installert", "NotificationOptionApplicationUpdateAvailable": "Applikasjonsoppdatering er tilgjengeleg", - "NewVersionIsAvailable": "Ein ny versjon av Jellyfin serveren er tilgjengeleg for nedlasting.", + "NewVersionIsAvailable": "Ein ny versjon av Jellyfin-tjenaren er tilgjengeleg for nedlasting.", "NameSeasonUnknown": "Ukjend sesong", "NameSeasonNumber": "Sesong {0}", - "NameInstallFailed": "{0} Installasjonen feila", + "NameInstallFailed": "Installasjonen av {0} feila", "MusicVideos": "Musikkvideoar", "Music": "Musikk", "Movies": "Filmar", "MixedContent": "Blanda innhald", - "Sync": "Synkronisera", + "Sync": "Synkronisere", "TaskDownloadMissingSubtitlesDescription": "Søk Internettet for manglande undertekstar basert på metadatainnstillingar.", "TaskDownloadMissingSubtitles": "Last ned manglande undertekstar", "TaskRefreshChannelsDescription": "Oppdater internettkanalinformasjon.", "TaskRefreshChannels": "Oppdater kanalar", - "TaskCleanTranscodeDescription": "Slett transkodefiler som er meir enn ein dag gamal.", - "TaskCleanTranscode": "Reins transkodemappe", + "TaskCleanTranscodeDescription": "Slett transkodefiler som er meir enn ein dag gammal.", + "TaskCleanTranscode": "Fjern transkodemappe", "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringar for programtillegg som er sette opp til å oppdaterast automatisk.", "TaskUpdatePlugins": "Oppdaterer programtillegg", "TaskRefreshPeopleDescription": "Oppdaterer metadata for skodespelarar og regissørar i mediebiblioteket ditt.", "TaskRefreshPeople": "Oppdater personar", "TaskCleanLogsDescription": "Slett loggfiler som er meir enn {0} dagar gamle.", - "TaskCleanLogs": "Reins loggmappe", + "TaskCleanLogs": "Slett loggmappe", "TaskRefreshLibraryDescription": "Skannar mediebiblioteket ditt for nye filer og oppdaterer metadata.", "TaskRefreshLibrary": "Skann mediebibliotek", "TaskRefreshChapterImagesDescription": "Lager miniatyrbilete for videoar som har kapittel.", "TaskRefreshChapterImages": "Trekk ut kapittelbilete", - "TaskCleanCacheDescription": "Slettar mellomlagra filer som ikkje lengre trengst av systemet.", - "TaskCleanCache": "Rens mappe for hurtiglager", + "TaskCleanCacheDescription": "Sletter mellomlagra filer som ikkje lengre trengst av systemet.", + "TaskCleanCache": "Reingjer mappe for hurtiglager", "TasksChannelsCategory": "Internettkanalar", "TasksApplicationCategory": "Applikasjon", "TasksLibraryCategory": "Bibliotek", @@ -96,7 +96,7 @@ "TvShows": "TV-seriar", "System": "System", "SubtitleDownloadFailureFromForItem": "Feila å laste ned undertekstar frå {0} for {1}", - "StartupEmbyServerIsLoading": "Jellyfintenaren laster. Prøv igjen om litt.", + "StartupEmbyServerIsLoading": "Jellyfin-tenaren laster. Prøv igjen om litt.", "Songs": "Songar", "Shows": "Program", "ServerNameNeedsToBeRestarted": "{0} må omstartast", @@ -112,5 +112,10 @@ "NotificationOptionVideoPlaybackStopped": "Videoavspeling stoppa", "NotificationOptionVideoPlayback": "Videoavspeling starta", "NotificationOptionUserLockedOut": "Brukar er utestengd", - "NotificationOptionTaskFailed": "Planlagt oppgåve feila" + "NotificationOptionTaskFailed": "Planlagt oppgåve feila", + "TaskCleanActivityLogDescription": "Sletter aktivitetslogginnlegg som er eldre enn den konfigurerte alderen.", + "TaskCleanActivityLog": "Slett aktivitetslogg", + "Undefined": "Udefinert", + "Forced": "Tvungen", + "Default": "Standard" } From 323bc75c13f270c3d21f969e75dbd1dca96c7f0b Mon Sep 17 00:00:00 2001 From: emmanuel billeaud Date: Sat, 8 May 2021 18:08:07 +0000 Subject: [PATCH 1629/1930] Translated using Weblate (French) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/fr/ --- Emby.Server.Implementations/Localization/Core/fr.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/fr.json b/Emby.Server.Implementations/Localization/Core/fr.json index d12c1ddec7..ce1493be8a 100644 --- a/Emby.Server.Implementations/Localization/Core/fr.json +++ b/Emby.Server.Implementations/Localization/Core/fr.json @@ -15,7 +15,7 @@ "Favorites": "Favoris", "Folders": "Dossiers", "Genres": "Genres", - "HeaderAlbumArtists": "Artistes", + "HeaderAlbumArtists": "Artistes de l'album", "HeaderContinueWatching": "Continuer à regarder", "HeaderFavoriteAlbums": "Albums favoris", "HeaderFavoriteArtists": "Artistes préférés", @@ -107,7 +107,7 @@ "TaskCleanLogs": "Nettoyer le répertoire des journaux", "TaskRefreshLibraryDescription": "Scanne toute les bibliothèques pour trouver les nouveaux fichiers et rafraîchit les métadonnées.", "TaskRefreshLibrary": "Scanner toutes les Bibliothèques", - "TaskRefreshChapterImagesDescription": "Crée des images de miniature pour les vidéos ayant des chapitres.", + "TaskRefreshChapterImagesDescription": "Crée des vignettes pour les vidéos ayant des chapitres.", "TaskRefreshChapterImages": "Extraire les images de chapitre", "TaskCleanCacheDescription": "Supprime les fichiers de cache dont le système n'a plus besoin.", "TaskCleanCache": "Vider le répertoire cache", From b281488d36e4d4c30c26f7a42df3d32a1aa62166 Mon Sep 17 00:00:00 2001 From: Daniel Wykerd Date: Sun, 9 May 2021 14:50:29 +0000 Subject: [PATCH 1630/1930] Translated using Weblate (Afrikaans) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/af/ --- Emby.Server.Implementations/Localization/Core/af.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/af.json b/Emby.Server.Implementations/Localization/Core/af.json index b029b7042b..4f21c66bc4 100644 --- a/Emby.Server.Implementations/Localization/Core/af.json +++ b/Emby.Server.Implementations/Localization/Core/af.json @@ -115,5 +115,7 @@ "TaskRefreshChapterImages": "Verkry Hoofstuk Beelde", "Undefined": "Ongedefineerd", "Forced": "Geforseer", - "Default": "Oorspronklik" + "Default": "Oorspronklik", + "TaskCleanActivityLogDescription": "Verwyder aktiwiteitsaantekeninge ouer as die opgestelde ouderdom.", + "TaskCleanActivityLog": "Maak Aktiwiteitsaantekeninge Skoon" } From 0115ca9bc26dbdd13923fc8ac611f4ff50e2fdba Mon Sep 17 00:00:00 2001 From: Benjamin Vraspillai Date: Fri, 7 May 2021 22:09:53 +0000 Subject: [PATCH 1631/1930] Translated using Weblate (Norwegian Nynorsk) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nn/ --- .../Localization/Core/nn.json | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json index 5c0cd5ec50..16511e6867 100644 --- a/Emby.Server.Implementations/Localization/Core/nn.json +++ b/Emby.Server.Implementations/Localization/Core/nn.json @@ -37,10 +37,10 @@ "AppDeviceValues": "App: {0}, Eining: {1}", "Albums": "Album", "NotificationOptionServerRestartRequired": "Tenaren krev omstart", - "NotificationOptionPluginUpdateInstalled": "Tilleggsprogramoppdatering vart installert", - "NotificationOptionPluginUninstalled": "Tilleggsprogram avinstallert", - "NotificationOptionPluginInstalled": "Tilleggsprogram installert", - "NotificationOptionPluginError": "Tilleggsprogram feila", + "NotificationOptionPluginUpdateInstalled": "Programvaretilleggoppdatering vart installert", + "NotificationOptionPluginUninstalled": "Programvaretillegg avinstallert", + "NotificationOptionPluginInstalled": "Programvaretillegg installert", + "NotificationOptionPluginError": "Programvaretillegg feila", "NotificationOptionNewLibraryContent": "Nytt innhald er lagt til", "NotificationOptionInstallationFailed": "Installasjonsfeil", "NotificationOptionCameraImageUploaded": "Kamerabilde vart lasta opp", @@ -56,7 +56,7 @@ "Music": "Musikk", "Movies": "Filmar", "MixedContent": "Blanda innhald", - "Sync": "Synkronisere", + "Sync": "Synkroniser", "TaskDownloadMissingSubtitlesDescription": "Søk Internettet for manglande undertekstar basert på metadatainnstillingar.", "TaskDownloadMissingSubtitles": "Last ned manglande undertekstar", "TaskRefreshChannelsDescription": "Oppdater internettkanalinformasjon.", @@ -64,17 +64,17 @@ "TaskCleanTranscodeDescription": "Slett transkodefiler som er meir enn ein dag gammal.", "TaskCleanTranscode": "Fjern transkodemappe", "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringar for programtillegg som er sette opp til å oppdaterast automatisk.", - "TaskUpdatePlugins": "Oppdaterer programtillegg", + "TaskUpdatePlugins": "Oppdaterer programvaretillegg", "TaskRefreshPeopleDescription": "Oppdaterer metadata for skodespelarar og regissørar i mediebiblioteket ditt.", "TaskRefreshPeople": "Oppdater personar", "TaskCleanLogsDescription": "Slett loggfiler som er meir enn {0} dagar gamle.", - "TaskCleanLogs": "Slett loggmappe", + "TaskCleanLogs": "Slett loggmappa", "TaskRefreshLibraryDescription": "Skannar mediebiblioteket ditt for nye filer og oppdaterer metadata.", "TaskRefreshLibrary": "Skann mediebibliotek", "TaskRefreshChapterImagesDescription": "Lager miniatyrbilete for videoar som har kapittel.", "TaskRefreshChapterImages": "Trekk ut kapittelbilete", "TaskCleanCacheDescription": "Sletter mellomlagra filer som ikkje lengre trengst av systemet.", - "TaskCleanCache": "Reingjer mappe for hurtiglager", + "TaskCleanCache": "Fjern hurtigbuffer", "TasksChannelsCategory": "Internettkanalar", "TasksApplicationCategory": "Applikasjon", "TasksLibraryCategory": "Bibliotek", @@ -96,7 +96,7 @@ "TvShows": "TV-seriar", "System": "System", "SubtitleDownloadFailureFromForItem": "Feila å laste ned undertekstar frå {0} for {1}", - "StartupEmbyServerIsLoading": "Jellyfin-tenaren laster. Prøv igjen om litt.", + "StartupEmbyServerIsLoading": "Jellyfin-tenaren laster. Prøv igjen seinare.", "Songs": "Songar", "Shows": "Program", "ServerNameNeedsToBeRestarted": "{0} må omstartast", @@ -106,9 +106,9 @@ "PluginUpdatedWithName": "{0} blei oppdatert", "PluginUninstalledWithName": "{0} blei avinstallert", "PluginInstalledWithName": "{0} blei installert", - "Plugin": "Programtillegg", + "Plugin": "Programvaretillegg", "Playlists": "Speleliste", - "Photos": "Foto", + "Photos": "Bilete", "NotificationOptionVideoPlaybackStopped": "Videoavspeling stoppa", "NotificationOptionVideoPlayback": "Videoavspeling starta", "NotificationOptionUserLockedOut": "Brukar er utestengd", From b0a12c0bb0432bfc7c0e903f85d40a7cf64a8d2f Mon Sep 17 00:00:00 2001 From: Benjamin Vraspillai Date: Fri, 7 May 2021 22:02:27 +0000 Subject: [PATCH 1632/1930] =?UTF-8?q?Translated=20using=20Weblate=20(Norwe?= =?UTF-8?q?gian=20Bokm=C3=A5l)=20Translation:=20Jellyfin/Jellyfin=20Transl?= =?UTF-8?q?ate-URL:=20https://translate.jellyfin.org/projects/jellyfin/jel?= =?UTF-8?q?lyfin-core/nb=5FNO/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Localization/Core/nb.json | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index a4f957a3a6..fbe1f7c4d5 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -30,20 +30,20 @@ "ItemAddedWithName": "{0} ble lagt til i biblioteket", "ItemRemovedWithName": "{0} ble fjernet fra biblioteket", "LabelIpAddressValue": "IP-adresse: {0}", - "LabelRunningTimeValue": "Kjøretid {0}", + "LabelRunningTimeValue": "Spilletid {0}", "Latest": "Siste", - "MessageApplicationUpdated": "Jellyfin Server har blitt oppdatert", - "MessageApplicationUpdatedTo": "Jellyfin Server ble oppdatert til {0}", - "MessageNamedServerConfigurationUpdatedWithValue": "Serverkonfigurasjon seksjon {0} har blitt oppdatert", - "MessageServerConfigurationUpdated": "Serverkonfigurasjon er oppdatert", + "MessageApplicationUpdated": "Jellyfin-tjeneren har blitt oppdatert", + "MessageApplicationUpdatedTo": "Jellyfin-tjeneren ble oppdatert til {0}", + "MessageNamedServerConfigurationUpdatedWithValue": "Tjenerkonfigurasjonsseksjon {0} har blitt oppdatert", + "MessageServerConfigurationUpdated": "Tjenerkonfigurasjon er oppdatert", "MixedContent": "Blandet innhold", "Movies": "Filmer", "Music": "Musikk", "MusicVideos": "Musikkvideoer", - "NameInstallFailed": "{0}-installasjonen mislyktes", + "NameInstallFailed": "Installasjonen av {0} mislyktes", "NameSeasonNumber": "Sesong {0}", - "NameSeasonUnknown": "Sesong ukjent", - "NewVersionIsAvailable": "En ny versjon av Jellyfin Server er tilgjengelig for nedlasting.", + "NameSeasonUnknown": "Ukjent sesong", + "NewVersionIsAvailable": "En ny versjon av Jellyfin-tjeneren er tilgjengelig for nedlasting.", "NotificationOptionApplicationUpdateAvailable": "En programvareoppdatering er tilgjengelig", "NotificationOptionApplicationUpdateInstalled": "Applikasjonsoppdatering installert", "NotificationOptionAudioPlayback": "Lydavspilling startet", @@ -51,18 +51,18 @@ "NotificationOptionCameraImageUploaded": "Kamerabilde lastet opp", "NotificationOptionInstallationFailed": "Installasjonen feilet", "NotificationOptionNewLibraryContent": "Nytt innhold lagt til", - "NotificationOptionPluginError": "Pluginfeil", - "NotificationOptionPluginInstalled": "Plugin installert", - "NotificationOptionPluginUninstalled": "Plugin avinstallert", - "NotificationOptionPluginUpdateInstalled": "Pluginoppdatering installert", - "NotificationOptionServerRestartRequired": "Serveromstart er nødvendig", + "NotificationOptionPluginError": "Programvareutvidelsesfeil", + "NotificationOptionPluginInstalled": "Programvareutvidelse installert", + "NotificationOptionPluginUninstalled": "Programvareutvidelse avinstallert", + "NotificationOptionPluginUpdateInstalled": "Programvareutvidelsesoppdatering installert", + "NotificationOptionServerRestartRequired": "Tjeneromstart er nødvendig", "NotificationOptionTaskFailed": "Feil under utføring av planlagt oppgave", "NotificationOptionUserLockedOut": "Bruker er utestengt", "NotificationOptionVideoPlayback": "Videoavspilling startet", "NotificationOptionVideoPlaybackStopped": "Videoavspilling stoppet", "Photos": "Bilder", "Playlists": "Spillelister", - "Plugin": "Plugin", + "Plugin": "Programvareutvidelse", "PluginInstalledWithName": "{0} ble installert", "PluginUninstalledWithName": "{0} ble avinstallert", "PluginUpdatedWithName": "{0} ble oppdatert", @@ -72,7 +72,7 @@ "ServerNameNeedsToBeRestarted": "{0} må startes på nytt", "Shows": "Program", "Songs": "Sanger", - "StartupEmbyServerIsLoading": "Jellyfin Server laster. Prøv igjen snart.", + "StartupEmbyServerIsLoading": "Jellyfin-tjener laster. Prøv igjen snart.", "SubtitleDownloadFailureForItem": "En feil oppstå under nedlasting av undertekster for {0}", "SubtitleDownloadFailureFromForItem": "Kunne ikke laste ned undertekster fra {0} for {1}", "Sync": "Synkroniser", @@ -86,37 +86,37 @@ "UserOfflineFromDevice": "{0} har koblet fra {1}", "UserOnlineFromDevice": "{0} er tilkoblet fra {1}", "UserPasswordChangedWithName": "Passordet for {0} er oppdatert", - "UserPolicyUpdatedWithName": "Brukerpolicyen har blitt oppdatert for {0}", + "UserPolicyUpdatedWithName": "Brukerretningslinjene har blitt oppdatert for {0}", "UserStartedPlayingItemWithValues": "{0} har startet avspilling {1} på {2}", "UserStoppedPlayingItemWithValues": "{0} har stoppet avspilling {1}", "ValueHasBeenAddedToLibrary": "{0} har blitt lagt til i mediebiblioteket ditt", "ValueSpecialEpisodeName": "Spesialepisode - {0}", "VersionNumber": "Versjon {0}", - "TasksChannelsCategory": "Internett kanaler", + "TasksChannelsCategory": "Internettkanaler", "TasksApplicationCategory": "Applikasjon", "TasksLibraryCategory": "Bibliotek", "TasksMaintenanceCategory": "Vedlikehold", - "TaskCleanCache": "Tøm buffer katalog", + "TaskCleanCache": "Tøm hurtigbuffer", "TaskRefreshLibrary": "Skann mediebibliotek", "TaskRefreshChapterImagesDescription": "Lager forhåndsvisningsbilder for videoer som har kapitler.", - "TaskRefreshChapterImages": "Trekk ut Kapittelbilder", + "TaskRefreshChapterImages": "Trekk ut kapittelbilder", "TaskCleanCacheDescription": "Sletter mellomlagrede filer som ikke lengre trengs av systemet.", - "TaskDownloadMissingSubtitlesDescription": "Søker etter manglende underteksting på nett basert på metadatakonfigurasjon.", - "TaskDownloadMissingSubtitles": "Last ned manglende underteksting", - "TaskRefreshChannelsDescription": "Frisker opp internettkanalinformasjon.", - "TaskRefreshChannels": "Oppfrisk kanaler", + "TaskDownloadMissingSubtitlesDescription": "Søker etter manglende undertekster på nett basert på metadatakonfigurasjon.", + "TaskDownloadMissingSubtitles": "Last ned manglende undertekster", + "TaskRefreshChannelsDescription": "Oppdaterer internettkanalinformasjon.", + "TaskRefreshChannels": "Oppdater kanaler", "TaskCleanTranscodeDescription": "Sletter omkodede filer som er mer enn én dag gamle.", "TaskCleanTranscode": "Tøm transkodingmappe", - "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringer for utvidelser som er stilt inn til å oppdatere automatisk.", - "TaskUpdatePlugins": "Oppdater utvidelser", + "TaskUpdatePluginsDescription": "Laster ned og installerer oppdateringer for programvareutvidelser som er stilt inn til å oppdatere automatisk.", + "TaskUpdatePlugins": "Oppdater programvareutvidelse", "TaskRefreshPeopleDescription": "Oppdaterer metadata for skuespillere og regissører i mediebiblioteket ditt.", - "TaskRefreshPeople": "Oppfrisk personer", + "TaskRefreshPeople": "Oppdater personer", "TaskCleanLogsDescription": "Sletter loggfiler som er eldre enn {0} dager gamle.", "TaskCleanLogs": "Tøm loggmappe", "TaskRefreshLibraryDescription": "Skanner mediebibliotekene dine for nye filer og oppdaterer metadata.", "TaskCleanActivityLog": "Tøm aktivitetslogg", "Undefined": "Udefinert", - "Forced": "Tvungen", + "Forced": "Tvunget", "Default": "Standard", "TaskCleanActivityLogDescription": "Sletter oppføringer i aktivitetsloggen som er eldre enn den konfigurerte alderen." } From a315ab4fa49f86c288ff4e4c23387c4f085f842e Mon Sep 17 00:00:00 2001 From: thecoldicelander Date: Sat, 8 May 2021 02:04:23 +0000 Subject: [PATCH 1633/1930] Translated using Weblate (Icelandic) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/is/ --- Emby.Server.Implementations/Localization/Core/is.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/is.json b/Emby.Server.Implementations/Localization/Core/is.json index 0f769eaada..b262a8b424 100644 --- a/Emby.Server.Implementations/Localization/Core/is.json +++ b/Emby.Server.Implementations/Localization/Core/is.json @@ -25,7 +25,7 @@ "Channels": "Stöðvar", "CameraImageUploadedFrom": "Ný ljósmynd frá myndavél hefur verið hlaðið upp frá {0}", "Books": "Bækur", - "AuthenticationSucceededWithUserName": "{0} náði að auðkennast", + "AuthenticationSucceededWithUserName": "{0} auðkenning tókst", "Artists": "Listamaður", "Application": "Forrit", "AppDeviceValues": "Snjallforrit: {0}, Tæki: {1}", @@ -106,5 +106,6 @@ "TasksChannelsCategory": "Netrásir", "TasksApplicationCategory": "Forrit", "TasksLibraryCategory": "Miðlasafn", - "TasksMaintenanceCategory": "Viðhald" + "TasksMaintenanceCategory": "Viðhald", + "Default": "Sjálfgefið" } From 289c06adca53cd34af3657c3c931f0f2c770fd61 Mon Sep 17 00:00:00 2001 From: Erikas Date: Thu, 6 May 2021 11:40:46 +0000 Subject: [PATCH 1634/1930] Translated using Weblate (Lithuanian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/lt/ --- Emby.Server.Implementations/Localization/Core/lt-LT.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/lt-LT.json b/Emby.Server.Implementations/Localization/Core/lt-LT.json index 9920ef4d51..f3a131d405 100644 --- a/Emby.Server.Implementations/Localization/Core/lt-LT.json +++ b/Emby.Server.Implementations/Localization/Core/lt-LT.json @@ -114,8 +114,9 @@ "TasksApplicationCategory": "Programa", "TasksLibraryCategory": "Mediateka", "TasksMaintenanceCategory": "Priežiūra", - "TaskCleanActivityLog": "Švarus veiklos žurnalas", + "TaskCleanActivityLog": "Išvalyti veiklos žurnalą", "Undefined": "Neapibrėžtas", "Forced": "Priverstas", - "Default": "Numatytas" + "Default": "Numatytas", + "TaskCleanActivityLogDescription": "Ištrina veiklos žuranlo įrašus, kurie yra senesni nei nustatytas amžius." } From b9163ff2aa13f745f61eba6194818707c1de3b8f Mon Sep 17 00:00:00 2001 From: Ishan Badgainya Date: Fri, 7 May 2021 08:21:24 +0000 Subject: [PATCH 1635/1930] Translated using Weblate (Hindi) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/hi/ --- Emby.Server.Implementations/Localization/Core/hi.json | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/hi.json b/Emby.Server.Implementations/Localization/Core/hi.json index ef3697b15f..82dc601bcb 100644 --- a/Emby.Server.Implementations/Localization/Core/hi.json +++ b/Emby.Server.Implementations/Localization/Core/hi.json @@ -51,5 +51,14 @@ "Latest": "सबसे नया", "LabelIpAddressValue": "आई पी एड्रेस: {0}", "ItemRemovedWithName": "{0} लाइब्रेरी में से निकाल दिया है", - "HomeVideos": "होम वीडियोस" + "HomeVideos": "होम वीडियोस", + "NotificationOptionVideoPlayback": "वीडियो प्लेबैक शुरू हुआ", + "NotificationOptionUserLockedOut": "उपयोगकर्ता लॉक हो गया", + "NotificationOptionTaskFailed": "निर्धारित कार्य विफलता", + "NotificationOptionServerRestartRequired": "सर्वर पुनरारंभ आवश्यक है", + "NotificationOptionPluginUpdateInstalled": "प्लगइन अद्यतन स्थापित", + "NotificationOptionNewLibraryContent": "नई सामग्री जोड़ी गई", + "LabelRunningTimeValue": "चलने का समय: {0}", + "ItemAddedWithName": "{0} को लाइब्रेरी में जोड़ा गया", + "Inherit": "इनहेरिट" } From 88bfd1bcf45bdfa6c64e3439d7f406799645163c Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Mon, 10 May 2021 17:58:21 +0200 Subject: [PATCH 1636/1930] Add tests for LocalizationManager --- .../Localization/LocalizationManagerTests.cs | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs diff --git a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs new file mode 100644 index 0000000000..acdf74c4f7 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs @@ -0,0 +1,167 @@ +using System.Linq; +using System.Threading.Tasks; +using Emby.Server.Implementations.Localization; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Localization +{ + public class LocalizationManagerTests + { + private LocalizationManager _localizationManager = null!; + + public LocalizationManagerTests() + { + var config = new ServerConfiguration() { UICulture = "de-DE" }; + Setup(config); + } + + [Fact] + public void GetCountries_All_Success() + { + var countries = _localizationManager.GetCountries(); + var countryInfos = countries.ToList(); + + Assert.Equal(139, countryInfos.Count); + + var germany = countryInfos.FirstOrDefault(x => x.Name == "DE"); + Assert.NotNull(germany); + Assert.Equal("Germany", germany!.DisplayName); + Assert.Equal("DEU", germany!.ThreeLetterISORegionName); + Assert.Equal("DE", germany!.TwoLetterISORegionName); + } + + [Fact] + public async Task GetCultures_All_Success() + { + await _localizationManager.LoadAll(); + var cultures = _localizationManager.GetCultures().ToList(); + + Assert.Equal(189, cultures.Count); + + var germany = cultures.FirstOrDefault(x => x.TwoLetterISOLanguageName == "de"); + Assert.NotNull(germany); + Assert.Equal("ger", germany!.ThreeLetterISOLanguageName); + Assert.Equal("German", germany!.DisplayName); + Assert.Equal("German", germany!.Name); + Assert.Contains("deu", germany!.ThreeLetterISOLanguageNames); + Assert.Contains("ger", germany!.ThreeLetterISOLanguageNames); + } + + [Theory] + [InlineData("de")] + [InlineData("ger")] + [InlineData("german")] + public async Task FindLanguage_Valid_Success(string identifier) + { + await _localizationManager.LoadAll(); + + var germany = _localizationManager.FindLanguageInfo(identifier); + Assert.NotNull(germany); + + Assert.Equal("ger", germany!.ThreeLetterISOLanguageName); + Assert.Equal("German", germany!.DisplayName); + Assert.Equal("German", germany!.Name); + Assert.Contains("deu", germany!.ThreeLetterISOLanguageNames); + Assert.Contains("ger", germany!.ThreeLetterISOLanguageNames); + } + + [Fact] + public async Task ParentalRatings_Default_Success() + { + await _localizationManager.LoadAll(); + var ratings = _localizationManager.GetParentalRatings().ToList(); + + Assert.Equal(23, ratings.Count); + + var tvma = ratings.FirstOrDefault(x => x.Name == "TV-MA"); + Assert.NotNull(tvma); + Assert.Equal(9, tvma!.Value); + } + + [Fact] + public async Task ParentalRatings_ConfiguredCountryCode_Success() + { + Setup(new ServerConfiguration() + { + MetadataCountryCode = "DE" + }); + await _localizationManager.LoadAll(); + var ratings = _localizationManager.GetParentalRatings().ToList(); + + Assert.Equal(10, ratings.Count); + + var fsk = ratings.FirstOrDefault(x => x.Name == "FSK-12"); + Assert.NotNull(fsk); + Assert.Equal(7, fsk!.Value); + } + + [Theory] + [InlineData("CA-R", "CA", 10)] + [InlineData("FSK-16", "DE", 8)] + [InlineData("FSK-18", "DE", 9)] + [InlineData("FSK-18", "US", 9)] + [InlineData("TV-MA", "US", 9)] + [InlineData("XXX", "asdf", 100)] + [InlineData("Germany: FSK-18", "DE", 9)] + public async Task GetRatingLevelFromString_Valid_Success(string value, string countryCode, int expectedLevel) + { + Setup(new ServerConfiguration() + { + MetadataCountryCode = countryCode + }); + await _localizationManager.LoadAll(); + var level = _localizationManager.GetRatingLevel(value); + Assert.NotNull(level); + Assert.Equal(expectedLevel, level!); + } + + [Fact] + public async Task GetRatingLevelFromString_Unrated_Success() + { + await _localizationManager.LoadAll(); + Assert.Null(_localizationManager.GetRatingLevel("n/a")); + } + + [Theory] + [InlineData("Default", "Default")] + [InlineData("HeaderLiveTV", "Live TV")] + public void GetLocalizedString_Valid_Success(string key, string expected) + { + Setup(new ServerConfiguration() + { + UICulture = "en-US" + }); + + var translated = _localizationManager.GetLocalizedString(key); + Assert.NotNull(translated); + Assert.Equal(expected, translated); + } + + [Fact] + public void GetLocalizedString_Invalid_Success() + { + Setup(new ServerConfiguration() + { + UICulture = "en-US" + }); + + var key = "SuperInvalidTranslationKeyThatWillNeverBeAdded"; + + var translated = _localizationManager.GetLocalizedString(key); + Assert.NotNull(translated); + Assert.Equal(key, translated); + } + + private void Setup(ServerConfiguration config) + { + var mockConfiguration = new Mock(); + mockConfiguration.SetupGet(x => x.Configuration).Returns(config); + + _localizationManager = new LocalizationManager(mockConfiguration.Object, new NullLogger()); + } + } +} From db2b53a4b52d0c1e9797bfc70030b04421ba46a6 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Mon, 10 May 2021 18:05:35 +0200 Subject: [PATCH 1637/1930] Refactor LocalizationManager and remove dead method --- .../Localization/LocalizationManager.cs | 426 +++++++++--------- .../Globalization/ILocalizationManager.cs | 8 - 2 files changed, 203 insertions(+), 231 deletions(-) diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 220e423bf5..efbccaa5b9 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -25,18 +25,18 @@ namespace Emby.Server.Implementations.Localization private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly; private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" }; - private readonly IServerConfigurationManager _configurationManager; - private readonly ILogger _logger; - private readonly Dictionary> _allParentalRatings = new Dictionary>(StringComparer.OrdinalIgnoreCase); + private readonly IServerConfigurationManager _configurationManager; + private readonly ConcurrentDictionary> _dictionaries = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); - private List _cultures; - private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; + private readonly ILogger _logger; + + private List _cultures; /// /// Initializes a new instance of the class. @@ -51,57 +51,6 @@ namespace Emby.Server.Implementations.Localization _logger = logger; } - /// - /// Loads all resources into memory. - /// - /// . - public async Task LoadAll() - { - const string RatingsResource = "Emby.Server.Implementations.Localization.Ratings."; - - // Extract from the assembly - foreach (var resource in _assembly.GetManifestResourceNames()) - { - if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal)) - { - continue; - } - - string countryCode = resource.Substring(RatingsResource.Length, 2); - var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); - - using (var str = _assembly.GetManifestResourceStream(resource)) - using (var reader = new StreamReader(str)) - { - await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) - { - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - string[] parts = line.Split(','); - if (parts.Length == 2 - && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) - { - var name = parts[0]; - dict.Add(name, new ParentalRating(name, value)); - } -#if DEBUG - else - { - _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode); - } -#endif - } - } - - _allParentalRatings[countryCode] = dict; - } - - await LoadCultures().ConfigureAwait(false); - } - /// /// Gets the cultures. /// @@ -109,62 +58,6 @@ namespace Emby.Server.Implementations.Localization public IEnumerable GetCultures() => _cultures; - private async Task LoadCultures() - { - List list = new List(); - - const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt"; - - using (var stream = _assembly.GetManifestResourceStream(ResourcePath)) - using (var reader = new StreamReader(stream)) - { - await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) - { - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - var parts = line.Split('|'); - - if (parts.Length == 5) - { - string name = parts[3]; - if (string.IsNullOrWhiteSpace(name)) - { - continue; - } - - string twoCharName = parts[2]; - if (string.IsNullOrWhiteSpace(twoCharName)) - { - continue; - } - - string[] threeletterNames; - if (string.IsNullOrWhiteSpace(parts[1])) - { - threeletterNames = new[] { parts[0] }; - } - else - { - threeletterNames = new[] { parts[0], parts[1] }; - } - - list.Add(new CultureDto - { - DisplayName = name, - Name = name, - ThreeLetterISOLanguageNames = threeletterNames, - TwoLetterISOLanguageName = twoCharName - }); - } - } - } - - _cultures = list; - } - /// public CultureDto FindLanguageInfo(string language) => GetCultures() @@ -186,34 +79,6 @@ namespace Emby.Server.Implementations.Localization public IEnumerable GetParentalRatings() => GetParentalRatingsDictionary().Values; - /// - /// Gets the parental ratings dictionary. - /// - /// . - private Dictionary GetParentalRatingsDictionary() - { - var countryCode = _configurationManager.Configuration.MetadataCountryCode; - - if (string.IsNullOrEmpty(countryCode)) - { - countryCode = "us"; - } - - return GetRatings(countryCode) ?? GetRatings("us"); - } - - /// - /// Gets the ratings. - /// - /// The country code. - /// The ratings. - private Dictionary GetRatings(string countryCode) - { - _allParentalRatings.TryGetValue(countryCode, out var value); - - return value; - } - /// public int? GetRatingLevel(string rating) { @@ -250,7 +115,7 @@ namespace Emby.Server.Implementations.Localization var index = rating.IndexOf(':', StringComparison.Ordinal); if (index != -1) { - rating = rating.Substring(index).TrimStart(':').Trim(); + rating = rating.Substring(index + 1).Trim(); if (!string.IsNullOrWhiteSpace(rating)) { @@ -262,20 +127,6 @@ namespace Emby.Server.Implementations.Localization return null; } - /// - public bool HasUnicodeCategory(string value, UnicodeCategory category) - { - foreach (var chr in value) - { - if (char.GetUnicodeCategory(chr) == category) - { - return true; - } - } - - return false; - } - /// public string GetLocalizedString(string phrase) { @@ -305,74 +156,6 @@ namespace Emby.Server.Implementations.Localization return phrase; } - private Dictionary GetLocalizationDictionary(string culture) - { - if (string.IsNullOrEmpty(culture)) - { - throw new ArgumentNullException(nameof(culture)); - } - - const string Prefix = "Core"; - - return _dictionaries.GetOrAdd( - culture, - f => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult()); - } - - private async Task> GetDictionary(string prefix, string culture, string baseFilename) - { - if (string.IsNullOrEmpty(culture)) - { - throw new ArgumentNullException(nameof(culture)); - } - - var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); - - var namespaceName = GetType().Namespace + "." + prefix; - - await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false); - await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false); - - return dictionary; - } - - private async Task CopyInto(IDictionary dictionary, string resourcePath) - { - using (var stream = _assembly.GetManifestResourceStream(resourcePath)) - { - // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain - if (stream != null) - { - var dict = await JsonSerializer.DeserializeAsync>(stream, _jsonOptions).ConfigureAwait(false); - - foreach (var key in dict.Keys) - { - dictionary[key] = dict[key]; - } - } - else - { - _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath); - } - } - } - - private static string GetResourceFilename(string culture) - { - var parts = culture.Split('-'); - - if (parts.Length == 2) - { - culture = parts[0].ToLowerInvariant() + "-" + parts[1].ToUpperInvariant(); - } - else - { - culture = culture.ToLowerInvariant(); - } - - return culture + ".json"; - } - /// public IEnumerable GetLocalizationOptions() { @@ -414,5 +197,202 @@ namespace Emby.Server.Implementations.Localization yield return new LocalizationOption("Turkish", "tr"); yield return new LocalizationOption("Tiếng Việt", "vi"); } + + /// + /// Loads all resources into memory. + /// + /// . + public async Task LoadAll() + { + const string RatingsResource = "Emby.Server.Implementations.Localization.Ratings."; + + // Extract from the assembly + foreach (var resource in _assembly.GetManifestResourceNames()) + { + if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal)) + { + continue; + } + + string countryCode = resource.Substring(RatingsResource.Length, 2); + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + + await using var str = _assembly.GetManifestResourceStream(resource); + using var reader = new StreamReader(str); + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) + { + if (string.IsNullOrWhiteSpace(line)) + { + continue; + } + + string[] parts = line.Split(','); + if (parts.Length == 2 + && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) + { + var name = parts[0]; + dict.Add(name, new ParentalRating(name, value)); + } +#if DEBUG + else + { + _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode); + } +#endif + } + + _allParentalRatings[countryCode] = dict; + } + + await LoadCultures().ConfigureAwait(false); + } + + private async Task LoadCultures() + { + List list = new List(); + + const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt"; + + await using var stream = _assembly.GetManifestResourceStream(ResourcePath); + using var reader = new StreamReader(stream); + await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) + { + if (string.IsNullOrWhiteSpace(line)) + { + continue; + } + + var parts = line.Split('|'); + + if (parts.Length == 5) + { + string name = parts[3]; + if (string.IsNullOrWhiteSpace(name)) + { + continue; + } + + string twoCharName = parts[2]; + if (string.IsNullOrWhiteSpace(twoCharName)) + { + continue; + } + + string[] threeletterNames; + if (string.IsNullOrWhiteSpace(parts[1])) + { + threeletterNames = new[] { parts[0] }; + } + else + { + threeletterNames = new[] { parts[0], parts[1] }; + } + + list.Add(new CultureDto + { + DisplayName = name, + Name = name, + ThreeLetterISOLanguageNames = threeletterNames, + TwoLetterISOLanguageName = twoCharName + }); + } + } + + _cultures = list; + } + + /// + /// Gets the parental ratings dictionary. + /// + /// . + private Dictionary GetParentalRatingsDictionary() + { + var countryCode = _configurationManager.Configuration.MetadataCountryCode; + + if (string.IsNullOrEmpty(countryCode)) + { + countryCode = "us"; + } + + return GetRatings(countryCode) ?? GetRatings("us"); + } + + /// + /// Gets the ratings. + /// + /// The country code. + /// The ratings. + private Dictionary GetRatings(string countryCode) + { + _allParentalRatings.TryGetValue(countryCode, out var value); + + return value; + } + + private Dictionary GetLocalizationDictionary(string culture) + { + if (string.IsNullOrEmpty(culture)) + { + throw new ArgumentNullException(nameof(culture)); + } + + const string Prefix = "Core"; + + return _dictionaries.GetOrAdd( + culture, + _ => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult()); + } + + private async Task> GetDictionary(string prefix, string culture, string baseFilename) + { + if (string.IsNullOrEmpty(culture)) + { + throw new ArgumentNullException(nameof(culture)); + } + + var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); + + var namespaceName = GetType().Namespace + "." + prefix; + + await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false); + await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false); + + return dictionary; + } + + private async Task CopyInto(IDictionary dictionary, string resourcePath) + { + await using var stream = _assembly.GetManifestResourceStream(resourcePath); + // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain + if (stream != null) + { + var dict = await JsonSerializer.DeserializeAsync>(stream, _jsonOptions).ConfigureAwait(false); + + foreach (var key in dict.Keys) + { + dictionary[key] = dict[key]; + } + } + else + { + _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath); + } + } + + private static string GetResourceFilename(string culture) + { + var parts = culture.Split('-'); + + if (parts.Length == 2) + { + culture = parts[0].ToLowerInvariant() + "-" + parts[1].ToUpperInvariant(); + } + else + { + culture = culture.ToLowerInvariant(); + } + + return culture + ".json"; + } } } diff --git a/MediaBrowser.Model/Globalization/ILocalizationManager.cs b/MediaBrowser.Model/Globalization/ILocalizationManager.cs index baefeb39cf..e0e7317efd 100644 --- a/MediaBrowser.Model/Globalization/ILocalizationManager.cs +++ b/MediaBrowser.Model/Globalization/ILocalizationManager.cs @@ -56,14 +56,6 @@ namespace MediaBrowser.Model.Globalization /// . IEnumerable GetLocalizationOptions(); - /// - /// Checks if the string contains a character with the specified unicode category. - /// - /// The string. - /// The unicode category. - /// Wether or not the string contains a character with the specified unicode category. - bool HasUnicodeCategory(string value, UnicodeCategory category); - /// /// Returns the correct for the given language. /// From cb01dd8684824ab74e05b8b4d4aaa462cedf0929 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Mon, 10 May 2021 20:51:41 +0200 Subject: [PATCH 1638/1930] Use TMDb parental rating building from movies for shows --- .../Plugins/Tmdb/Movies/TmdbMovieProvider.cs | 7 +------ .../Plugins/Tmdb/TV/TmdbSeriesProvider.cs | 2 +- MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs index d22c1b50aa..4a0884c079 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs @@ -206,12 +206,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies if (ourRelease != null) { - var ratingPrefix = string.Equals(info.MetadataCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? string.Empty : info.MetadataCountryCode + "-"; - var newRating = ratingPrefix + ourRelease.Certification; - - newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase); - - movie.OfficialRating = newRating; + movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification); } else if (usRelease != null) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs index 496e1ae256..da76345b5b 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs @@ -300,7 +300,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV if (ourRelease != null) { - series.OfficialRating = ourRelease.Rating; + series.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Rating); } else if (usRelease != null) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 2498ce9c42..b4e165f82b 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -173,5 +173,20 @@ namespace MediaBrowser.Providers.Plugins.Tmdb return imageLanguage; } + + /// + /// Combines the metadata country code and the parental rating from the Api into the value we store in our database. + /// + /// The Iso 3166-1 country code of the rating country. + /// The rating value returned by the Tmdb Api. + /// The combined parental rating of country code+rating value. + public static string BuildParentalRating(string countryCode, string ratingValue) + { + // exclude US because we store us values as TV-14 without the country code. + var ratingPrefix = string.Equals(countryCode, "US", StringComparison.OrdinalIgnoreCase) ? string.Empty : countryCode + "-"; + var newRating = ratingPrefix + ratingValue; + + return newRating.Replace("DE-", "FSK-", StringComparison.OrdinalIgnoreCase); + } } } From 5b08bdda371fbb7221cbe408f4b5f903053df5c6 Mon Sep 17 00:00:00 2001 From: Haziq Rohaizan Date: Mon, 10 May 2021 20:59:48 +0000 Subject: [PATCH 1639/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- .../Localization/Core/ms.json | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index 5e3d095ff1..df22f76686 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -39,7 +39,7 @@ "MixedContent": "Kandungan campuran", "Movies": "Filem", "Music": "Muzik", - "MusicVideos": "Video muzik", + "MusicVideos": "Muzik video", "NameInstallFailed": "{0} pemasangan gagal", "NameSeasonNumber": "Musim {0}", "NameSeasonUnknown": "Musim Tidak Diketahui", @@ -60,7 +60,7 @@ "NotificationOptionUserLockedOut": "User locked out", "NotificationOptionVideoPlayback": "Video playback started", "NotificationOptionVideoPlaybackStopped": "Video playback stopped", - "Photos": "Photos", + "Photos": "Gambar", "Playlists": "Playlists", "Plugin": "Plugin", "PluginInstalledWithName": "{0} was installed", @@ -82,14 +82,22 @@ "UserCreatedWithName": "User {0} has been created", "UserDeletedWithName": "User {0} has been deleted", "UserDownloadingItemWithValues": "{0} is downloading {1}", - "UserLockedOutWithName": "User {0} has been locked out", - "UserOfflineFromDevice": "{0} has disconnected from {1}", - "UserOnlineFromDevice": "{0} is online from {1}", - "UserPasswordChangedWithName": "Password has been changed for user {0}", - "UserPolicyUpdatedWithName": "User policy has been updated for {0}", + "UserLockedOutWithName": "Pengguna {0} telah dikunci", + "UserOfflineFromDevice": "{0} telah terputus dari {1}", + "UserOnlineFromDevice": "{0} dalam talian dari {1}", + "UserPasswordChangedWithName": "Kata laluan telah diubah untuk pengguna {0}", + "UserPolicyUpdatedWithName": "Dasar pengguna telah dikemas kini untuk {0}", "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}", "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}", "ValueHasBeenAddedToLibrary": "{0} has been added to your media library", "ValueSpecialEpisodeName": "Khas - {0}", - "VersionNumber": "Versi {0}" + "VersionNumber": "Versi {0}", + "TaskCleanActivityLog": "Log Aktiviti Bersih", + "TasksChannelsCategory": "Saluran Internet", + "TasksApplicationCategory": "Aplikasi", + "TasksLibraryCategory": "Perpustakaan", + "TasksMaintenanceCategory": "Penyelenggaraan", + "Undefined": "Tidak ditentukan", + "Forced": "Paksa", + "Default": "Asal" } From af5b09bd97cf91a39dec0b0394f84e46d56a8199 Mon Sep 17 00:00:00 2001 From: archon eleven Date: Mon, 10 May 2021 21:00:57 +0000 Subject: [PATCH 1640/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- Emby.Server.Implementations/Localization/Core/ms.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index df22f76686..2e0c113a20 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -60,8 +60,8 @@ "NotificationOptionUserLockedOut": "User locked out", "NotificationOptionVideoPlayback": "Video playback started", "NotificationOptionVideoPlaybackStopped": "Video playback stopped", - "Photos": "Gambar", - "Playlists": "Playlists", + "Photos": "Gambar-gambar", + "Playlists": "Senarai ulangmain", "Plugin": "Plugin", "PluginInstalledWithName": "{0} was installed", "PluginUninstalledWithName": "{0} was uninstalled", From c9db6a78ee9cd8754b7afc7e61950f4d8521e77a Mon Sep 17 00:00:00 2001 From: archon eleven Date: Mon, 10 May 2021 21:15:43 +0000 Subject: [PATCH 1641/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- .../Localization/Core/ms.json | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index 2e0c113a20..104e116ab5 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -45,14 +45,14 @@ "NameSeasonUnknown": "Musim Tidak Diketahui", "NewVersionIsAvailable": "Versi terbaru Jellyfin Server bersedia untuk dimuat turunkan.", "NotificationOptionApplicationUpdateAvailable": "Kemas kini aplikasi telah sedia", - "NotificationOptionApplicationUpdateInstalled": "Application update installed", - "NotificationOptionAudioPlayback": "Audio playback started", - "NotificationOptionAudioPlaybackStopped": "Audio playback stopped", - "NotificationOptionCameraImageUploaded": "Camera image uploaded", + "NotificationOptionApplicationUpdateInstalled": "Kemas kini aplikasi telah dipasang", + "NotificationOptionAudioPlayback": "Ulangmain audio bermula", + "NotificationOptionAudioPlaybackStopped": "Ulangmain audio dihentikan", + "NotificationOptionCameraImageUploaded": "Imej kamera telah dimuatnaik", "NotificationOptionInstallationFailed": "Pemasangan gagal", - "NotificationOptionNewLibraryContent": "New content added", - "NotificationOptionPluginError": "Plugin failure", - "NotificationOptionPluginInstalled": "Plugin installed", + "NotificationOptionNewLibraryContent": "Kandungan baru telah ditambah", + "NotificationOptionPluginError": "Kegagalan plugin", + "NotificationOptionPluginInstalled": "Plugin telah dipasang", "NotificationOptionPluginUninstalled": "Plugin uninstalled", "NotificationOptionPluginUpdateInstalled": "Plugin update installed", "NotificationOptionServerRestartRequired": "Server restart required", @@ -71,8 +71,8 @@ "ScheduledTaskStartedWithName": "{0} bermula", "ServerNameNeedsToBeRestarted": "{0} needs to be restarted", "Shows": "Series", - "Songs": "Songs", - "StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.", + "Songs": "Lagu-lagu", + "StartupEmbyServerIsLoading": "Jellyfin Server sedang dimuatkan. Sila cuba sebentar lagi.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}", "Sync": "Sync", @@ -84,8 +84,8 @@ "UserDownloadingItemWithValues": "{0} is downloading {1}", "UserLockedOutWithName": "Pengguna {0} telah dikunci", "UserOfflineFromDevice": "{0} telah terputus dari {1}", - "UserOnlineFromDevice": "{0} dalam talian dari {1}", - "UserPasswordChangedWithName": "Kata laluan telah diubah untuk pengguna {0}", + "UserOnlineFromDevice": "{0} berada dalam talian dari {1}", + "UserPasswordChangedWithName": "Kata laluan telah ditukar bagi pengguna {0}", "UserPolicyUpdatedWithName": "Dasar pengguna telah dikemas kini untuk {0}", "UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}", "UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}", From a84e8c3884291acb721aeb202139372462e6c800 Mon Sep 17 00:00:00 2001 From: Haziq Rohaizan Date: Mon, 10 May 2021 21:12:16 +0000 Subject: [PATCH 1642/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- Emby.Server.Implementations/Localization/Core/ms.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index 104e116ab5..0b04586913 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -61,7 +61,7 @@ "NotificationOptionVideoPlayback": "Video playback started", "NotificationOptionVideoPlaybackStopped": "Video playback stopped", "Photos": "Gambar-gambar", - "Playlists": "Senarai ulangmain", + "Playlists": "Senarai main", "Plugin": "Plugin", "PluginInstalledWithName": "{0} was installed", "PluginUninstalledWithName": "{0} was uninstalled", @@ -99,5 +99,7 @@ "TasksMaintenanceCategory": "Penyelenggaraan", "Undefined": "Tidak ditentukan", "Forced": "Paksa", - "Default": "Asal" + "Default": "Asal", + "TaskCleanCache": "Bersihkan Direktori Cache", + "TaskCleanActivityLogDescription": "Padamkan entri log aktiviti yang lebih tua daripada usia yang dikonfigurasi." } From e3f55a0c54a2517361c237543aba717fd2a16e69 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Tue, 11 May 2021 05:55:46 -0600 Subject: [PATCH 1643/1930] Reduce warnings in MediaBrowser.Controller (#6006) Co-authored-by: Patrick Barron <18354464+barronpm@users.noreply.github.com> --- .../Collections/CollectionManager.cs | 14 ++---- .../Images/BaseDynamicImageProvider.cs | 2 +- Jellyfin.Api/Controllers/MoviesController.cs | 11 ++--- Jellyfin.Api/Controllers/PersonsController.cs | 6 +-- Jellyfin.Drawing.Skia/StripCollageBuilder.cs | 14 +++--- .../Channels/ChannelItemInfo.cs | 26 +++++----- .../Channels/ChannelItemResult.cs | 8 ++-- .../Channels/ChannelLatestMediaSearch.cs | 11 +++++ .../Channels/ChannelSearchInfo.cs | 5 -- .../Collections/CollectionCreatedEventArgs.cs | 24 ++++++++++ .../Collections/CollectionCreationOptions.cs | 4 +- ...ents.cs => CollectionModifiedEventArgs.cs} | 23 +++------ .../Drawing/ImageCollageOptions.cs | 4 +- .../Drawing/ImageStream.cs | 10 +++- MediaBrowser.Controller/Dto/DtoOptions.cs | 47 +++++++++---------- .../Entities/AggregateFolder.cs | 1 + .../Entities/Audio/MusicArtist.cs | 2 +- MediaBrowser.Controller/Entities/BaseItem.cs | 8 ++-- MediaBrowser.Controller/Entities/Book.cs | 10 ++-- MediaBrowser.Controller/Entities/Genre.cs | 2 +- .../Entities/InternalPeopleQuery.cs | 22 +++++---- .../Entities/LinkedChild.cs | 45 +++--------------- .../Entities/LinkedChildComparer.cs | 34 ++++++++++++++ .../Entities/LinkedChildType.cs | 18 +++++++ .../Entities/MusicVideo.cs | 8 ++-- .../Library/DeleteOptions.cs | 8 ++-- .../Library/IIntroProvider.cs | 12 ++--- MediaBrowser.Controller/Library/Profiler.cs | 4 +- .../LiveTv/ActiveRecordingInfo.cs | 19 ++++++++ MediaBrowser.Controller/LiveTv/ChannelInfo.cs | 6 +-- .../LiveTv/ILiveTvManager.cs | 16 ++----- .../LiveTv/LiveTvProgram.cs | 12 ++--- MediaBrowser.Controller/LiveTv/ProgramInfo.cs | 33 +++++++------ .../LiveTv/RecordingInfo.cs | 26 +++++----- .../LiveTv/SeriesTimerInfo.cs | 29 +++++++----- .../MediaBrowser.Controller.csproj | 2 +- .../Net/IWebSocketConnection.cs | 2 +- .../Providers/AlbumInfo.cs | 14 +++--- .../Providers/ArtistInfo.cs | 4 +- .../Providers/EpisodeInfo.cs | 10 ++-- .../Providers/IMetadataService.cs | 12 ++--- .../Providers/IProviderManager.cs | 7 --- .../Providers/ItemLookupInfo.cs | 12 ++--- .../Providers/MetadataRefreshOptions.cs | 31 ++++++------ .../Providers/RefreshPriority.cs | 23 +++++++++ .../Providers/RemoteSearchQuery.cs | 2 +- .../Providers/SeasonInfo.cs | 4 +- .../Resolvers/IResolverIgnoreRule.cs | 2 +- .../Session/ISessionManager.cs | 4 +- .../Session/SessionInfo.cs | 4 +- 50 files changed, 367 insertions(+), 290 deletions(-) create mode 100644 MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs create mode 100644 MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs rename MediaBrowser.Controller/Collections/{CollectionEvents.cs => CollectionModifiedEventArgs.cs} (55%) create mode 100644 MediaBrowser.Controller/Entities/LinkedChildComparer.cs create mode 100644 MediaBrowser.Controller/Entities/LinkedChildType.cs create mode 100644 MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs create mode 100644 MediaBrowser.Controller/Providers/RefreshPriority.cs diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index 1b85a9d4ba..c56f334481 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -164,7 +164,7 @@ namespace Emby.Server.Implementations.Collections parentFolder.AddChild(collection, CancellationToken.None); - if (options.ItemIdList.Length > 0) + if (options.ItemIdList.Count > 0) { await AddToCollectionAsync( collection.Id, @@ -248,11 +248,7 @@ namespace Emby.Server.Implementations.Collections if (fireEvent) { - ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs - { - Collection = collection, - ItemsChanged = itemList - }); + ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList)); } } } @@ -304,11 +300,7 @@ namespace Emby.Server.Implementations.Collections }, RefreshPriority.High); - ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs - { - Collection = collection, - ItemsChanged = itemList - }); + ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList)); } /// diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs index 5f7e51858a..6fa3c1c618 100644 --- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs @@ -191,7 +191,7 @@ namespace Emby.Server.Implementations.Images InputPaths = GetStripCollageImagePaths(primaryItem, items).ToArray() }; - if (options.InputPaths.Length == 0) + if (options.InputPaths.Count == 0) { return null; } diff --git a/Jellyfin.Api/Controllers/MoviesController.cs b/Jellyfin.Api/Controllers/MoviesController.cs index d0a2358ae2..010a3b19a7 100644 --- a/Jellyfin.Api/Controllers/MoviesController.cs +++ b/Jellyfin.Api/Controllers/MoviesController.cs @@ -18,6 +18,7 @@ using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Api.Controllers @@ -300,9 +301,8 @@ namespace Jellyfin.Api.Controllers private IEnumerable GetActors(IEnumerable items) { - var people = _libraryManager.GetPeople(new InternalPeopleQuery + var people = _libraryManager.GetPeople(new InternalPeopleQuery(Array.Empty(), new[] { PersonType.Director }) { - ExcludePersonTypes = new[] { PersonType.Director }, MaxListOrder = 3 }); @@ -316,10 +316,9 @@ namespace Jellyfin.Api.Controllers private IEnumerable GetDirectors(IEnumerable items) { - var people = _libraryManager.GetPeople(new InternalPeopleQuery - { - PersonTypes = new[] { PersonType.Director } - }); + var people = _libraryManager.GetPeople(new InternalPeopleQuery( + new[] { PersonType.Director }, + Array.Empty())); var itemIds = items.Select(i => i.Id).ToList(); diff --git a/Jellyfin.Api/Controllers/PersonsController.cs b/Jellyfin.Api/Controllers/PersonsController.cs index 70a94e27cb..b98307f879 100644 --- a/Jellyfin.Api/Controllers/PersonsController.cs +++ b/Jellyfin.Api/Controllers/PersonsController.cs @@ -94,10 +94,10 @@ namespace Jellyfin.Api.Controllers } var isFavoriteInFilters = filters.Any(f => f == ItemFilter.IsFavorite); - var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery + var peopleItems = _libraryManager.GetPeopleItems(new InternalPeopleQuery( + personTypes, + excludePersonTypes) { - PersonTypes = personTypes, - ExcludePersonTypes = excludePersonTypes, NameContains = searchTerm, User = user, IsFavorite = !isFavorite.HasValue && isFavoriteInFilters ? true : isFavorite, diff --git a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs index e9f9aad57d..09a3702385 100644 --- a/Jellyfin.Drawing.Skia/StripCollageBuilder.cs +++ b/Jellyfin.Drawing.Skia/StripCollageBuilder.cs @@ -68,7 +68,7 @@ namespace Jellyfin.Drawing.Skia /// The path at which to place the resulting collage image. /// The desired width of the collage. /// The desired height of the collage. - public void BuildSquareCollage(string[] paths, string outputPath, int width, int height) + public void BuildSquareCollage(IReadOnlyList paths, string outputPath, int width, int height) { using var bitmap = BuildSquareCollageBitmap(paths, width, height); using var outputStream = new SKFileWStream(outputPath); @@ -84,7 +84,7 @@ namespace Jellyfin.Drawing.Skia /// The desired width of the collage. /// The desired height of the collage. /// The name of the library to draw on the collage. - public void BuildThumbCollage(string[] paths, string outputPath, int width, int height, string? libraryName) + public void BuildThumbCollage(IReadOnlyList paths, string outputPath, int width, int height, string? libraryName) { using var bitmap = BuildThumbCollageBitmap(paths, width, height, libraryName); using var outputStream = new SKFileWStream(outputPath); @@ -92,7 +92,7 @@ namespace Jellyfin.Drawing.Skia pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90); } - private SKBitmap BuildThumbCollageBitmap(string[] paths, int width, int height, string? libraryName) + private SKBitmap BuildThumbCollageBitmap(IReadOnlyList paths, int width, int height, string? libraryName) { var bitmap = new SKBitmap(width, height); @@ -152,14 +152,14 @@ namespace Jellyfin.Drawing.Skia return bitmap; } - private SKBitmap? GetNextValidImage(string[] paths, int currentIndex, out int newIndex) + private SKBitmap? GetNextValidImage(IReadOnlyList paths, int currentIndex, out int newIndex) { var imagesTested = new Dictionary(); SKBitmap? bitmap = null; - while (imagesTested.Count < paths.Length) + while (imagesTested.Count < paths.Count) { - if (currentIndex >= paths.Length) + if (currentIndex >= paths.Count) { currentIndex = 0; } @@ -180,7 +180,7 @@ namespace Jellyfin.Drawing.Skia return bitmap; } - private SKBitmap BuildSquareCollageBitmap(string[] paths, int width, int height) + private SKBitmap BuildSquareCollageBitmap(IReadOnlyList paths, int width, int height) { var bitmap = new SKBitmap(width, height); var imageIndex = 0; diff --git a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs index fa7aff647b..4d1e35f9ea 100644 --- a/MediaBrowser.Controller/Channels/ChannelItemInfo.cs +++ b/MediaBrowser.Controller/Channels/ChannelItemInfo.cs @@ -13,6 +13,19 @@ namespace MediaBrowser.Controller.Channels { public class ChannelItemInfo : IHasProviderIds { + public ChannelItemInfo() + { + MediaSources = new List(); + TrailerTypes = new List(); + Genres = new List(); + Studios = new List(); + People = new List(); + Tags = new List(); + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + Artists = new List(); + AlbumArtists = new List(); + } + public string Name { get; set; } public string SeriesName { get; set; } @@ -80,18 +93,5 @@ namespace MediaBrowser.Controller.Channels public bool IsLiveStream { get; set; } public string Etag { get; set; } - - public ChannelItemInfo() - { - MediaSources = new List(); - TrailerTypes = new List(); - Genres = new List(); - Studios = new List(); - People = new List(); - Tags = new List(); - ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - Artists = new List(); - AlbumArtists = new List(); - } } } diff --git a/MediaBrowser.Controller/Channels/ChannelItemResult.cs b/MediaBrowser.Controller/Channels/ChannelItemResult.cs index 8e937852f1..6b20776629 100644 --- a/MediaBrowser.Controller/Channels/ChannelItemResult.cs +++ b/MediaBrowser.Controller/Channels/ChannelItemResult.cs @@ -8,13 +8,13 @@ namespace MediaBrowser.Controller.Channels { public class ChannelItemResult { - public List Items { get; set; } - - public int? TotalRecordCount { get; set; } - public ChannelItemResult() { Items = new List(); } + + public List Items { get; set; } + + public int? TotalRecordCount { get; set; } } } diff --git a/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs b/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs new file mode 100644 index 0000000000..6f0761e64b --- /dev/null +++ b/MediaBrowser.Controller/Channels/ChannelLatestMediaSearch.cs @@ -0,0 +1,11 @@ +#nullable disable + +#pragma warning disable CS1591 + +namespace MediaBrowser.Controller.Channels +{ + public class ChannelLatestMediaSearch + { + public string UserId { get; set; } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs index 53a73d62a9..990b025bcb 100644 --- a/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs +++ b/MediaBrowser.Controller/Channels/ChannelSearchInfo.cs @@ -10,9 +10,4 @@ namespace MediaBrowser.Controller.Channels public string UserId { get; set; } } - - public class ChannelLatestMediaSearch - { - public string UserId { get; set; } - } } diff --git a/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs b/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs new file mode 100644 index 0000000000..82b3a49773 --- /dev/null +++ b/MediaBrowser.Controller/Collections/CollectionCreatedEventArgs.cs @@ -0,0 +1,24 @@ +#nullable disable + +#pragma warning disable CS1591 + +using System; +using MediaBrowser.Controller.Entities.Movies; + +namespace MediaBrowser.Controller.Collections +{ + public class CollectionCreatedEventArgs : EventArgs + { + /// + /// Gets or sets the collection. + /// + /// The collection. + public BoxSet Collection { get; set; } + + /// + /// Gets or sets the options. + /// + /// The options. + public CollectionCreationOptions Options { get; set; } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs index 94e7541f87..30f5f4efa2 100644 --- a/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs +++ b/MediaBrowser.Controller/Collections/CollectionCreationOptions.cs @@ -25,8 +25,8 @@ namespace MediaBrowser.Controller.Collections public Dictionary ProviderIds { get; set; } - public string[] ItemIdList { get; set; } + public IReadOnlyList ItemIdList { get; set; } - public Guid[] UserIds { get; set; } + public IReadOnlyList UserIds { get; set; } } } diff --git a/MediaBrowser.Controller/Collections/CollectionEvents.cs b/MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs similarity index 55% rename from MediaBrowser.Controller/Collections/CollectionEvents.cs rename to MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs index 821318ffcb..8155cf3dbd 100644 --- a/MediaBrowser.Controller/Collections/CollectionEvents.cs +++ b/MediaBrowser.Controller/Collections/CollectionModifiedEventArgs.cs @@ -9,23 +9,14 @@ using MediaBrowser.Controller.Entities.Movies; namespace MediaBrowser.Controller.Collections { - public class CollectionCreatedEventArgs : EventArgs - { - /// - /// Gets or sets the collection. - /// - /// The collection. - public BoxSet Collection { get; set; } - - /// - /// Gets or sets the options. - /// - /// The options. - public CollectionCreationOptions Options { get; set; } - } - public class CollectionModifiedEventArgs : EventArgs { + public CollectionModifiedEventArgs(BoxSet collection, IReadOnlyCollection itemsChanged) + { + Collection = collection; + ItemsChanged = itemsChanged; + } + /// /// Gets or sets the collection. /// @@ -36,6 +27,6 @@ namespace MediaBrowser.Controller.Collections /// Gets or sets the items changed. /// /// The items changed. - public List ItemsChanged { get; set; } + public IReadOnlyCollection ItemsChanged { get; set; } } } diff --git a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs index f06bbe4d0d..e9c88ffb56 100644 --- a/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs +++ b/MediaBrowser.Controller/Drawing/ImageCollageOptions.cs @@ -1,5 +1,7 @@ #nullable disable +using System.Collections.Generic; + #pragma warning disable CS1591 namespace MediaBrowser.Controller.Drawing @@ -10,7 +12,7 @@ namespace MediaBrowser.Controller.Drawing /// Gets or sets the input paths. /// /// The input paths. - public string[] InputPaths { get; set; } + public IReadOnlyList InputPaths { get; set; } /// /// Gets or sets the output path. diff --git a/MediaBrowser.Controller/Drawing/ImageStream.cs b/MediaBrowser.Controller/Drawing/ImageStream.cs index 591cc53d10..5ee781ffa9 100644 --- a/MediaBrowser.Controller/Drawing/ImageStream.cs +++ b/MediaBrowser.Controller/Drawing/ImageStream.cs @@ -22,9 +22,15 @@ namespace MediaBrowser.Controller.Drawing public void Dispose() { - if (Stream != null) + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) { - Stream.Dispose(); + Stream?.Dispose(); } } } diff --git a/MediaBrowser.Controller/Dto/DtoOptions.cs b/MediaBrowser.Controller/Dto/DtoOptions.cs index 758e841a7f..ecc833154d 100644 --- a/MediaBrowser.Controller/Dto/DtoOptions.cs +++ b/MediaBrowser.Controller/Dto/DtoOptions.cs @@ -18,6 +18,28 @@ namespace MediaBrowser.Controller.Dto ItemFields.RefreshState }; + private static readonly ImageType[] AllImageTypes = Enum.GetValues(); + + private static readonly ItemFields[] AllItemFields = Enum.GetValues() + .Except(DefaultExcludedFields) + .ToArray(); + + public DtoOptions() + : this(true) + { + } + + public DtoOptions(bool allFields) + { + ImageTypeLimit = int.MaxValue; + EnableImages = true; + EnableUserData = true; + AddCurrentProgram = true; + + Fields = allFields ? AllItemFields : Array.Empty(); + ImageTypes = AllImageTypes; + } + public IReadOnlyList Fields { get; set; } public IReadOnlyList ImageTypes { get; set; } @@ -32,34 +54,9 @@ namespace MediaBrowser.Controller.Dto public bool AddCurrentProgram { get; set; } - public DtoOptions() - : this(true) - { - } - - private static readonly ImageType[] AllImageTypes = Enum.GetNames(typeof(ImageType)) - .Select(i => (ImageType)Enum.Parse(typeof(ImageType), i, true)) - .ToArray(); - - private static readonly ItemFields[] AllItemFields = Enum.GetNames(typeof(ItemFields)) - .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)) - .Except(DefaultExcludedFields) - .ToArray(); - public bool ContainsField(ItemFields field) => Fields.Contains(field); - public DtoOptions(bool allFields) - { - ImageTypeLimit = int.MaxValue; - EnableImages = true; - EnableUserData = true; - AddCurrentProgram = true; - - Fields = allFields ? AllItemFields : Array.Empty(); - ImageTypes = AllImageTypes; - } - public int GetImageLimit(ImageType type) { if (EnableImages && ImageTypes.Contains(type)) diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index f1944a7d3d..e365bfda1f 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -86,6 +86,7 @@ namespace MediaBrowser.Controller.Entities } private bool _requiresRefresh; + public override bool RequiresRefresh() { var changed = base.RequiresRefresh() || _requiresRefresh; diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 6101d30169..b07c3eed13 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -114,7 +114,7 @@ namespace MediaBrowser.Controller.Entities.Audio } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index ca52132735..238c98982c 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -339,9 +339,9 @@ namespace MediaBrowser.Controller.Entities get { // if (IsOffline) - //{ + // { // return LocationType.Offline; - //} + // } var path = Path; if (string.IsNullOrEmpty(path)) @@ -2769,11 +2769,11 @@ namespace MediaBrowser.Controller.Entities // var parentId = Id; // if (!video.IsOwnedItem || video.ParentId != parentId) - //{ + // { // video.IsOwnedItem = true; // video.ParentId = parentId; // newOptions.ForceSave = true; - //} + // } if (video == null) { diff --git a/MediaBrowser.Controller/Entities/Book.cs b/MediaBrowser.Controller/Entities/Book.cs index 3d0370248e..d75beb06da 100644 --- a/MediaBrowser.Controller/Entities/Book.cs +++ b/MediaBrowser.Controller/Entities/Book.cs @@ -12,6 +12,11 @@ namespace MediaBrowser.Controller.Entities { public class Book : BaseItem, IHasLookupInfo, IHasSeries { + public Book() + { + this.RunTimeTicks = TimeSpan.TicksPerSecond; + } + [JsonIgnore] public override string MediaType => Model.Entities.MediaType.Book; @@ -28,11 +33,6 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public Guid SeriesId { get; set; } - public Book() - { - this.RunTimeTicks = TimeSpan.TicksPerSecond; - } - public string FindSeriesSortName() { return SeriesName; diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 7987f38a07..310c0c9ec7 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -35,7 +35,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. diff --git a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs index b2d6a46091..3e1d892748 100644 --- a/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalPeopleQuery.cs @@ -3,12 +3,24 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using Jellyfin.Data.Entities; namespace MediaBrowser.Controller.Entities { public class InternalPeopleQuery { + public InternalPeopleQuery() + : this(Array.Empty(), Array.Empty()) + { + } + + public InternalPeopleQuery(IReadOnlyList personTypes, IReadOnlyList excludePersonTypes) + { + PersonTypes = personTypes; + ExcludePersonTypes = excludePersonTypes; + } + /// /// Gets or sets the maximum number of items the query should return. /// @@ -16,9 +28,9 @@ namespace MediaBrowser.Controller.Entities public Guid ItemId { get; set; } - public string[] PersonTypes { get; set; } + public IReadOnlyList PersonTypes { get; } - public string[] ExcludePersonTypes { get; set; } + public IReadOnlyList ExcludePersonTypes { get; } public int? MaxListOrder { get; set; } @@ -29,11 +41,5 @@ namespace MediaBrowser.Controller.Entities public User User { get; set; } public bool? IsFavorite { get; set; } - - public InternalPeopleQuery() - { - PersonTypes = Array.Empty(); - ExcludePersonTypes = Array.Empty(); - } } } diff --git a/MediaBrowser.Controller/Entities/LinkedChild.cs b/MediaBrowser.Controller/Entities/LinkedChild.cs index 01c0a93393..fd5fef3dc5 100644 --- a/MediaBrowser.Controller/Entities/LinkedChild.cs +++ b/MediaBrowser.Controller/Entities/LinkedChild.cs @@ -3,15 +3,18 @@ #pragma warning disable CS1591 using System; -using System.Collections.Generic; using System.Globalization; using System.Text.Json.Serialization; -using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.Entities { public class LinkedChild { + public LinkedChild() + { + Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); + } + public string Path { get; set; } public LinkedChildType Type { get; set; } @@ -22,7 +25,7 @@ namespace MediaBrowser.Controller.Entities public string Id { get; set; } /// - /// Serves as a cache. + /// Gets or sets the linked item id. /// public Guid? ItemId { get; set; } @@ -41,41 +44,5 @@ namespace MediaBrowser.Controller.Entities return child; } - - public LinkedChild() - { - Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); - } - } - - public enum LinkedChildType - { - Manual = 0, - Shortcut = 1 - } - - public class LinkedChildComparer : IEqualityComparer - { - private readonly IFileSystem _fileSystem; - - public LinkedChildComparer(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } - - public bool Equals(LinkedChild x, LinkedChild y) - { - if (x.Type == y.Type) - { - return _fileSystem.AreEqual(x.Path, y.Path); - } - - return false; - } - - public int GetHashCode(LinkedChild obj) - { - return ((obj.Path ?? string.Empty) + (obj.LibraryItemId ?? string.Empty) + obj.Type).GetHashCode(); - } } } diff --git a/MediaBrowser.Controller/Entities/LinkedChildComparer.cs b/MediaBrowser.Controller/Entities/LinkedChildComparer.cs new file mode 100644 index 0000000000..66fc44b8a9 --- /dev/null +++ b/MediaBrowser.Controller/Entities/LinkedChildComparer.cs @@ -0,0 +1,34 @@ +#nullable disable + +#pragma warning disable CS1591 + +using System.Collections.Generic; +using MediaBrowser.Model.IO; + +namespace MediaBrowser.Controller.Entities +{ + public class LinkedChildComparer : IEqualityComparer + { + private readonly IFileSystem _fileSystem; + + public LinkedChildComparer(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + + public bool Equals(LinkedChild x, LinkedChild y) + { + if (x.Type == y.Type) + { + return _fileSystem.AreEqual(x.Path, y.Path); + } + + return false; + } + + public int GetHashCode(LinkedChild obj) + { + return ((obj.Path ?? string.Empty) + (obj.LibraryItemId ?? string.Empty) + obj.Type).GetHashCode(); + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Entities/LinkedChildType.cs b/MediaBrowser.Controller/Entities/LinkedChildType.cs new file mode 100644 index 0000000000..9ddb7b6202 --- /dev/null +++ b/MediaBrowser.Controller/Entities/LinkedChildType.cs @@ -0,0 +1,18 @@ +namespace MediaBrowser.Controller.Entities +{ + /// + /// The linked child type. + /// + public enum LinkedChildType + { + /// + /// Manually linked child. + /// + Manual = 0, + + /// + /// Shortcut linked child. + /// + Shortcut = 1 + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index f42e7723c3..4e622ba01b 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -13,15 +13,15 @@ namespace MediaBrowser.Controller.Entities { public class MusicVideo : Video, IHasArtist, IHasMusicGenres, IHasLookupInfo { - /// - [JsonIgnore] - public IReadOnlyList Artists { get; set; } - public MusicVideo() { Artists = Array.Empty(); } + /// + [JsonIgnore] + public IReadOnlyList Artists { get; set; } + public override UnratedItem GetBlockUnratedType() { return UnratedItem.Music; diff --git a/MediaBrowser.Controller/Library/DeleteOptions.cs b/MediaBrowser.Controller/Library/DeleteOptions.cs index b7417efcb5..408e702845 100644 --- a/MediaBrowser.Controller/Library/DeleteOptions.cs +++ b/MediaBrowser.Controller/Library/DeleteOptions.cs @@ -4,13 +4,13 @@ namespace MediaBrowser.Controller.Library { public class DeleteOptions { - public bool DeleteFileLocation { get; set; } - - public bool DeleteFromExternalProvider { get; set; } - public DeleteOptions() { DeleteFromExternalProvider = true; } + + public bool DeleteFileLocation { get; set; } + + public bool DeleteFromExternalProvider { get; set; } } } diff --git a/MediaBrowser.Controller/Library/IIntroProvider.cs b/MediaBrowser.Controller/Library/IIntroProvider.cs index 3bb1bd9a09..a74d1b9f0b 100644 --- a/MediaBrowser.Controller/Library/IIntroProvider.cs +++ b/MediaBrowser.Controller/Library/IIntroProvider.cs @@ -11,6 +11,12 @@ namespace MediaBrowser.Controller.Library /// public interface IIntroProvider { + /// + /// Gets the name. + /// + /// The name. + string Name { get; } + /// /// Gets the intros. /// @@ -24,11 +30,5 @@ namespace MediaBrowser.Controller.Library /// /// IEnumerable{System.String}. IEnumerable GetAllIntroFiles(); - - /// - /// Gets the name. - /// - /// The name. - string Name { get; } } } diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs index 8f42d37061..583fd73c3a 100644 --- a/MediaBrowser.Controller/Library/Profiler.cs +++ b/MediaBrowser.Controller/Library/Profiler.cs @@ -15,12 +15,12 @@ namespace MediaBrowser.Controller.Library /// /// The name. /// - readonly string _name; + private readonly string _name; /// /// The stopwatch. /// - readonly Stopwatch _stopwatch; + private readonly Stopwatch _stopwatch; /// /// The _logger. diff --git a/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs b/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs new file mode 100644 index 0000000000..463061e686 --- /dev/null +++ b/MediaBrowser.Controller/LiveTv/ActiveRecordingInfo.cs @@ -0,0 +1,19 @@ +#nullable disable + +#pragma warning disable CS1591 + +using System.Threading; + +namespace MediaBrowser.Controller.LiveTv +{ + public class ActiveRecordingInfo + { + public string Id { get; set; } + + public string Path { get; set; } + + public TimerInfo Timer { get; set; } + + public CancellationTokenSource CancellationTokenSource { get; set; } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs index a55fd670d5..699c15f934 100644 --- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.LiveTv public string Number { get; set; } /// - /// Get or sets the Id. + /// Gets or sets the Id. /// /// The id of the channel. public string Id { get; set; } @@ -54,13 +54,13 @@ namespace MediaBrowser.Controller.LiveTv public string ChannelGroup { get; set; } /// - /// Supply the image path if it can be accessed directly from the file system. + /// Gets or sets the the image path if it can be accessed directly from the file system. /// /// The image path. public string ImagePath { get; set; } /// - /// Supply the image url if it can be downloaded. + /// Gets or sets the image url if it can be downloaded. /// /// The image URL. public string ImageUrl { get; set; } diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs index c28e0426b5..f4dc18e11c 100644 --- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs +++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs @@ -268,16 +268,21 @@ namespace MediaBrowser.Controller.LiveTv void AddChannelInfo(IReadOnlyCollection<(BaseItemDto, LiveTvChannel)> items, DtoOptions options, User user); Task> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken); + Task> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken); IListingsProvider[] ListingProviders { get; } List GetTunerHostTypes(); + Task> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken); event EventHandler> SeriesTimerCancelled; + event EventHandler> TimerCancelled; + event EventHandler> TimerCreated; + event EventHandler> SeriesTimerCreated; string GetEmbyTvActiveRecordingPath(string id); @@ -288,15 +293,4 @@ namespace MediaBrowser.Controller.LiveTv List GetRecordingFolders(User user); } - - public class ActiveRecordingInfo - { - public string Id { get; set; } - - public string Path { get; set; } - - public TimerInfo Timer { get; set; } - - public CancellationTokenSource CancellationTokenSource { get; set; } - } } diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index d9634a731f..a66bec11cb 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -101,7 +101,7 @@ namespace MediaBrowser.Controller.LiveTv public bool IsMovie { get; set; } /// - /// Gets or sets a value indicating whether this instance is sports. + /// Gets a value indicating whether this instance is sports. /// /// true if this instance is sports; otherwise, false. [JsonIgnore] @@ -115,35 +115,35 @@ namespace MediaBrowser.Controller.LiveTv public bool IsSeries { get; set; } /// - /// Gets or sets a value indicating whether this instance is live. + /// Gets a value indicating whether this instance is live. /// /// true if this instance is live; otherwise, false. [JsonIgnore] public bool IsLive => Tags.Contains("Live", StringComparer.OrdinalIgnoreCase); /// - /// Gets or sets a value indicating whether this instance is news. + /// Gets a value indicating whether this instance is news. /// /// true if this instance is news; otherwise, false. [JsonIgnore] public bool IsNews => Tags.Contains("News", StringComparer.OrdinalIgnoreCase); /// - /// Gets or sets a value indicating whether this instance is kids. + /// Gets a value indicating whether this instance is kids. /// /// true if this instance is kids; otherwise, false. [JsonIgnore] public bool IsKids => Tags.Contains("Kids", StringComparer.OrdinalIgnoreCase); /// - /// Gets or sets a value indicating whether this instance is premiere. + /// Gets a value indicating whether this instance is premiere. /// /// true if this instance is premiere; otherwise, false. [JsonIgnore] public bool IsPremiere => Tags.Contains("Premiere", StringComparer.OrdinalIgnoreCase); /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. diff --git a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs index 4a977c5cc3..3c3ac2471f 100644 --- a/MediaBrowser.Controller/LiveTv/ProgramInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ProgramInfo.cs @@ -10,8 +10,16 @@ namespace MediaBrowser.Controller.LiveTv { public class ProgramInfo { + public ProgramInfo() + { + Genres = new List(); + + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + SeriesProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + /// - /// Id of the program. + /// Gets or sets the id of the program. /// public string Id { get; set; } @@ -22,7 +30,7 @@ namespace MediaBrowser.Controller.LiveTv public string ChannelId { get; set; } /// - /// Name of the program. + /// Gets or sets the name of the program. /// public string Name { get; set; } @@ -45,17 +53,17 @@ namespace MediaBrowser.Controller.LiveTv public string ShortOverview { get; set; } /// - /// The start date of the program, in UTC. + /// Gets or sets the start date of the program, in UTC. /// public DateTime StartDate { get; set; } /// - /// The end date of the program, in UTC. + /// Gets or sets the end date of the program, in UTC. /// public DateTime EndDate { get; set; } /// - /// Genre of the program. + /// Gets or sets the genre of the program. /// public List Genres { get; set; } @@ -71,6 +79,9 @@ namespace MediaBrowser.Controller.LiveTv /// true if this instance is hd; otherwise, false. public bool? IsHD { get; set; } + /// + /// Gets or sets a value indicating whether this instance is 3d. + /// public bool? Is3D { get; set; } /// @@ -100,13 +111,13 @@ namespace MediaBrowser.Controller.LiveTv public string EpisodeTitle { get; set; } /// - /// Supply the image path if it can be accessed directly from the file system. + /// Gets or sets the image path if it can be accessed directly from the file system. /// /// The image path. public string ImagePath { get; set; } /// - /// Supply the image url if it can be downloaded. + /// Gets or sets the image url if it can be downloaded. /// /// The image URL. public string ImageUrl { get; set; } @@ -212,13 +223,5 @@ namespace MediaBrowser.Controller.LiveTv public Dictionary ProviderIds { get; set; } public Dictionary SeriesProviderIds { get; set; } - - public ProgramInfo() - { - Genres = new List(); - - ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - SeriesProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } } } diff --git a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs index 00135afa81..1dcf7a58fe 100644 --- a/MediaBrowser.Controller/LiveTv/RecordingInfo.cs +++ b/MediaBrowser.Controller/LiveTv/RecordingInfo.cs @@ -10,8 +10,13 @@ namespace MediaBrowser.Controller.LiveTv { public class RecordingInfo { + public RecordingInfo() + { + Genres = new List(); + } + /// - /// Id of the recording. + /// Gets or sets the id of the recording. /// public string Id { get; set; } @@ -28,7 +33,7 @@ namespace MediaBrowser.Controller.LiveTv public string TimerId { get; set; } /// - /// ChannelId of the recording. + /// Gets or sets the channelId of the recording. /// public string ChannelId { get; set; } @@ -39,7 +44,7 @@ namespace MediaBrowser.Controller.LiveTv public ChannelType ChannelType { get; set; } /// - /// Name of the recording. + /// Gets or sets the name of the recording. /// public string Name { get; set; } @@ -62,12 +67,12 @@ namespace MediaBrowser.Controller.LiveTv public string Overview { get; set; } /// - /// The start date of the recording, in UTC. + /// Gets or sets the start date of the recording, in UTC. /// public DateTime StartDate { get; set; } /// - /// The end date of the recording, in UTC. + /// Gets or sets the end date of the recording, in UTC. /// public DateTime EndDate { get; set; } @@ -84,7 +89,7 @@ namespace MediaBrowser.Controller.LiveTv public RecordingStatus Status { get; set; } /// - /// Genre of the program. + /// Gets or sets the genre of the program. /// public List Genres { get; set; } @@ -173,13 +178,13 @@ namespace MediaBrowser.Controller.LiveTv public float? CommunityRating { get; set; } /// - /// Supply the image path if it can be accessed directly from the file system. + /// Gets or sets the image path if it can be accessed directly from the file system. /// /// The image path. public string ImagePath { get; set; } /// - /// Supply the image url if it can be downloaded. + /// Gets or sets the image url if it can be downloaded. /// /// The image URL. public string ImageUrl { get; set; } @@ -201,10 +206,5 @@ namespace MediaBrowser.Controller.LiveTv /// /// The date last updated. public DateTime DateLastUpdated { get; set; } - - public RecordingInfo() - { - Genres = new List(); - } } } diff --git a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs index 1bb649a991..d6811fe14e 100644 --- a/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/SeriesTimerInfo.cs @@ -10,13 +10,20 @@ namespace MediaBrowser.Controller.LiveTv { public class SeriesTimerInfo { + public SeriesTimerInfo() + { + Days = new List(); + SkipEpisodesInLibrary = true; + KeepUntil = KeepUntil.UntilDeleted; + } + /// - /// Id of the recording. + /// Gets or sets the id of the recording. /// public string Id { get; set; } /// - /// ChannelId of the recording. + /// Gets or sets the channelId of the recording. /// public string ChannelId { get; set; } @@ -27,24 +34,27 @@ namespace MediaBrowser.Controller.LiveTv public string ProgramId { get; set; } /// - /// Name of the recording. + /// Gets or sets the name of the recording. /// public string Name { get; set; } + /// + /// Gets or sets the service name. + /// public string ServiceName { get; set; } /// - /// Description of the recording. + /// Gets or sets the description of the recording. /// public string Overview { get; set; } /// - /// The start date of the recording, in UTC. + /// Gets or sets the start date of the recording, in UTC. /// public DateTime StartDate { get; set; } /// - /// The end date of the recording, in UTC. + /// Gets or sets the end date of the recording, in UTC. /// public DateTime EndDate { get; set; } @@ -113,12 +123,5 @@ namespace MediaBrowser.Controller.LiveTv /// /// The series identifier. public string SeriesId { get; set; } - - public SeriesTimerInfo() - { - Days = new List(); - SkipEpisodesInLibrary = true; - KeepUntil = KeepUntil.UntilDeleted; - } } } diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 37ce35fc27..3f3a505eaf 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -16,7 +16,7 @@ - + diff --git a/MediaBrowser.Controller/Net/IWebSocketConnection.cs b/MediaBrowser.Controller/Net/IWebSocketConnection.cs index 5e9fce5503..e50cd97819 100644 --- a/MediaBrowser.Controller/Net/IWebSocketConnection.cs +++ b/MediaBrowser.Controller/Net/IWebSocketConnection.cs @@ -34,7 +34,7 @@ namespace MediaBrowser.Controller.Net DateTime LastKeepAliveDate { get; set; } /// - /// Gets or sets the query string. + /// Gets the query string. /// /// The query string. IQueryCollection QueryString { get; } diff --git a/MediaBrowser.Controller/Providers/AlbumInfo.cs b/MediaBrowser.Controller/Providers/AlbumInfo.cs index 276bcf1252..c7fad5974a 100644 --- a/MediaBrowser.Controller/Providers/AlbumInfo.cs +++ b/MediaBrowser.Controller/Providers/AlbumInfo.cs @@ -7,6 +7,13 @@ namespace MediaBrowser.Controller.Providers { public class AlbumInfo : ItemLookupInfo { + public AlbumInfo() + { + ArtistProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + SongInfos = new List(); + AlbumArtists = Array.Empty(); + } + /// /// Gets or sets the album artist. /// @@ -20,12 +27,5 @@ namespace MediaBrowser.Controller.Providers public Dictionary ArtistProviderIds { get; set; } public List SongInfos { get; set; } - - public AlbumInfo() - { - ArtistProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - SongInfos = new List(); - AlbumArtists = Array.Empty(); - } } } diff --git a/MediaBrowser.Controller/Providers/ArtistInfo.cs b/MediaBrowser.Controller/Providers/ArtistInfo.cs index adf885baa6..e9181f4765 100644 --- a/MediaBrowser.Controller/Providers/ArtistInfo.cs +++ b/MediaBrowser.Controller/Providers/ArtistInfo.cs @@ -6,11 +6,11 @@ namespace MediaBrowser.Controller.Providers { public class ArtistInfo : ItemLookupInfo { - public List SongInfos { get; set; } - public ArtistInfo() { SongInfos = new List(); } + + public List SongInfos { get; set; } } } diff --git a/MediaBrowser.Controller/Providers/EpisodeInfo.cs b/MediaBrowser.Controller/Providers/EpisodeInfo.cs index 341bf69361..0c932fa877 100644 --- a/MediaBrowser.Controller/Providers/EpisodeInfo.cs +++ b/MediaBrowser.Controller/Providers/EpisodeInfo.cs @@ -9,6 +9,11 @@ namespace MediaBrowser.Controller.Providers { public class EpisodeInfo : ItemLookupInfo { + public EpisodeInfo() + { + SeriesProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + public Dictionary SeriesProviderIds { get; set; } public int? IndexNumberEnd { get; set; } @@ -16,10 +21,5 @@ namespace MediaBrowser.Controller.Providers public bool IsMissingEpisode { get; set; } public string SeriesDisplayOrder { get; set; } - - public EpisodeInfo() - { - SeriesProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } } } diff --git a/MediaBrowser.Controller/Providers/IMetadataService.cs b/MediaBrowser.Controller/Providers/IMetadataService.cs index 5f3d4274ef..05fbb18ee4 100644 --- a/MediaBrowser.Controller/Providers/IMetadataService.cs +++ b/MediaBrowser.Controller/Providers/IMetadataService.cs @@ -10,6 +10,12 @@ namespace MediaBrowser.Controller.Providers { public interface IMetadataService { + /// + /// Gets the order. + /// + /// The order. + int Order { get; } + /// /// Determines whether this instance can refresh the specified item. /// @@ -27,11 +33,5 @@ namespace MediaBrowser.Controller.Providers /// The cancellation token. /// Task. Task RefreshMetadata(BaseItem item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken); - - /// - /// Gets the order. - /// - /// The order. - int Order { get; } } } diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index b4d91f396f..684bd9e681 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -191,11 +191,4 @@ namespace MediaBrowser.Controller.Providers double? GetRefreshProgress(Guid id); } - - public enum RefreshPriority - { - High = 0, - Normal = 1, - Low = 2 - } } diff --git a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs index f16669a781..e6f49c26ae 100644 --- a/MediaBrowser.Controller/Providers/ItemLookupInfo.cs +++ b/MediaBrowser.Controller/Providers/ItemLookupInfo.cs @@ -10,6 +10,12 @@ namespace MediaBrowser.Controller.Providers { public class ItemLookupInfo : IHasProviderIds { + public ItemLookupInfo() + { + IsAutomated = true; + ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + /// /// Gets or sets the name. /// @@ -53,11 +59,5 @@ namespace MediaBrowser.Controller.Providers public DateTime? PremiereDate { get; set; } public bool IsAutomated { get; set; } - - public ItemLookupInfo() - { - IsAutomated = true; - ProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); - } } } diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 5afc358ba7..1152504669 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -11,21 +11,6 @@ namespace MediaBrowser.Controller.Providers { public class MetadataRefreshOptions : ImageRefreshOptions { - /// - /// When paired with MetadataRefreshMode=FullRefresh, all existing data will be overwritten with new data from the providers. - /// - public bool ReplaceAllMetadata { get; set; } - - public MetadataRefreshMode MetadataRefreshMode { get; set; } - - public RemoteSearchResult SearchResult { get; set; } - - public string[] RefreshPaths { get; set; } - - public bool ForceSave { get; set; } - - public bool EnableRemoteContentProbe { get; set; } - public MetadataRefreshOptions(IDirectoryService directoryService) : base(directoryService) { @@ -53,6 +38,22 @@ namespace MediaBrowser.Controller.Providers } } + /// + /// Gets or sets a value indicating whether all existing data should be overwritten with new data from providers + /// when paired with MetadataRefreshMode=FullRefresh + /// + public bool ReplaceAllMetadata { get; set; } + + public MetadataRefreshMode MetadataRefreshMode { get; set; } + + public RemoteSearchResult SearchResult { get; set; } + + public string[] RefreshPaths { get; set; } + + public bool ForceSave { get; set; } + + public bool EnableRemoteContentProbe { get; set; } + public bool RefreshItem(BaseItem item) { if (RefreshPaths != null && RefreshPaths.Length > 0) diff --git a/MediaBrowser.Controller/Providers/RefreshPriority.cs b/MediaBrowser.Controller/Providers/RefreshPriority.cs new file mode 100644 index 0000000000..3619f679d6 --- /dev/null +++ b/MediaBrowser.Controller/Providers/RefreshPriority.cs @@ -0,0 +1,23 @@ +namespace MediaBrowser.Controller.Providers +{ + /// + /// Provider refresh priority. + /// + public enum RefreshPriority + { + /// + /// High priority. + /// + High = 0, + + /// + /// Normal priority. + /// + Normal = 1, + + /// + /// Low priority. + /// + Low = 2 + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs index d830231cfb..d4df5fa0db 100644 --- a/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs +++ b/MediaBrowser.Controller/Providers/RemoteSearchQuery.cs @@ -14,7 +14,7 @@ namespace MediaBrowser.Controller.Providers public Guid ItemId { get; set; } /// - /// Will only search within the given provider when set. + /// Gets or sets the provider name to search within if set. /// public string SearchProviderName { get; set; } diff --git a/MediaBrowser.Controller/Providers/SeasonInfo.cs b/MediaBrowser.Controller/Providers/SeasonInfo.cs index 2a4c1f03c7..7e39bc37a6 100644 --- a/MediaBrowser.Controller/Providers/SeasonInfo.cs +++ b/MediaBrowser.Controller/Providers/SeasonInfo.cs @@ -7,11 +7,11 @@ namespace MediaBrowser.Controller.Providers { public class SeasonInfo : ItemLookupInfo { - public Dictionary SeriesProviderIds { get; set; } - public SeasonInfo() { SeriesProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); } + + public Dictionary SeriesProviderIds { get; set; } } } diff --git a/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs b/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs index bb80e60256..a07b3e8988 100644 --- a/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs +++ b/MediaBrowser.Controller/Resolvers/IResolverIgnoreRule.cs @@ -4,7 +4,7 @@ using MediaBrowser.Model.IO; namespace MediaBrowser.Controller.Resolvers { /// - /// Provides a base "rule" that anyone can use to have paths ignored by the resolver + /// Provides a base "rule" that anyone can use to have paths ignored by the resolver. /// public interface IResolverIgnoreRule { diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 7eda49c602..4c3cf5ffe1 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -346,21 +346,19 @@ namespace MediaBrowser.Controller.Session /// Logouts the specified access token. /// /// The access token. - /// Task. void Logout(string accessToken); + void Logout(AuthenticationInfo accessToken); /// /// Revokes the user tokens. /// - /// Task. void RevokeUserTokens(Guid userId, string currentAccessToken); /// /// Revokes the token. /// /// The identifier. - /// Task. void RevokeToken(string id); void CloseIfNeeded(SessionInfo session); diff --git a/MediaBrowser.Controller/Session/SessionInfo.cs b/MediaBrowser.Controller/Session/SessionInfo.cs index 5da3783bf8..6134c0cf33 100644 --- a/MediaBrowser.Controller/Session/SessionInfo.cs +++ b/MediaBrowser.Controller/Session/SessionInfo.cs @@ -54,7 +54,7 @@ namespace MediaBrowser.Controller.Session public string RemoteEndPoint { get; set; } /// - /// Gets or sets the playable media types. + /// Gets the playable media types. /// /// The playable media types. public IReadOnlyList PlayableMediaTypes @@ -230,7 +230,7 @@ namespace MediaBrowser.Controller.Session public string UserPrimaryImageTag { get; set; } /// - /// Gets or sets the supported commands. + /// Gets the supported commands. /// /// The supported commands. public IReadOnlyList SupportedCommands From 85ecea77221ff6dfda73a7b75efb5d29f2e3cc96 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Tue, 11 May 2021 21:45:15 +0100 Subject: [PATCH 1644/1930] corrected tests --- .../Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs index a89d6e86f7..0d1e408c85 100644 --- a/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs @@ -19,7 +19,6 @@ namespace Jellyfin.Server.Integration.Tests [Theory] [InlineData("a=1&b=2&c=3", "a=1&b=2&c=3")] // won't be processed as there is more than 1. [InlineData("a=1", "a=1")] // won't be processed as it has a value - [InlineData("%3D", "==")] // will decode with an empty string value '=' = ''. [InlineData("a%3D1%26b%3D2%26c%3D3", "a=1&b=2&c=3")] // will be processed. public async Task Ensure_Decoding_Of_Urls_Is_Working(string sourceUrl, string unencodedUrl) { From c584d36fd4a643cfd252eddabbda8a91c2d8e0da Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Wed, 12 May 2021 14:48:45 +0200 Subject: [PATCH 1645/1930] Fix Tmdb person language --- .../Plugins/Tmdb/People/TmdbPersonImageProvider.cs | 5 ++--- .../Plugins/Tmdb/People/TmdbPersonProvider.cs | 5 ++--- MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs | 4 +++- MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs | 6 ++++++ 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index bf42ceadef..d523d0315d 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 -using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -48,6 +47,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) { + var language = item.GetPreferredMetadataLanguage(); var person = (Person)item; if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) @@ -55,14 +55,13 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People return Enumerable.Empty(); } - var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); + var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), language, cancellationToken).ConfigureAwait(false); if (personResult?.Images?.Profiles == null) { return Enumerable.Empty(); } var remoteImages = new RemoteImageInfo[personResult.Images.Profiles.Count]; - var language = item.GetPreferredMetadataLanguage(); for (var i = 0; i < personResult.Images.Profiles.Count; i++) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs index 1757c82678..6db550b1d0 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -32,7 +31,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People { if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { - var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); + var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false); if (personResult != null) { @@ -96,7 +95,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People if (personTmdbId > 0) { - var person = await _tmdbClientManager.GetPersonAsync(personTmdbId, cancellationToken).ConfigureAwait(false); + var person = await _tmdbClientManager.GetPersonAsync(personTmdbId, id.MetadataLanguage, cancellationToken).ConfigureAwait(false); result.HasMetadata = true; diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 05e5d3ced7..125b1b604a 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -276,9 +276,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id. /// /// The person's TMDb id. + /// The episode's language. /// The cancellation token. /// The TMDb person information or null if not found. - public async Task GetPersonAsync(int personTmdbId, CancellationToken cancellationToken) + public async Task GetPersonAsync(int personTmdbId, string language, CancellationToken cancellationToken) { var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}"; if (_memoryCache.TryGetValue(key, out Person person)) @@ -290,6 +291,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb person = await _tmDbClient.GetPersonAsync( personTmdbId, + TmdbUtils.NormalizeLanguage(language), PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds, cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index b4e165f82b..7c64035fe4 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -148,6 +148,12 @@ namespace MediaBrowser.Providers.Plugins.Tmdb if (parts.Length == 2) { + // TMDB doesn't support Switzerland (de-CH, it-CH or fr-CH) so use the language (de, it or fr) without country code + if (string.Equals(parts[1], "ch", StringComparison.Ordinal)) + { + return parts[0]; + } + language = parts[0] + "-" + parts[1].ToUpperInvariant(); } From d0bfb56d2ef0607b10d83706f7ec76fc16bb4cf9 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Wed, 12 May 2021 16:19:08 +0100 Subject: [PATCH 1646/1930] changed to slice. --- Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs index dd05f7bc5c..7d2c30b9db 100644 --- a/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs +++ b/Jellyfin.Server/Middleware/UrlDecodeQueryFeature.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Web; @@ -66,17 +67,16 @@ namespace Jellyfin.Server.Middleware foreach (var pair in queryString) { - var section = pair.ToString(); - var i = section.IndexOf('=', System.StringComparison.Ordinal); + var i = pair.IndexOf('='); if (i == -1) { // encoded is an equals. - pairs.Add(section, new StringValues(string.Empty)); + pairs.Add(pair[0..i].ToString(), new StringValues(string.Empty)); continue; } - pairs.Add(section[0..i], new StringValues(section[(i + 1)..])); + pairs.Add(pair[0..i].ToString(), new StringValues(pair[(i + 1)..].ToString())); } _store = new QueryCollection(pairs); From f53aa55bdbcdf83c527648a9fc3c89191039ecd1 Mon Sep 17 00:00:00 2001 From: crobibero Date: Wed, 12 May 2021 13:32:54 -0600 Subject: [PATCH 1647/1930] Don't logout if deviceId is null. --- .../Session/SessionManager.cs | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 6844152ea5..a1c8fae6f6 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1540,23 +1540,26 @@ namespace Emby.Server.Implementations.Session Limit = 1 }).Items.FirstOrDefault(); - var allExistingForDevice = _authRepo.Get( - new AuthenticationInfoQuery - { - DeviceId = deviceId - }).Items; - - foreach (var auth in allExistingForDevice) + if (!string.IsNullOrEmpty(deviceId)) { - if (existing == null || !string.Equals(auth.AccessToken, existing.AccessToken, StringComparison.Ordinal)) + var allExistingForDevice = _authRepo.Get( + new AuthenticationInfoQuery + { + DeviceId = deviceId + }).Items; + + foreach (var auth in allExistingForDevice) { - try + if (existing == null || !string.Equals(auth.AccessToken, existing.AccessToken, StringComparison.Ordinal)) { - Logout(auth); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error while logging out."); + try + { + Logout(auth); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error while logging out."); + } } } } From 59c4170966f68a511c4c143eb1b8e27ac3f5cbc0 Mon Sep 17 00:00:00 2001 From: Benjamin Vraspillai Date: Wed, 12 May 2021 16:34:33 +0000 Subject: [PATCH 1648/1930] Translated using Weblate (Norwegian Nynorsk) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nn/ --- Emby.Server.Implementations/Localization/Core/nn.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json index 16511e6867..f5683f35b7 100644 --- a/Emby.Server.Implementations/Localization/Core/nn.json +++ b/Emby.Server.Implementations/Localization/Core/nn.json @@ -19,7 +19,7 @@ "HeaderFavoriteArtists": "Favorittartistar", "HeaderFavoriteAlbums": "Favorittalbum", "HeaderContinueWatching": "Fortsett å sjå", - "HeaderAlbumArtists": "Albumartistar", + "HeaderAlbumArtists": "Albumartist", "Genres": "Sjangrar", "Folders": "Mapper", "Favorites": "Favorittar", @@ -97,8 +97,8 @@ "System": "System", "SubtitleDownloadFailureFromForItem": "Feila å laste ned undertekstar frå {0} for {1}", "StartupEmbyServerIsLoading": "Jellyfin-tenaren laster. Prøv igjen seinare.", - "Songs": "Songar", - "Shows": "Program", + "Songs": "Sangar", + "Shows": "Seriar", "ServerNameNeedsToBeRestarted": "{0} må omstartast", "ScheduledTaskStartedWithName": "{0} starta", "ScheduledTaskFailedWithName": "{0} feila", @@ -107,7 +107,7 @@ "PluginUninstalledWithName": "{0} blei avinstallert", "PluginInstalledWithName": "{0} blei installert", "Plugin": "Programvaretillegg", - "Playlists": "Speleliste", + "Playlists": "Spelelister", "Photos": "Bilete", "NotificationOptionVideoPlaybackStopped": "Videoavspeling stoppa", "NotificationOptionVideoPlayback": "Videoavspeling starta", From abbdaa997ed9fb1261f868c10acb11c406f3fbb7 Mon Sep 17 00:00:00 2001 From: archon eleven Date: Mon, 10 May 2021 21:17:33 +0000 Subject: [PATCH 1649/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- Emby.Server.Implementations/Localization/Core/ms.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index 0b04586913..676e59ab4f 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -59,7 +59,7 @@ "NotificationOptionTaskFailed": "Scheduled task failure", "NotificationOptionUserLockedOut": "User locked out", "NotificationOptionVideoPlayback": "Video playback started", - "NotificationOptionVideoPlaybackStopped": "Video playback stopped", + "NotificationOptionVideoPlaybackStopped": "Ulangmain video dihentikan", "Photos": "Gambar-gambar", "Playlists": "Senarai main", "Plugin": "Plugin", @@ -74,7 +74,7 @@ "Songs": "Lagu-lagu", "StartupEmbyServerIsLoading": "Jellyfin Server sedang dimuatkan. Sila cuba sebentar lagi.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", - "SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}", + "SubtitleDownloadFailureFromForItem": "Muat turun sarikata gagal dari {0} untuk {1}", "Sync": "Sync", "System": "Sistem", "TvShows": "TV Shows", From 88a7875a2739bef91f1d7216c5ebd89b4c267911 Mon Sep 17 00:00:00 2001 From: Haziq Rohaizan Date: Mon, 10 May 2021 21:16:08 +0000 Subject: [PATCH 1650/1930] Translated using Weblate (Malay) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ms/ --- Emby.Server.Implementations/Localization/Core/ms.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ms.json b/Emby.Server.Implementations/Localization/Core/ms.json index 676e59ab4f..5b4c8ae107 100644 --- a/Emby.Server.Implementations/Localization/Core/ms.json +++ b/Emby.Server.Implementations/Localization/Core/ms.json @@ -72,7 +72,7 @@ "ServerNameNeedsToBeRestarted": "{0} needs to be restarted", "Shows": "Series", "Songs": "Lagu-lagu", - "StartupEmbyServerIsLoading": "Jellyfin Server sedang dimuatkan. Sila cuba sebentar lagi.", + "StartupEmbyServerIsLoading": "Pelayan Jellyfin sedang dimuatkan. Sila cuba sebentar lagi.", "SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}", "SubtitleDownloadFailureFromForItem": "Muat turun sarikata gagal dari {0} untuk {1}", "Sync": "Sync", From 6bcbc2b88ae84b1d7cfc50f0872580bed437a60f Mon Sep 17 00:00:00 2001 From: crobibero Date: Thu, 13 May 2021 07:32:02 -0600 Subject: [PATCH 1651/1930] Reduce warnings in MediaBrowser.Controller --- MediaBrowser.Controller/Channels/Channel.cs | 2 +- .../Channels/IChannelManager.cs | 26 ++- .../Channels/IDisableMediaSourceDisplay.cs | 8 + .../Channels/IHasFolderAttributes.cs | 9 + .../Channels/IRequiresMediaInfoCallback.cs | 8 +- .../Channels/ISearchableChannel.cs | 32 ---- .../Channels/ISupportsDelete.cs | 17 ++ .../Channels/ISupportsLatestMedia.cs | 21 +++ .../Channels/ISupportsMediaProbe.cs | 8 + .../Channels/InternalChannelFeatures.cs | 4 +- .../Devices/IDeviceManager.cs | 4 +- MediaBrowser.Controller/Dto/IDtoService.cs | 6 + .../Entities/AggregateFolder.cs | 8 +- .../Entities/Audio/MusicArtist.cs | 4 +- .../Entities/Audio/MusicGenre.cs | 6 +- MediaBrowser.Controller/Entities/BaseItem.cs | 39 ++-- .../Entities/CollectionFolder.cs | 66 ++++--- MediaBrowser.Controller/Entities/Folder.cs | 170 +++++++++--------- MediaBrowser.Controller/Entities/Genre.cs | 42 +++-- .../Entities/IHasSeries.cs | 2 +- .../Entities/IHasShares.cs | 11 ++ .../Entities/Movies/Movie.cs | 4 +- .../Entities/MusicVideo.cs | 4 +- MediaBrowser.Controller/Entities/Person.cs | 9 +- MediaBrowser.Controller/Entities/Share.cs | 5 - MediaBrowser.Controller/Entities/Studio.cs | 6 +- .../Entities/TV/Episode.cs | 13 +- MediaBrowser.Controller/Entities/TV/Season.cs | 6 +- MediaBrowser.Controller/Entities/TV/Series.cs | 5 +- MediaBrowser.Controller/Entities/Trailer.cs | 4 +- .../Entities/UserItemData.cs | 2 +- .../Entities/UserRootFolder.cs | 5 +- MediaBrowser.Controller/Entities/UserView.cs | 20 ++- MediaBrowser.Controller/Entities/Year.cs | 10 +- .../Extensions/StringExtensions.cs | 2 +- .../Library/ILibraryManager.cs | 6 + .../LiveTv/LiveTvChannel.cs | 2 +- .../LiveTv/LiveTvProgram.cs | 2 +- MediaBrowser.Controller/LiveTv/TimerInfo.cs | 15 +- .../MediaEncoding/EncodingHelper.cs | 1 + .../MediaEncoding/EncodingJobInfo.cs | 31 +--- .../MediaEncoding/IMediaEncoder.cs | 2 +- .../MediaEncoding/TranscodingJobType.cs | 23 +++ MediaBrowser.Controller/Playlists/Playlist.cs | 3 +- .../Plugins/IRunBeforeStartup.cs | 9 + .../Plugins/IServerEntryPoint.cs | 8 +- .../Providers/MetadataRefreshOptions.cs | 2 +- .../Sync/IHasDynamicAccess.cs | 22 --- .../Sync/IRemoteSyncProvider.cs | 9 - .../Sync/IServerSyncProvider.cs | 32 ---- MediaBrowser.Controller/Sync/ISyncProvider.cs | 31 ---- .../Sync/SyncedFileInfo.cs | 43 ----- .../TV/ITVSeriesManager.cs | 10 ++ 53 files changed, 412 insertions(+), 427 deletions(-) create mode 100644 MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs create mode 100644 MediaBrowser.Controller/Channels/IHasFolderAttributes.cs create mode 100644 MediaBrowser.Controller/Channels/ISupportsDelete.cs create mode 100644 MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs create mode 100644 MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs create mode 100644 MediaBrowser.Controller/Entities/IHasShares.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs create mode 100644 MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs delete mode 100644 MediaBrowser.Controller/Sync/IHasDynamicAccess.cs delete mode 100644 MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs delete mode 100644 MediaBrowser.Controller/Sync/IServerSyncProvider.cs delete mode 100644 MediaBrowser.Controller/Sync/ISyncProvider.cs delete mode 100644 MediaBrowser.Controller/Sync/SyncedFileInfo.cs diff --git a/MediaBrowser.Controller/Channels/Channel.cs b/MediaBrowser.Controller/Channels/Channel.cs index 26c64e0da6..26a936be0c 100644 --- a/MediaBrowser.Controller/Channels/Channel.cs +++ b/MediaBrowser.Controller/Channels/Channel.cs @@ -84,7 +84,7 @@ namespace MediaBrowser.Controller.Channels internal static bool IsChannelVisible(BaseItem channelItem, User user) { - var channel = ChannelManager.GetChannel(channelItem.ChannelId.ToString("")); + var channel = ChannelManager.GetChannel(channelItem.ChannelId.ToString(string.Empty)); return channel.IsVisible(user); } diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs index 4c5626338e..95d95465e0 100644 --- a/MediaBrowser.Controller/Channels/IChannelManager.cs +++ b/MediaBrowser.Controller/Channels/IChannelManager.cs @@ -51,32 +51,47 @@ namespace MediaBrowser.Controller.Channels /// Gets the channels internal. /// /// The query. + /// The of . QueryResult GetChannelsInternal(ChannelQuery query); /// /// Gets the channels. /// /// The query. + /// The of . QueryResult GetChannels(ChannelQuery query); /// - /// Gets the latest media. + /// Gets the latest channel items. /// + /// The item query. + /// The cancellation token. + /// A containing the of . Task> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken); /// - /// Gets the latest media. + /// Gets the latest channel items. /// + /// The item query. + /// The cancellation token. + /// A containing the of . Task> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken); /// /// Gets the channel items. /// + /// The query. + /// The cancellation token. + /// A containing the of . Task> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken); /// - /// Gets the channel items internal. + /// Gets the channel items. /// + /// The query. + /// The progress to report to. + /// The cancellation token. + /// A containing the of . Task> GetChannelItemsInternal(InternalItemsQuery query, IProgress progress, CancellationToken cancellationToken); /// @@ -87,6 +102,11 @@ namespace MediaBrowser.Controller.Channels /// Task{IEnumerable{MediaSourceInfo}}. IEnumerable GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken); + /// + /// Whether the item supports media probe. + /// + /// The item. + /// Whether media probe should be enabled. bool EnableMediaProbe(BaseItem item); } } diff --git a/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs b/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs new file mode 100644 index 0000000000..a2dc5682dd --- /dev/null +++ b/MediaBrowser.Controller/Channels/IDisableMediaSourceDisplay.cs @@ -0,0 +1,8 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Controller.Channels +{ + public interface IDisableMediaSourceDisplay + { + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs b/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs new file mode 100644 index 0000000000..47277a8cc8 --- /dev/null +++ b/MediaBrowser.Controller/Channels/IHasFolderAttributes.cs @@ -0,0 +1,9 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Controller.Channels +{ + public interface IHasFolderAttributes + { + string[] Attributes { get; } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs b/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs index 589295543c..eeaa6b622e 100644 --- a/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs +++ b/MediaBrowser.Controller/Channels/IRequiresMediaInfoCallback.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS1591 - using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -7,11 +5,17 @@ using MediaBrowser.Model.Dto; namespace MediaBrowser.Controller.Channels { + /// + /// The channel requires a media info callback. + /// public interface IRequiresMediaInfoCallback { /// /// Gets the channel item media information. /// + /// The channel item id. + /// The cancellation token. + /// The enumerable of media source info. Task> GetChannelItemMediaInfo(string id, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Controller/Channels/ISearchableChannel.cs b/MediaBrowser.Controller/Channels/ISearchableChannel.cs index b58446fc43..b87943a6ed 100644 --- a/MediaBrowser.Controller/Channels/ISearchableChannel.cs +++ b/MediaBrowser.Controller/Channels/ISearchableChannel.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Controller.Entities; namespace MediaBrowser.Controller.Channels { @@ -19,35 +18,4 @@ namespace MediaBrowser.Controller.Channels /// Task{IEnumerable{ChannelItemInfo}}. Task> Search(ChannelSearchInfo searchInfo, CancellationToken cancellationToken); } - - public interface ISupportsLatestMedia - { - /// - /// Gets the latest media. - /// - /// The request. - /// The cancellation token. - /// Task{IEnumerable{ChannelItemInfo}}. - Task> GetLatestMedia(ChannelLatestMediaSearch request, CancellationToken cancellationToken); - } - - public interface ISupportsDelete - { - bool CanDelete(BaseItem item); - - Task DeleteItem(string id, CancellationToken cancellationToken); - } - - public interface IDisableMediaSourceDisplay - { - } - - public interface ISupportsMediaProbe - { - } - - public interface IHasFolderAttributes - { - string[] Attributes { get; } - } } diff --git a/MediaBrowser.Controller/Channels/ISupportsDelete.cs b/MediaBrowser.Controller/Channels/ISupportsDelete.cs new file mode 100644 index 0000000000..d7234fa38f --- /dev/null +++ b/MediaBrowser.Controller/Channels/ISupportsDelete.cs @@ -0,0 +1,17 @@ +#nullable disable + +#pragma warning disable CS1591 + +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; + +namespace MediaBrowser.Controller.Channels +{ + public interface ISupportsDelete + { + bool CanDelete(BaseItem item); + + Task DeleteItem(string id, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs new file mode 100644 index 0000000000..6820d9222c --- /dev/null +++ b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs @@ -0,0 +1,21 @@ +#nullable disable + +#pragma warning disable CS1591 + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Channels +{ + public interface ISupportsLatestMedia + { + /// + /// Gets the latest media. + /// + /// The request. + /// The cancellation token. + /// Task{IEnumerable{ChannelItemInfo}}. + Task> GetLatestMedia(ChannelLatestMediaSearch request, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs b/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs new file mode 100644 index 0000000000..2682de51c4 --- /dev/null +++ b/MediaBrowser.Controller/Channels/ISupportsMediaProbe.cs @@ -0,0 +1,8 @@ +#pragma warning disable CS1591 + +namespace MediaBrowser.Controller.Channels +{ + public interface ISupportsMediaProbe + { + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs index 152c653dc4..45cd08173a 100644 --- a/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs +++ b/MediaBrowser.Controller/Channels/InternalChannelFeatures.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.Channels public List ContentTypes { get; set; } /// - /// Represents the maximum number of records the channel allows retrieving at a time. + /// Gets or sets the maximum number of records the channel allows retrieving at a time. /// public int? MaxPageSize { get; set; } @@ -41,7 +41,7 @@ namespace MediaBrowser.Controller.Channels public List DefaultSortFields { get; set; } /// - /// Indicates if a sort ascending/descending toggle is supported or not. + /// Gets or sets a value indicating whether a sort ascending/descending toggle is supported or not. /// public bool SupportsSortOrderToggle { get; set; } diff --git a/MediaBrowser.Controller/Devices/IDeviceManager.cs b/MediaBrowser.Controller/Devices/IDeviceManager.cs index ef17c8fb37..8096be1bd3 100644 --- a/MediaBrowser.Controller/Devices/IDeviceManager.cs +++ b/MediaBrowser.Controller/Devices/IDeviceManager.cs @@ -20,7 +20,6 @@ namespace MediaBrowser.Controller.Devices /// /// The reported identifier. /// The capabilities. - /// Task. void SaveCapabilities(string reportedId, ClientCapabilities capabilities); /// @@ -47,6 +46,9 @@ namespace MediaBrowser.Controller.Devices /// /// Determines whether this instance [can access device] the specified user identifier. /// + /// The user to test. + /// The device id to test. + /// Whether the user can access the device. bool CanAccessDevice(User user, string deviceId); void UpdateDeviceOptions(string deviceId, DeviceOptions options); diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs index 7f4bbead0f..e0950b1f61 100644 --- a/MediaBrowser.Controller/Dto/IDtoService.cs +++ b/MediaBrowser.Controller/Dto/IDtoService.cs @@ -36,11 +36,17 @@ namespace MediaBrowser.Controller.Dto /// The options. /// The user. /// The owner. + /// The of . IReadOnlyList GetBaseItemDtos(IReadOnlyList items, DtoOptions options, User user = null, BaseItem owner = null); /// /// Gets the item by name dto. /// + /// The item. + /// The dto options. + /// The list of tagged items. + /// The user. + /// The . BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List taggedItems, User user = null); } } diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs index e365bfda1f..533130fc8e 100644 --- a/MediaBrowser.Controller/Entities/AggregateFolder.cs +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -22,6 +22,8 @@ namespace MediaBrowser.Controller.Entities /// public class AggregateFolder : Folder { + private bool _requiresRefresh; + public AggregateFolder() { PhysicalLocationsList = Array.Empty(); @@ -85,8 +87,6 @@ namespace MediaBrowser.Controller.Entities } } - private bool _requiresRefresh; - public override bool RequiresRefresh() { var changed = base.RequiresRefresh() || _requiresRefresh; @@ -106,11 +106,11 @@ namespace MediaBrowser.Controller.Entities return changed; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { ClearCache(); - var changed = base.BeforeMetadataRefresh(replaceAllMetdata) || _requiresRefresh; + var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh; _requiresRefresh = false; return changed; } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index b07c3eed13..0928a8073b 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -208,9 +208,9 @@ namespace MediaBrowser.Controller.Entities.Audio /// /// This is called before any metadata refresh and returns true or false indicating if changes were made. /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (IsAccessedByName) { diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index b07d47ffdd..a682a2e58c 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -38,7 +38,7 @@ namespace MediaBrowser.Controller.Entities.Audio public override bool IsDisplayedAsFolder => true; /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. @@ -106,9 +106,9 @@ namespace MediaBrowser.Controller.Entities.Audio /// /// This is called before any metadata refresh and returns true or false indicating if changes were made. /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 238c98982c..6e46b4cec8 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -92,7 +92,8 @@ namespace MediaBrowser.Controller.Entities public const string ShortsFolderName = "shorts"; public const string FeaturettesFolderName = "featurettes"; - public static readonly string[] AllExtrasTypesFolderNames = { + public static readonly string[] AllExtrasTypesFolderNames = + { ExtrasFolderName, BehindTheScenesFolderName, DeletedScenesFolderName, @@ -177,7 +178,7 @@ namespace MediaBrowser.Controller.Entities public virtual bool AlwaysScanInternalMetadataPath => false; /// - /// Gets a value indicating whether this instance is in mixed folder. + /// Gets or sets a value indicating whether this instance is in mixed folder. /// /// true if this instance is in mixed folder; otherwise, false. [JsonIgnore] @@ -244,7 +245,7 @@ namespace MediaBrowser.Controller.Entities public ProgramAudio? Audio { get; set; } /// - /// Return the id that should be used to key display prefs for this item. + /// Gets the id that should be used to key display prefs for this item. /// Default is based on the type for everything except actual generic folders. /// /// The display prefs id. @@ -280,7 +281,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// [JsonIgnore] @@ -305,8 +306,11 @@ namespace MediaBrowser.Controller.Entities public string ServiceName { get; set; } /// - /// If this content came from an external service, the id of the content on that service. + /// Gets or sets the external id. /// + /// + /// If this content came from an external service, the id of the content on that service. + /// [JsonIgnore] public string ExternalId { get; set; } @@ -330,7 +334,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Gets or sets the type of the location. + /// Gets the type of the location. /// /// The type of the location. [JsonIgnore] @@ -449,8 +453,11 @@ namespace MediaBrowser.Controller.Entities } /// - /// This is just a helper for convenience. + /// Gets the primary image path. /// + /// + /// This is just a helper for convenience. + /// /// The primary image path. [JsonIgnore] public string PrimaryImagePath => this.GetImagePath(ImageType.Primary); @@ -541,7 +548,7 @@ namespace MediaBrowser.Controller.Entities public DateTime DateLastRefreshed { get; set; } /// - /// The logger. + /// Gets or sets the logger. /// public static ILogger Logger { get; set; } @@ -621,7 +628,7 @@ namespace MediaBrowser.Controller.Entities private Guid[] _themeVideoIds; /// - /// Gets the name of the sort. + /// Gets or sets the name of the sort. /// /// The name of the sort. [JsonIgnore] @@ -848,7 +855,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// When the item first debuted. For movies this could be premiere date, episodes would be first aired + /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be first aired. /// /// The premiere date. [JsonIgnore] @@ -945,7 +952,7 @@ namespace MediaBrowser.Controller.Entities public int? ProductionYear { get; set; } /// - /// If the item is part of a series, this is it's number in the series. + /// Gets or sets the index number. If the item is part of a series, this is it's number in the series. /// This could be episode number, album track number, etc. /// /// The index number. @@ -953,7 +960,7 @@ namespace MediaBrowser.Controller.Entities public int? IndexNumber { get; set; } /// - /// For an episode this could be the season number, or for a song this could be the disc number. + /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this could be the disc number. /// /// The parent index number. [JsonIgnore] @@ -1017,9 +1024,9 @@ namespace MediaBrowser.Controller.Entities } // if (!user.IsParentalScheduleAllowed()) - //{ + // { // return PlayAccess.None; - //} + // } return PlayAccess.Full; } @@ -2645,7 +2652,9 @@ namespace MediaBrowser.Controller.Entities /// /// This is called before any metadata refresh and returns true if changes were made. /// - public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata) + /// Whether to replace all metadata. + /// true if the item has change, else false. + public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata) { _sortName = null; diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index a86da29ce4..d0fb3997d5 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -29,30 +29,45 @@ namespace MediaBrowser.Controller.Entities public class CollectionFolder : Folder, ICollectionFolder { private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; - public static IXmlSerializer XmlSerializer { get; set; } - - public static IServerApplicationHost ApplicationHost { get; set; } + private static readonly Dictionary _libraryOptions = new Dictionary(); + private bool _requiresRefresh; + /// + /// Initializes a new instance of the class. + /// public CollectionFolder() { PhysicalLocationsList = Array.Empty(); PhysicalFolderIds = Array.Empty(); } + public static IXmlSerializer XmlSerializer { get; set; } + + public static IServerApplicationHost ApplicationHost { get; set; } + [JsonIgnore] public override bool SupportsPlayedStatus => false; [JsonIgnore] public override bool SupportsInheritedParentImages => false; + public string CollectionType { get; set; } + + /// + /// Gets the item's children. + /// + /// + /// Our children are actually just references to the ones in the physical root... + /// + /// The actual children. + [JsonIgnore] + public override IEnumerable Children => GetActualChildren(); + public override bool CanDelete() { return false; } - public string CollectionType { get; set; } - - private static readonly Dictionary LibraryOptions = new Dictionary(); public LibraryOptions GetLibraryOptions() { return GetLibraryOptions(Path); @@ -106,12 +121,12 @@ namespace MediaBrowser.Controller.Entities public static LibraryOptions GetLibraryOptions(string path) { - lock (LibraryOptions) + lock (_libraryOptions) { - if (!LibraryOptions.TryGetValue(path, out var options)) + if (!_libraryOptions.TryGetValue(path, out var options)) { options = LoadLibraryOptions(path); - LibraryOptions[path] = options; + _libraryOptions[path] = options; } return options; @@ -120,9 +135,9 @@ namespace MediaBrowser.Controller.Entities public static void SaveLibraryOptions(string path, LibraryOptions options) { - lock (LibraryOptions) + lock (_libraryOptions) { - LibraryOptions[path] = options; + _libraryOptions[path] = options; var clone = JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions); foreach (var mediaPath in clone.PathInfos) @@ -139,15 +154,18 @@ namespace MediaBrowser.Controller.Entities public static void OnCollectionFolderChange() { - lock (LibraryOptions) + lock (_libraryOptions) { - LibraryOptions.Clear(); + _libraryOptions.Clear(); } } /// - /// Allow different display preferences for each collection folder. + /// Gets the display preferences id. /// + /// + /// Allow different display preferences for each collection folder. + /// /// The display prefs id. [JsonIgnore] public override Guid DisplayPreferencesId => Id; @@ -155,21 +173,20 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public override string[] PhysicalLocations => PhysicalLocationsList; + public string[] PhysicalLocationsList { get; set; } + + public Guid[] PhysicalFolderIds { get; set; } + public override bool IsSaveLocalMetadataEnabled() { return true; } - public string[] PhysicalLocationsList { get; set; } - - public Guid[] PhysicalFolderIds { get; set; } - protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService) { return CreateResolveArgs(directoryService, true).FileSystemChildren; } - private bool _requiresRefresh; public override bool RequiresRefresh() { var changed = base.RequiresRefresh() || _requiresRefresh; @@ -201,9 +218,9 @@ namespace MediaBrowser.Controller.Entities return changed; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var changed = base.BeforeMetadataRefresh(replaceAllMetdata) || _requiresRefresh; + var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh; _requiresRefresh = false; return changed; } @@ -312,13 +329,6 @@ namespace MediaBrowser.Controller.Entities return Task.CompletedTask; } - /// - /// Our children are actually just references to the ones in the physical root... - /// - /// The actual children. - [JsonIgnore] - public override IEnumerable Children => GetActualChildren(); - public IEnumerable GetActualChildren() { return GetPhysicalFolders(true).SelectMany(c => c.Children); diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index a59f5c6e4b..29d837c143 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -37,6 +37,11 @@ namespace MediaBrowser.Controller.Entities /// public class Folder : BaseItem { + public Folder() + { + LinkedChildren = Array.Empty(); + } + public static IUserViewManager UserViewManager { get; set; } /// @@ -50,11 +55,6 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public DateTime? DateLastMediaAdded { get; set; } - public Folder() - { - LinkedChildren = Array.Empty(); - } - [JsonIgnore] public override bool SupportsThemeMedia => true; @@ -86,6 +86,85 @@ namespace MediaBrowser.Controller.Entities [JsonIgnore] public virtual bool SupportsDateLastMediaAdded => false; + [JsonIgnore] + public override string FileNameWithoutExtension + { + get + { + if (IsFileProtocol) + { + return System.IO.Path.GetFileName(Path); + } + + return null; + } + } + + /// + /// Gets the actual children. + /// + /// The actual children. + [JsonIgnore] + public virtual IEnumerable Children => LoadChildren(); + + /// + /// Gets thread-safe access to all recursive children of this folder - without regard to user. + /// + /// The recursive children. + [JsonIgnore] + public IEnumerable RecursiveChildren => GetRecursiveChildren(); + + [JsonIgnore] + protected virtual bool SupportsShortcutChildren => false; + + protected virtual bool FilterLinkedChildrenPerUser => false; + + [JsonIgnore] + protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren; + + [JsonIgnore] + public virtual bool SupportsUserDataFromChildren + { + get + { + // These are just far too slow. + if (this is ICollectionFolder) + { + return false; + } + + if (this is UserView) + { + return false; + } + + if (this is UserRootFolder) + { + return false; + } + + if (this is Channel) + { + return false; + } + + if (SourceType != SourceType.Library) + { + return false; + } + + if (this is IItemByName) + { + if (this is not IHasDualAccess hasDualAccess || hasDualAccess.IsAccessedByName) + { + return false; + } + } + + return true; + } + } + public override bool CanDelete() { if (IsRoot) @@ -108,20 +187,6 @@ namespace MediaBrowser.Controller.Entities return baseResult; } - [JsonIgnore] - public override string FileNameWithoutExtension - { - get - { - if (IsFileProtocol) - { - return System.IO.Path.GetFileName(Path); - } - - return null; - } - } - protected override bool IsAllowTagFilterEnforced() { if (this is ICollectionFolder) @@ -137,9 +202,6 @@ namespace MediaBrowser.Controller.Entities return true; } - [JsonIgnore] - protected virtual bool SupportsShortcutChildren => false; - /// /// Adds the child. /// @@ -169,20 +231,6 @@ namespace MediaBrowser.Controller.Entities LibraryManager.CreateItem(item, this); } - /// - /// Gets the actual children. - /// - /// The actual children. - [JsonIgnore] - public virtual IEnumerable Children => LoadChildren(); - - /// - /// thread-safe access to all recursive children of this folder - without regard to user. - /// - /// The recursive children. - [JsonIgnore] - public IEnumerable RecursiveChildren => GetRecursiveChildren(); - public override bool IsVisible(User user) { if (this is ICollectionFolder && !(this is BasePluginFolder)) @@ -1428,8 +1476,6 @@ namespace MediaBrowser.Controller.Entities return list; } - protected virtual bool FilterLinkedChildrenPerUser => false; - public bool ContainsLinkedChildByItemId(Guid itemId) { var linkedChildren = LinkedChildren; @@ -1530,9 +1576,6 @@ namespace MediaBrowser.Controller.Entities .Where(i => i.Item2 != null); } - [JsonIgnore] - protected override bool SupportsOwnedItems => base.SupportsOwnedItems || SupportsShortcutChildren; - protected override async Task RefreshedOwnedItems(MetadataRefreshOptions options, List fileSystemChildren, CancellationToken cancellationToken) { var changesFound = false; @@ -1696,51 +1739,6 @@ namespace MediaBrowser.Controller.Entities return !IsPlayed(user); } - [JsonIgnore] - public virtual bool SupportsUserDataFromChildren - { - get - { - // These are just far too slow. - if (this is ICollectionFolder) - { - return false; - } - - if (this is UserView) - { - return false; - } - - if (this is UserRootFolder) - { - return false; - } - - if (this is Channel) - { - return false; - } - - if (SourceType != SourceType.Library) - { - return false; - } - - var iItemByName = this as IItemByName; - if (iItemByName != null) - { - var hasDualAccess = this as IHasDualAccess; - if (hasDualAccess == null || hasDualAccess.IsAccessedByName) - { - return false; - } - } - - return true; - } - } - public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields) { if (!SupportsUserDataFromChildren) diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index 310c0c9ec7..698643b446 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -16,6 +16,23 @@ namespace MediaBrowser.Controller.Entities /// public class Genre : BaseItem, IItemByName { + /// + /// Gets the folder containing the item. + /// If the item is a folder, it returns the folder itself. + /// + /// The containing folder path. + [JsonIgnore] + public override string ContainingFolderPath => Path; + + [JsonIgnore] + public override bool IsDisplayedAsFolder => true; + + [JsonIgnore] + public override bool SupportsAncestors => false; + + [JsonIgnore] + public override bool SupportsPeople => false; + public override List GetUserDataKeys() { var list = base.GetUserDataKeys(); @@ -34,20 +51,6 @@ namespace MediaBrowser.Controller.Entities return 1; } - /// - /// Gets the folder containing the item. - /// If the item is a folder, it returns the folder itself. - /// - /// The containing folder path. - [JsonIgnore] - public override string ContainingFolderPath => Path; - - [JsonIgnore] - public override bool IsDisplayedAsFolder => true; - - [JsonIgnore] - public override bool SupportsAncestors => false; - public override bool IsSaveLocalMetadataEnabled() { return true; @@ -72,9 +75,6 @@ namespace MediaBrowser.Controller.Entities return LibraryManager.GetItemList(query); } - [JsonIgnore] - public override bool SupportsPeople => false; - public static string GetPath(string name) { return GetPath(name, true); @@ -107,12 +107,10 @@ namespace MediaBrowser.Controller.Entities return base.RequiresRefresh(); } - /// - /// This is called before any metadata refresh and returns true or false indicating if changes were made. - /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + /// + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) diff --git a/MediaBrowser.Controller/Entities/IHasSeries.cs b/MediaBrowser.Controller/Entities/IHasSeries.cs index 64d769d5ba..5f774bbdee 100644 --- a/MediaBrowser.Controller/Entities/IHasSeries.cs +++ b/MediaBrowser.Controller/Entities/IHasSeries.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Controller.Entities public interface IHasSeries { /// - /// Gets the name of the series. + /// Gets or sets the name of the series. /// /// The name of the series. string SeriesName { get; set; } diff --git a/MediaBrowser.Controller/Entities/IHasShares.cs b/MediaBrowser.Controller/Entities/IHasShares.cs new file mode 100644 index 0000000000..bdde744a37 --- /dev/null +++ b/MediaBrowser.Controller/Entities/IHasShares.cs @@ -0,0 +1,11 @@ +#nullable disable + +#pragma warning disable CS1591 + +namespace MediaBrowser.Controller.Entities +{ + public interface IHasShares + { + Share[] Shares { get; set; } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 64d60c2e90..b54bbf5eb9 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -144,9 +144,9 @@ namespace MediaBrowser.Controller.Entities.Movies } /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (!ProductionYear.HasValue) { diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index 4e622ba01b..237ad5198c 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -36,9 +36,9 @@ namespace MediaBrowser.Controller.Entities return info; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (!ProductionYear.HasValue) { diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index d9ff55362c..913f76d3bd 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -50,7 +50,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. @@ -67,6 +67,9 @@ namespace MediaBrowser.Controller.Entities return true; } + /// + /// Gets a value indicating whether to enable alpha numeric sorting. + /// [JsonIgnore] public override bool EnableAlphaNumericSorting => false; @@ -126,9 +129,9 @@ namespace MediaBrowser.Controller.Entities /// /// This is called before any metadata refresh and returns true or false indicating if changes were made. /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) diff --git a/MediaBrowser.Controller/Entities/Share.cs b/MediaBrowser.Controller/Entities/Share.cs index 7e4ec18307..64f446eef2 100644 --- a/MediaBrowser.Controller/Entities/Share.cs +++ b/MediaBrowser.Controller/Entities/Share.cs @@ -4,11 +4,6 @@ namespace MediaBrowser.Controller.Entities { - public interface IHasShares - { - Share[] Shares { get; set; } - } - public class Share { public string UserId { get; set; } diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index ae1d10447b..6fd0a6c6c3 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -29,7 +29,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. @@ -105,9 +105,9 @@ namespace MediaBrowser.Controller.Entities /// /// This is called before any metadata refresh and returns true or false indicating if changes were made. /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 2724bd9b3d..1b4cc7a78b 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -34,7 +34,7 @@ namespace MediaBrowser.Controller.Entities.TV public IReadOnlyList RemoteTrailerIds { get; set; } /// - /// Gets the season in which it aired. + /// Gets or sets the season in which it aired. /// /// The aired season. public int? AirsBeforeSeasonNumber { get; set; } @@ -44,7 +44,7 @@ namespace MediaBrowser.Controller.Entities.TV public int? AirsBeforeEpisodeNumber { get; set; } /// - /// This is the ending episode number for double episodes. + /// Gets or sets the ending episode number for double episodes. /// /// The index number. public int? IndexNumberEnd { get; set; } @@ -116,7 +116,7 @@ namespace MediaBrowser.Controller.Entities.TV } /// - /// This Episode's Series Instance. + /// Gets the Episode's Series Instance. /// /// The series. [JsonIgnore] @@ -261,6 +261,7 @@ namespace MediaBrowser.Controller.Entities.TV [JsonIgnore] public Guid SeasonId { get; set; } + [JsonIgnore] public Guid SeriesId { get; set; } @@ -318,9 +319,9 @@ namespace MediaBrowser.Controller.Entities.TV return id; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (!IsLocked) { @@ -328,7 +329,7 @@ namespace MediaBrowser.Controller.Entities.TV { try { - if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetdata)) + if (LibraryManager.FillMissingEpisodeNumbersFromPath(this, replaceAllMetadata)) { hasChanges = true; } diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index ad3e0fe8d6..5e2053dcc7 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -81,7 +81,7 @@ namespace MediaBrowser.Controller.Entities.TV } /// - /// This Episode's Series Instance. + /// Gets this Episode's Series Instance. /// /// The series. [JsonIgnore] @@ -242,9 +242,9 @@ namespace MediaBrowser.Controller.Entities.TV /// This is called before any metadata refresh and returns true or false indicating if changes were made. /// /// true if XXXX, false otherwise. - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (!IndexNumber.HasValue && !string.IsNullOrEmpty(Path)) { diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index ded825abc0..44d07b4a48 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -59,8 +59,11 @@ namespace MediaBrowser.Controller.Entities.TV public IReadOnlyList RemoteTrailerIds { get; set; } /// - /// airdate, dvd or absolute. + /// Gets or sets the display order. /// + /// + /// Valid options are airdate, dvd or absolute. + /// public string DisplayOrder { get; set; } /// diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs index b086b5906b..732b45521b 100644 --- a/MediaBrowser.Controller/Entities/Trailer.cs +++ b/MediaBrowser.Controller/Entities/Trailer.cs @@ -45,9 +45,9 @@ namespace MediaBrowser.Controller.Entities return info; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (!ProductionYear.HasValue) { diff --git a/MediaBrowser.Controller/Entities/UserItemData.cs b/MediaBrowser.Controller/Entities/UserItemData.cs index f60359c014..6ab2116d73 100644 --- a/MediaBrowser.Controller/Entities/UserItemData.cs +++ b/MediaBrowser.Controller/Entities/UserItemData.cs @@ -96,7 +96,7 @@ namespace MediaBrowser.Controller.Entities public const double MinLikeValue = 6.5; /// - /// This is an interpreted property to indicate likes or dislikes + /// Gets or sets a value indicating whether the item is liked or not. /// This should never be serialized. /// /// null if [likes] contains no value, true if [likes]; otherwise, false. diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs index e492740ed0..2dea2e50bf 100644 --- a/MediaBrowser.Controller/Entities/UserRootFolder.cs +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -23,6 +23,7 @@ namespace MediaBrowser.Controller.Entities { private List _childrenIds = null; private readonly object _childIdsLock = new object(); + protected override List LoadChildren() { lock (_childIdsLock) @@ -87,10 +88,10 @@ namespace MediaBrowser.Controller.Entities return list; } - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { ClearCache(); - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); if (string.Equals("default", Name, StringComparison.OrdinalIgnoreCase)) { diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 0dfde27667..1e6c01bf8b 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -15,13 +15,19 @@ namespace MediaBrowser.Controller.Entities { public class UserView : Folder, IHasCollectionType { - /// + /// + /// Gets or sets the view type. + /// public string ViewType { get; set; } - /// + /// + /// Gets or sets the display parent id. + /// public new Guid DisplayParentId { get; set; } - /// + /// + /// Gets or sets the user id. + /// public Guid? UserId { get; set; } public static ITVSeriesManager TVSeriesManager; @@ -110,10 +116,10 @@ namespace MediaBrowser.Controller.Entities return GetChildren(user, false); } - private static string[] UserSpecificViewTypes = new string[] - { - Model.Entities.CollectionType.Playlists - }; + private static readonly string[] UserSpecificViewTypes = new string[] + { + Model.Entities.CollectionType.Playlists + }; public static bool IsUserSpecific(Folder folder) { diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index 4d84a151a7..f268bc939e 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -24,7 +24,7 @@ namespace MediaBrowser.Controller.Entities } /// - /// Returns the folder containing the item. + /// Gets the folder containing the item. /// If the item is a folder, it returns the folder itself. /// /// The containing folder path. @@ -112,11 +112,13 @@ namespace MediaBrowser.Controller.Entities } /// - /// This is called before any metadata refresh and returns true or false indicating if changes were made. + /// This is called before any metadata refresh and returns true if changes were made. /// - public override bool BeforeMetadataRefresh(bool replaceAllMetdata) + /// Whether to replace all metadata. + /// true if the item has change, else false. + public override bool BeforeMetadataRefresh(bool replaceAllMetadata) { - var hasChanges = base.BeforeMetadataRefresh(replaceAllMetdata); + var hasChanges = base.BeforeMetadataRefresh(replaceAllMetadata); var newPath = GetRebasedPath(); if (!string.Equals(Path, newPath, StringComparison.Ordinal)) diff --git a/MediaBrowser.Controller/Extensions/StringExtensions.cs b/MediaBrowser.Controller/Extensions/StringExtensions.cs index 8441a31713..48bd9522a8 100644 --- a/MediaBrowser.Controller/Extensions/StringExtensions.cs +++ b/MediaBrowser.Controller/Extensions/StringExtensions.cs @@ -33,7 +33,7 @@ namespace MediaBrowser.Controller.Extensions { // will throw if input contains invalid unicode chars // https://mnaoumov.wordpress.com/2014/06/14/stripping-invalid-characters-from-utf-16-strings/ - text = Regex.Replace(text, "([\ud800-\udbff](?![\udc00-\udfff]))|((? /// Resolves a set of files into a list of BaseItem. /// + /// The list of tiles. + /// Instance of the interface. + /// The parent folder. + /// The library options. + /// The collection type. + /// The list of . IEnumerable ResolvePaths( IEnumerable files, IDirectoryService directoryService, diff --git a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs index 51e56f4b5e..1a893fc2d0 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvChannel.cs @@ -148,7 +148,7 @@ namespace MediaBrowser.Controller.LiveTv public bool IsNews { get; set; } /// - /// Gets or sets a value indicating whether this instance is kids. + /// Gets a value indicating whether this instance is kids. /// /// true if this instance is kids; otherwise, false. [JsonIgnore] diff --git a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs index a66bec11cb..e2adec0009 100644 --- a/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs +++ b/MediaBrowser.Controller/LiveTv/LiveTvProgram.cs @@ -71,7 +71,7 @@ namespace MediaBrowser.Controller.LiveTv public override SourceType SourceType => SourceType.LiveTV; /// - /// The start date of the program, in UTC. + /// Gets or sets start date of the program, in UTC. /// [JsonIgnore] public DateTime StartDate { get; set; } diff --git a/MediaBrowser.Controller/LiveTv/TimerInfo.cs b/MediaBrowser.Controller/LiveTv/TimerInfo.cs index e54dc967ca..1a2e8acb31 100644 --- a/MediaBrowser.Controller/LiveTv/TimerInfo.cs +++ b/MediaBrowser.Controller/LiveTv/TimerInfo.cs @@ -28,18 +28,17 @@ namespace MediaBrowser.Controller.LiveTv public string[] Tags { get; set; } /// - /// Id of the recording. + /// Gets or sets the id of the recording. /// public string Id { get; set; } /// /// Gets or sets the series timer identifier. /// - /// The series timer identifier. public string SeriesTimerId { get; set; } /// - /// ChannelId of the recording. + /// Gets or sets the channelId of the recording. /// public string ChannelId { get; set; } @@ -52,24 +51,24 @@ namespace MediaBrowser.Controller.LiveTv public string ShowId { get; set; } /// - /// Name of the recording. + /// Gets or sets the name of the recording. /// public string Name { get; set; } /// - /// Description of the recording. + /// Gets or sets the description of the recording. /// public string Overview { get; set; } public string SeriesId { get; set; } /// - /// The start date of the recording, in UTC. + /// Gets or sets the start date of the recording, in UTC. /// public DateTime StartDate { get; set; } /// - /// The end date of the recording, in UTC. + /// Gets or sets the end date of the recording, in UTC. /// public DateTime EndDate { get; set; } @@ -133,7 +132,7 @@ namespace MediaBrowser.Controller.LiveTv public bool IsSeries { get; set; } /// - /// Gets or sets a value indicating whether this instance is live. + /// Gets a value indicating whether this instance is live. /// /// true if this instance is live; otherwise, false. [JsonIgnore] diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 97cb8d63ba..9300fd49a1 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -2933,6 +2933,7 @@ namespace MediaBrowser.Controller.MediaEncoding return threads; } + #nullable disable public void TryStreamCopy(EncodingJobInfo state) { diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 1e13382b75..bc34785eeb 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -430,7 +430,7 @@ namespace MediaBrowser.Controller.MediaEncoding } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the target video level. /// public double? TargetVideoLevel { @@ -453,7 +453,7 @@ namespace MediaBrowser.Controller.MediaEncoding } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the target video bit depth. /// public int? TargetVideoBitDepth { @@ -488,7 +488,7 @@ namespace MediaBrowser.Controller.MediaEncoding } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the target framerate. /// public float? TargetFramerate { @@ -520,7 +520,7 @@ namespace MediaBrowser.Controller.MediaEncoding } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the target packet length. /// public int? TargetPacketLength { @@ -536,7 +536,7 @@ namespace MediaBrowser.Controller.MediaEncoding } /// - /// Predicts the audio sample rate that will be in the output stream. + /// Gets the target video profile. /// public string TargetVideoProfile { @@ -700,25 +700,4 @@ namespace MediaBrowser.Controller.MediaEncoding Progress.Report(percentComplete.Value); } } - - /// - /// Enum TranscodingJobType. - /// - public enum TranscodingJobType - { - /// - /// The progressive. - /// - Progressive, - - /// - /// The HLS. - /// - Hls, - - /// - /// The dash. - /// - Dash - } } diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index d3260280a5..76a9fd7c74 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -20,7 +20,7 @@ namespace MediaBrowser.Controller.MediaEncoding public interface IMediaEncoder : ITranscoderSupport { /// - /// The location of the discovered FFmpeg tool. + /// Gets location of the discovered FFmpeg tool. /// FFmpegLocation EncoderLocation { get; } diff --git a/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs b/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs new file mode 100644 index 0000000000..66b6283719 --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/TranscodingJobType.cs @@ -0,0 +1,23 @@ +namespace MediaBrowser.Controller.MediaEncoding +{ + /// + /// Enum TranscodingJobType. + /// + public enum TranscodingJobType + { + /// + /// The progressive. + /// + Progressive, + + /// + /// The HLS. + /// + Hls, + + /// + /// The dash. + /// + Dash + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index a80c116439..f767c2c2b4 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -22,7 +22,8 @@ namespace MediaBrowser.Controller.Playlists { public class Playlist : Folder, IHasShares { - public static string[] SupportedExtensions = + public static readonly IReadOnlyList SupportedExtensions = + new[] { ".m3u", ".m3u8", diff --git a/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs b/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs new file mode 100644 index 0000000000..ea966c2827 --- /dev/null +++ b/MediaBrowser.Controller/Plugins/IRunBeforeStartup.cs @@ -0,0 +1,9 @@ +namespace MediaBrowser.Controller.Plugins +{ + /// + /// Indicates that a should be invoked as a pre-startup task. + /// + public interface IRunBeforeStartup + { + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs b/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs index b44e2531e1..6024661e15 100644 --- a/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs +++ b/MediaBrowser.Controller/Plugins/IServerEntryPoint.cs @@ -14,13 +14,7 @@ namespace MediaBrowser.Controller.Plugins /// /// Run the initialization for this module. This method is invoked at application start. /// + /// A representing the asynchronous operation. Task RunAsync(); } - - /// - /// Indicates that a should be invoked as a pre-startup task. - /// - public interface IRunBeforeStartup - { - } } diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 1152504669..2cf5367793 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -40,7 +40,7 @@ namespace MediaBrowser.Controller.Providers /// /// Gets or sets a value indicating whether all existing data should be overwritten with new data from providers - /// when paired with MetadataRefreshMode=FullRefresh + /// when paired with MetadataRefreshMode=FullRefresh. /// public bool ReplaceAllMetadata { get; set; } diff --git a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs b/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs deleted file mode 100644 index 3d3e44da01..0000000000 --- a/MediaBrowser.Controller/Sync/IHasDynamicAccess.cs +++ /dev/null @@ -1,22 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Sync; - -namespace MediaBrowser.Controller.Sync -{ - public interface IHasDynamicAccess - { - /// - /// Gets the synced file information. - /// - /// The identifier. - /// The target. - /// The cancellation token. - /// Task<SyncedFileInfo>. - Task GetSyncedFileInfo(string id, SyncTarget target, CancellationToken cancellationToken); - } -} diff --git a/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs b/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs deleted file mode 100644 index b2c53365c4..0000000000 --- a/MediaBrowser.Controller/Sync/IRemoteSyncProvider.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace MediaBrowser.Controller.Sync -{ - /// - /// A marker interface. - /// - public interface IRemoteSyncProvider - { - } -} diff --git a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs b/MediaBrowser.Controller/Sync/IServerSyncProvider.cs deleted file mode 100644 index 3891ac0a66..0000000000 --- a/MediaBrowser.Controller/Sync/IServerSyncProvider.cs +++ /dev/null @@ -1,32 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Querying; -using MediaBrowser.Model.Sync; - -namespace MediaBrowser.Controller.Sync -{ - public interface IServerSyncProvider : ISyncProvider - { - /// - /// Transfers the file. - /// - Task SendFile(SyncJob syncJob, string originalMediaPath, Stream inputStream, bool isMedia, string[] outputPathParts, SyncTarget target, IProgress progress, CancellationToken cancellationToken); - - Task> GetFiles(string[] directoryPathParts, SyncTarget target, CancellationToken cancellationToken); - } - - public interface ISupportsDirectCopy - { - /// - /// Sends the file. - /// - Task SendFile(SyncJob syncJob, string originalMediaPath, string inputPath, bool isMedia, string[] outputPathParts, SyncTarget target, IProgress progress, CancellationToken cancellationToken); - } -} diff --git a/MediaBrowser.Controller/Sync/ISyncProvider.cs b/MediaBrowser.Controller/Sync/ISyncProvider.cs deleted file mode 100644 index ea20014c79..0000000000 --- a/MediaBrowser.Controller/Sync/ISyncProvider.cs +++ /dev/null @@ -1,31 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System.Collections.Generic; -using MediaBrowser.Model.Sync; - -namespace MediaBrowser.Controller.Sync -{ - public interface ISyncProvider - { - /// - /// Gets the name. - /// - /// The name. - string Name { get; } - - /// - /// Gets the synchronize targets. - /// - /// The user identifier. - /// IEnumerable<SyncTarget>. - List GetSyncTargets(string userId); - - /// - /// Gets all synchronize targets. - /// - /// IEnumerable<SyncTarget>. - List GetAllSyncTargets(); - } -} diff --git a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs b/MediaBrowser.Controller/Sync/SyncedFileInfo.cs deleted file mode 100644 index 7eac52299b..0000000000 --- a/MediaBrowser.Controller/Sync/SyncedFileInfo.cs +++ /dev/null @@ -1,43 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System.Collections.Generic; -using MediaBrowser.Model.MediaInfo; - -namespace MediaBrowser.Controller.Sync -{ - public class SyncedFileInfo - { - public SyncedFileInfo() - { - RequiredHttpHeaders = new Dictionary(); - } - - /// - /// Gets or sets the path. - /// - /// The path. - public string Path { get; set; } - - public string[] PathParts { get; set; } - - /// - /// Gets or sets the protocol. - /// - /// The protocol. - public MediaProtocol Protocol { get; set; } - - /// - /// Gets or sets the required HTTP headers. - /// - /// The required HTTP headers. - public Dictionary RequiredHttpHeaders { get; set; } - - /// - /// Gets or sets the identifier. - /// - /// The identifier. - public string Id { get; set; } - } -} diff --git a/MediaBrowser.Controller/TV/ITVSeriesManager.cs b/MediaBrowser.Controller/TV/ITVSeriesManager.cs index 291dea04ef..328cf18f69 100644 --- a/MediaBrowser.Controller/TV/ITVSeriesManager.cs +++ b/MediaBrowser.Controller/TV/ITVSeriesManager.cs @@ -6,16 +6,26 @@ using MediaBrowser.Model.Querying; namespace MediaBrowser.Controller.TV { + /// + /// The TV Series manager. + /// public interface ITVSeriesManager { /// /// Gets the next up. /// + /// The next up query. + /// The dto options. + /// The query result of . QueryResult GetNextUp(NextUpQuery query, DtoOptions options); /// /// Gets the next up. /// + /// The next up request. + /// The list of parent folders. + /// The dto options. + /// The query result of . QueryResult GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions options); } } From 3c981cf41f2a8e498e674dc707f15b4ebb2679ae Mon Sep 17 00:00:00 2001 From: peterspenler Date: Thu, 13 May 2021 09:49:20 -0400 Subject: [PATCH 1652/1930] Reorder requested audio channels checks --- CONTRIBUTORS.md | 1 + .../MediaEncoding/EncodingJobInfo.cs | 20 +++++++++---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7a763a46c1..10ea6e8833 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -146,6 +146,7 @@ - [nielsvanvelzen](https://github.com/nielsvanvelzen) - [skyfrk](https://github.com/skyfrk) - [ianjazz246](https://github.com/ianjazz246) + - [peterspenler](https://github.com/peterspenler) # Emby Contributors diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs index 1e13382b75..0bb46df3ff 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobInfo.cs @@ -274,6 +274,16 @@ namespace MediaBrowser.Controller.MediaEncoding public int? GetRequestedAudioChannels(string codec) { + if (!string.IsNullOrEmpty(codec)) + { + var value = BaseRequest.GetOption(codec, "audiochannels"); + if (!string.IsNullOrEmpty(value) + && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) + { + return result; + } + } + if (BaseRequest.MaxAudioChannels.HasValue) { return BaseRequest.MaxAudioChannels; @@ -289,16 +299,6 @@ namespace MediaBrowser.Controller.MediaEncoding return BaseRequest.TranscodingMaxAudioChannels; } - if (!string.IsNullOrEmpty(codec)) - { - var value = BaseRequest.GetOption(codec, "audiochannels"); - if (!string.IsNullOrEmpty(value) - && int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) - { - return result; - } - } - return null; } From 81992ef205c373a854d4da338c6be157e12668dc Mon Sep 17 00:00:00 2001 From: Patrick Barron Date: Thu, 13 May 2021 10:47:00 -0400 Subject: [PATCH 1653/1930] Fix build --- MediaBrowser.Providers/Studios/StudiosImageProvider.cs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs index cd24c7e66a..f6153dd532 100644 --- a/MediaBrowser.Providers/Studios/StudiosImageProvider.cs +++ b/MediaBrowser.Providers/Studios/StudiosImageProvider.cs @@ -172,8 +172,8 @@ namespace MediaBrowser.Providers.Studios public IEnumerable GetAvailableImages(string file) { - using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)); - using (var reader = new StreamReader(fileStream)); + using var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using var reader = new StreamReader(fileStream); var lines = new List(); foreach (var line in reader.ReadAllLines()) @@ -184,11 +184,6 @@ namespace MediaBrowser.Providers.Studios } } - if (!string.IsNullOrWhiteSpace(text)) - { - lines.Add(text); - } - return lines; } } From 73654481e2faf97a089706d9f449de8b9d85238c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Fern=C3=A1ndez?= Date: Wed, 12 May 2021 21:06:53 +0200 Subject: [PATCH 1654/1930] chore: replace GH_TOKEN with JF_BOT_TOKEN --- .github/workflows/automation.yml | 10 +++++----- .github/workflows/merge-conflicts.yml | 2 +- .github/workflows/rebase.yml | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml index 2529d80994..de1590c746 100644 --- a/.github/workflows/automation.yml +++ b/.github/workflows/automation.yml @@ -20,7 +20,7 @@ jobs: with: project: Current Release action: delete - repo-token: ${{ secrets.GH_TOKEN }} + repo-token: ${{ secrets.JF_BOT_TOKEN }} - name: Add to 'Release Next' project uses: alex-page/github-project-automation-plus@v0.7.1 @@ -29,7 +29,7 @@ jobs: with: project: Release Next column: In progress - repo-token: ${{ secrets.GH_TOKEN }} + repo-token: ${{ secrets.JF_BOT_TOKEN }} - name: Add to 'Current Release' project uses: alex-page/github-project-automation-plus@v0.7.1 @@ -38,7 +38,7 @@ jobs: with: project: Current Release column: In progress - repo-token: ${{ secrets.GH_TOKEN }} + repo-token: ${{ secrets.JF_BOT_TOKEN }} - name: Check number of comments from the team member if: github.event.issue.pull_request == '' && github.event.comment.author_association == 'MEMBER' @@ -52,7 +52,7 @@ jobs: with: project: Issue Triage for Main Repo column: Needs triage - repo-token: ${{ secrets.GH_TOKEN }} + repo-token: ${{ secrets.JF_BOT_TOKEN }} - name: Add issue to triage project uses: alex-page/github-project-automation-plus@v0.7.1 @@ -61,4 +61,4 @@ jobs: with: project: Issue Triage for Main Repo column: Pending response - repo-token: ${{ secrets.GH_TOKEN }} + repo-token: ${{ secrets.JF_BOT_TOKEN }} diff --git a/.github/workflows/merge-conflicts.yml b/.github/workflows/merge-conflicts.yml index ce808617a1..1b04eab467 100644 --- a/.github/workflows/merge-conflicts.yml +++ b/.github/workflows/merge-conflicts.yml @@ -14,4 +14,4 @@ jobs: - uses: eps1lon/actions-label-merge-conflict@v2.0.1 with: dirtyLabel: 'merge conflict' - repoToken: ${{ secrets.GH_TOKEN }} + repoToken: ${{ secrets.JF_BOT_TOKEN }} diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml index 3172ec0d9f..3eec9fa033 100644 --- a/.github/workflows/rebase.yml +++ b/.github/workflows/rebase.yml @@ -11,17 +11,17 @@ jobs: - name: Notify as seen uses: peter-evans/create-or-update-comment@v1.4.5 with: - token: ${{ secrets.GH_TOKEN }} + token: ${{ secrets.JF_BOT_TOKEN }} comment-id: ${{ github.event.comment.id }} reactions: '+1' - name: Checkout the latest code uses: actions/checkout@v2 with: - token: ${{ secrets.GH_TOKEN }} + token: ${{ secrets.JF_BOT_TOKEN }} fetch-depth: 0 - name: Automatic Rebase uses: cirrus-actions/rebase@1.4 env: - GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} + GITHUB_TOKEN: ${{ secrets.JF_BOT_TOKEN }} From 66b185898f6c6545989d4c4adcf093f590c7668a Mon Sep 17 00:00:00 2001 From: crobibero Date: Fri, 14 May 2021 17:28:36 -0600 Subject: [PATCH 1655/1930] Update to dotnet5.0.6 --- .../Emby.Server.Implementations.csproj | 2 +- Jellyfin.Api/Jellyfin.Api.csproj | 2 +- .../Jellyfin.Server.Implementations.csproj | 8 ++++---- Jellyfin.Server/Jellyfin.Server.csproj | 4 ++-- deployment/Dockerfile.debian.amd64 | 3 ++- deployment/Dockerfile.debian.arm64 | 3 ++- deployment/Dockerfile.debian.armhf | 3 ++- deployment/Dockerfile.linux.amd64 | 3 ++- deployment/Dockerfile.linux.amd64-musl | 3 ++- deployment/Dockerfile.linux.arm64 | 3 ++- deployment/Dockerfile.linux.armhf | 3 ++- deployment/Dockerfile.macos | 3 ++- deployment/Dockerfile.portable | 3 ++- deployment/Dockerfile.ubuntu.amd64 | 3 ++- deployment/Dockerfile.ubuntu.arm64 | 3 ++- deployment/Dockerfile.ubuntu.armhf | 3 ++- deployment/Dockerfile.windows.amd64 | 3 ++- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 2 +- .../Jellyfin.Server.Integration.Tests.csproj | 2 +- tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj | 2 +- 20 files changed, 37 insertions(+), 24 deletions(-) diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 8ea98f454f..14f6f565c4 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -27,7 +27,7 @@ - + diff --git a/Jellyfin.Api/Jellyfin.Api.csproj b/Jellyfin.Api/Jellyfin.Api.csproj index c10c34b59a..eb9fc4f14c 100644 --- a/Jellyfin.Api/Jellyfin.Api.csproj +++ b/Jellyfin.Api/Jellyfin.Api.csproj @@ -15,7 +15,7 @@ - + diff --git a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj index 2c6a176b69..d24c73526a 100644 --- a/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj +++ b/Jellyfin.Server.Implementations/Jellyfin.Server.Implementations.csproj @@ -27,13 +27,13 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 3496cabe8e..f83de7ac83 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -38,8 +38,8 @@ - - + + diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index ec0321f477..99adf7e1c3 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index 8fd5ddb932..4e10a12f22 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 14615d19fb..17cd01d3e1 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 1f6ca15586..4e5d6486f9 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl index 6af5d8baf5..3dbe00a581 100644 --- a/deployment/Dockerfile.linux.amd64-musl +++ b/deployment/Dockerfile.linux.amd64-musl @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 index 15b59e29d1..0e17c0c4a4 100644 --- a/deployment/Dockerfile.linux.arm64 +++ b/deployment/Dockerfile.linux.arm64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf index 71a0fda215..7df4e51b5f 100644 --- a/deployment/Dockerfile.linux.armhf +++ b/deployment/Dockerfile.linux.armhf @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index 9291bcbb94..e3479ae9c2 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index e98ba74f87..f1774839a8 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,7 +15,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index d1fd8818e6..f723c4cdd1 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index 8e79d417cf..a810844c0c 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 627caa95a8..3838bab828 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,7 +16,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 5723abcae6..007d2648b2 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,7 +15,8 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/5f0f07ab-cd9a-4498-a9f7-67d90d582180/2a3db6698751e6cbb93ec244cb81cc5f/dotnet-sdk-5.0.202-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz + -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index 397b863b70..839cfb2807 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -18,7 +18,7 @@ - + diff --git a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj index 938385a2ad..4bf6faef73 100644 --- a/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj +++ b/tests/Jellyfin.Server.Integration.Tests/Jellyfin.Server.Integration.Tests.csproj @@ -12,7 +12,7 @@ - + diff --git a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj index 72e40ebcb5..260b99df99 100644 --- a/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj +++ b/tests/Jellyfin.Server.Tests/Jellyfin.Server.Tests.csproj @@ -13,7 +13,7 @@ - + From 42be818a09034103301cfc26de0941da10b34fd0 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 15 May 2021 20:28:15 +0200 Subject: [PATCH 1656/1930] Fully disable stupid rules --- jellyfin.ruleset | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 19c0a08b23..b450a3aaf8 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -1,13 +1,6 @@ - - - - - - - @@ -22,6 +15,10 @@ + + + + From 53bfe0e77de6b3d9e8bb4b9740c8fbe009b145c5 Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Sat, 15 May 2021 20:24:41 +0100 Subject: [PATCH 1657/1930] Changes as requested --- tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj | 3 +-- .../Controllers/EncoderController.cs | 6 +++--- .../EncodedQueryStringTest.cs | 2 +- 3 files changed, 5 insertions(+), 6 deletions(-) rename Jellyfin.Api/Controllers/TestsController.cs => tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs (87%) diff --git a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj index e3577caeee..806e4ea1d0 100644 --- a/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj +++ b/tests/Jellyfin.Api.Tests/Jellyfin.Api.Tests.csproj @@ -36,8 +36,7 @@ - - + diff --git a/Jellyfin.Api/Controllers/TestsController.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs similarity index 87% rename from Jellyfin.Api/Controllers/TestsController.cs rename to tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs index 1d1e1899fd..98ea00de6a 100644 --- a/Jellyfin.Api/Controllers/TestsController.cs +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/EncoderController.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Jellyfin.Api.Constants; using Microsoft.AspNetCore.Authorization; @@ -8,9 +8,9 @@ using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Api.Controllers { /// - /// Controller for testing. + /// Controller for testing the encoded url. /// - public class TestsController : BaseJellyfinApiController + public class EncoderController : BaseJellyfinApiController { /// /// Tests the url decoding. diff --git a/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs index 0d1e408c85..29d3fe33d0 100644 --- a/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs +++ b/tests/Jellyfin.Server.Integration.Tests/EncodedQueryStringTest.cs @@ -24,7 +24,7 @@ namespace Jellyfin.Server.Integration.Tests { var client = _factory.CreateClient(); - var response = await client.GetAsync("Tests/UrlDecode?" + sourceUrl).ConfigureAwait(false); + var response = await client.GetAsync("Encoder/UrlDecode?" + sourceUrl).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); string reply = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Assert.Equal(unencodedUrl, reply); From b6dda30a33e7ea3465629e041be74b3e9022d810 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sat, 15 May 2021 15:33:50 -0600 Subject: [PATCH 1658/1930] Fix suggestions from review --- .../Channels/IChannelManager.cs | 14 +++++++------- .../Channels/ISupportsDelete.cs | 4 +--- .../Channels/ISupportsLatestMedia.cs | 2 +- MediaBrowser.Controller/Dto/IDtoService.cs | 2 +- .../Library/ILibraryManager.cs | 2 +- MediaBrowser.Controller/Playlists/Playlist.cs | 17 ++++++++--------- MediaBrowser.Controller/TV/ITVSeriesManager.cs | 4 ++-- 7 files changed, 21 insertions(+), 24 deletions(-) diff --git a/MediaBrowser.Controller/Channels/IChannelManager.cs b/MediaBrowser.Controller/Channels/IChannelManager.cs index 95d95465e0..49be897ef3 100644 --- a/MediaBrowser.Controller/Channels/IChannelManager.cs +++ b/MediaBrowser.Controller/Channels/IChannelManager.cs @@ -51,14 +51,14 @@ namespace MediaBrowser.Controller.Channels /// Gets the channels internal. /// /// The query. - /// The of . + /// The channels. QueryResult GetChannelsInternal(ChannelQuery query); /// /// Gets the channels. /// /// The query. - /// The of . + /// The channels. QueryResult GetChannels(ChannelQuery query); /// @@ -66,7 +66,7 @@ namespace MediaBrowser.Controller.Channels /// /// The item query. /// The cancellation token. - /// A containing the of . + /// The latest channels. Task> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken); /// @@ -74,7 +74,7 @@ namespace MediaBrowser.Controller.Channels /// /// The item query. /// The cancellation token. - /// A containing the of . + /// The latest channels. Task> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken); /// @@ -82,7 +82,7 @@ namespace MediaBrowser.Controller.Channels /// /// The query. /// The cancellation token. - /// A containing the of . + /// The channel items. Task> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken); /// @@ -91,7 +91,7 @@ namespace MediaBrowser.Controller.Channels /// The query. /// The progress to report to. /// The cancellation token. - /// A containing the of . + /// The channel items. Task> GetChannelItemsInternal(InternalItemsQuery query, IProgress progress, CancellationToken cancellationToken); /// @@ -99,7 +99,7 @@ namespace MediaBrowser.Controller.Channels /// /// The item. /// The cancellation token. - /// Task{IEnumerable{MediaSourceInfo}}. + /// The item media sources. IEnumerable GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken); /// diff --git a/MediaBrowser.Controller/Channels/ISupportsDelete.cs b/MediaBrowser.Controller/Channels/ISupportsDelete.cs index d7234fa38f..204054374e 100644 --- a/MediaBrowser.Controller/Channels/ISupportsDelete.cs +++ b/MediaBrowser.Controller/Channels/ISupportsDelete.cs @@ -1,6 +1,4 @@ -#nullable disable - -#pragma warning disable CS1591 +#pragma warning disable CS1591 using System.Threading; using System.Threading.Tasks; diff --git a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs index 6820d9222c..dbba7cba2d 100644 --- a/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs +++ b/MediaBrowser.Controller/Channels/ISupportsLatestMedia.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Controller.Channels /// /// The request. /// The cancellation token. - /// Task{IEnumerable{ChannelItemInfo}}. + /// The latest media. Task> GetLatestMedia(ChannelLatestMediaSearch request, CancellationToken cancellationToken); } } \ No newline at end of file diff --git a/MediaBrowser.Controller/Dto/IDtoService.cs b/MediaBrowser.Controller/Dto/IDtoService.cs index e0950b1f61..61d7962357 100644 --- a/MediaBrowser.Controller/Dto/IDtoService.cs +++ b/MediaBrowser.Controller/Dto/IDtoService.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Controller.Dto /// The dto options. /// The list of tagged items. /// The user. - /// The . + /// The item dto. BaseItemDto GetItemByNameDto(BaseItem item, DtoOptions options, List taggedItems, User user = null); } } diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index ca21569a7e..3fd4ff899a 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -48,7 +48,7 @@ namespace MediaBrowser.Controller.Library /// The parent folder. /// The library options. /// The collection type. - /// The list of . + /// The items resolved from the paths. IEnumerable ResolvePaths( IEnumerable files, IDirectoryService directoryService, diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index f767c2c2b4..bb9e5da1e3 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -22,15 +22,14 @@ namespace MediaBrowser.Controller.Playlists { public class Playlist : Folder, IHasShares { - public static readonly IReadOnlyList SupportedExtensions = - new[] - { - ".m3u", - ".m3u8", - ".pls", - ".wpl", - ".zpl" - }; + public static readonly IReadOnlyList SupportedExtensions = new[] + { + ".m3u", + ".m3u8", + ".pls", + ".wpl", + ".zpl" + }; public Guid OwnerUserId { get; set; } diff --git a/MediaBrowser.Controller/TV/ITVSeriesManager.cs b/MediaBrowser.Controller/TV/ITVSeriesManager.cs index 328cf18f69..e066c03fdc 100644 --- a/MediaBrowser.Controller/TV/ITVSeriesManager.cs +++ b/MediaBrowser.Controller/TV/ITVSeriesManager.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Controller.TV /// /// The next up query. /// The dto options. - /// The query result of . + /// The next up items. QueryResult GetNextUp(NextUpQuery query, DtoOptions options); /// @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.TV /// The next up request. /// The list of parent folders. /// The dto options. - /// The query result of . + /// The next up items. QueryResult GetNextUp(NextUpQuery request, BaseItem[] parentsFolders, DtoOptions options); } } From a9f44c21eb273f395bd4f1ae11885700bcde178b Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Sat, 15 May 2021 21:49:04 +0200 Subject: [PATCH 1659/1930] Add tests for Recordinghelper --- .../LiveTv/EmbyTV/RecordingHelper.cs | 14 +-- jellyfin.ruleset | 2 + .../LiveTv/RecordingHelperTests.cs | 115 ++++++++++++++++++ 3 files changed, 119 insertions(+), 12 deletions(-) create mode 100644 tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs index 142c59542a..32245f899e 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs @@ -6,7 +6,7 @@ using MediaBrowser.Controller.LiveTv; namespace Emby.Server.Implementations.LiveTv.EmbyTV { - internal class RecordingHelper + internal static class RecordingHelper { public static DateTime GetStartTime(TimerInfo timer) { @@ -70,17 +70,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV private static string GetDateString(DateTime date) { - date = date.ToLocalTime(); - - return string.Format( - CultureInfo.InvariantCulture, - "{0}_{1}_{2}_{3}_{4}_{5}", - date.Year.ToString("0000", CultureInfo.InvariantCulture), - date.Month.ToString("00", CultureInfo.InvariantCulture), - date.Day.ToString("00", CultureInfo.InvariantCulture), - date.Hour.ToString("00", CultureInfo.InvariantCulture), - date.Minute.ToString("00", CultureInfo.InvariantCulture), - date.Second.ToString("00", CultureInfo.InvariantCulture)); + return date.ToLocalTime().ToString("yyyy_MM_dd_HH_mm_ss", CultureInfo.InvariantCulture); } } } diff --git a/jellyfin.ruleset b/jellyfin.ruleset index 19c0a08b23..6ba36d35cc 100644 --- a/jellyfin.ruleset +++ b/jellyfin.ruleset @@ -43,6 +43,8 @@ or pass in 'CancellationToken.None' explicitly to indicate intentionally not propagating the token --> + + diff --git a/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs new file mode 100644 index 0000000000..e8b93b437b --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/LiveTv/RecordingHelperTests.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using Emby.Server.Implementations.LiveTv.EmbyTV; +using MediaBrowser.Controller.LiveTv; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.LiveTv +{ + public static class RecordingHelperTests + { + public static IEnumerable GetRecordingName_Success_TestData() + { + yield return new object[] + { + "The Incredibles 2020_04_20_21_06_00", + new TimerInfo + { + Name = "The Incredibles", + StartDate = new DateTime(2020, 4, 20, 21, 6, 0, DateTimeKind.Local), + IsMovie = true + } + }; + + yield return new object[] + { + "The Incredibles (2004)", + new TimerInfo + { + Name = "The Incredibles", + IsMovie = true, + ProductionYear = 2004 + } + }; + + yield return new object[] + { + "The Big Bang Theory 2020_04_20_21_06_00", + new TimerInfo + { + Name = "The Big Bang Theory", + StartDate = new DateTime(2020, 4, 20, 21, 6, 0, DateTimeKind.Local), + IsProgramSeries = true, + } + }; + + yield return new object[] + { + "The Big Bang Theory S12E10", + new TimerInfo + { + Name = "The Big Bang Theory", + IsProgramSeries = true, + SeasonNumber = 12, + EpisodeNumber = 10 + } + }; + + yield return new object[] + { + "The Big Bang Theory S12E10 The VCR Illumination", + new TimerInfo + { + Name = "The Big Bang Theory", + IsProgramSeries = true, + SeasonNumber = 12, + EpisodeNumber = 10, + EpisodeTitle = "The VCR Illumination" + } + }; + + yield return new object[] + { + "The Big Bang Theory 2018-12-06", + new TimerInfo + { + Name = "The Big Bang Theory", + IsProgramSeries = true, + OriginalAirDate = new DateTime(2018, 12, 6) + } + }; + + yield return new object[] + { + "The Big Bang Theory 2018-12-06 - The VCR Illumination", + new TimerInfo + { + Name = "The Big Bang Theory", + IsProgramSeries = true, + OriginalAirDate = new DateTime(2018, 12, 6), + EpisodeTitle = "The VCR Illumination" + } + }; + + yield return new object[] + { + "The Big Bang Theory 2018_12_06_21_06_00 - The VCR Illumination", + new TimerInfo + { + Name = "The Big Bang Theory", + StartDate = new DateTime(2018, 12, 6, 21, 6, 0, DateTimeKind.Local), + IsProgramSeries = true, + OriginalAirDate = new DateTime(2018, 12, 6), + EpisodeTitle = "The VCR Illumination" + } + }; + } + + [Theory] + [MemberData(nameof(GetRecordingName_Success_TestData))] + public static void GetRecordingName_Success(string expected, TimerInfo timerInfo) + { + Assert.Equal(expected, RecordingHelper.GetRecordingName(timerInfo)); + } + } +} From ffc5aba023ee8ba77331447929079f0b0f4068a2 Mon Sep 17 00:00:00 2001 From: nyanmisaka Date: Sun, 16 May 2021 18:40:28 +0800 Subject: [PATCH 1660/1930] Fix the 'No decoder surfaces left' error on Cuda --- MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index 97cb8d63ba..61d583d944 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -596,7 +596,8 @@ namespace MediaBrowser.Controller.MediaEncoding && string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && isNvdecDecoder) { - arg.Append("-hwaccel_output_format cuda -autorotate 0 "); + // Fix for 'No decoder surfaces left' error. https://trac.ffmpeg.org/ticket/7562 + arg.Append("-hwaccel_output_format cuda -extra_hw_frames 3 -autorotate 0 "); } if (state.IsVideoRequest @@ -1070,7 +1071,6 @@ namespace MediaBrowser.Controller.MediaEncoding else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc) || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc) { - // following preset will be deprecated in ffmpeg 4.4, use p1~p7 instead. switch (encodingOptions.EncoderPreset) { case "veryslow": @@ -1251,7 +1251,7 @@ namespace MediaBrowser.Controller.MediaEncoding } if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) - && profile.Contains("constrainedbaseline", StringComparison.OrdinalIgnoreCase)) + && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase)) { profile = "constrained_baseline"; } From 1b49435a0eb18595c84236fb8cf7671263f3c3cf Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 16 May 2021 14:49:11 +0200 Subject: [PATCH 1661/1930] Reduce some allocations --- Emby.Naming/Audio/AudioFileParser.cs | 6 +- Emby.Naming/Emby.Naming.csproj | 1 + Emby.Naming/Video/ExtraResolver.cs | 119 ++-- Emby.Naming/Video/VideoResolver.cs | 22 +- .../Data/BaseSqliteRepository.cs | 6 +- .../Data/SqliteExtensions.cs | 110 +++- .../Data/SqliteItemRepository.cs | 569 +++++++----------- .../Data/SqliteUserDataRepository.cs | 16 +- .../Security/AuthorizationContext.cs | 36 +- .../Library/Resolvers/BaseVideoResolver.cs | 16 +- .../Security/AuthenticationRepository.cs | 41 +- Jellyfin.sln | 11 + .../Extensions/EnumerableExtensions.cs | 51 ++ .../Images/LocalImageProvider.cs | 17 +- .../MediaInfo/SubtitleResolver.cs | 219 ++++--- .../Jellyfin.Providers.Tests.csproj | 37 ++ .../MediaInfo/SubtitleResolverTests.cs | 96 +++ 17 files changed, 778 insertions(+), 595 deletions(-) create mode 100644 MediaBrowser.Common/Extensions/EnumerableExtensions.cs create mode 100644 tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj create mode 100644 tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs diff --git a/Emby.Naming/Audio/AudioFileParser.cs b/Emby.Naming/Audio/AudioFileParser.cs index 8b47dd12e4..af4aa0059f 100644 --- a/Emby.Naming/Audio/AudioFileParser.cs +++ b/Emby.Naming/Audio/AudioFileParser.cs @@ -1,7 +1,7 @@ using System; using System.IO; -using System.Linq; using Emby.Naming.Common; +using MediaBrowser.Common.Extensions; namespace Emby.Naming.Audio { @@ -18,8 +18,8 @@ namespace Emby.Naming.Audio /// True if file at path is audio file. public static bool IsAudioFile(string path, NamingOptions options) { - var extension = Path.GetExtension(path); - return options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); + var extension = Path.GetExtension(path.AsSpan()); + return options.AudioFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); } } } diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 63116f3680..a93ddbcb8a 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -27,6 +27,7 @@ + diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index 1d3b36a1ad..f9d06c09be 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -29,72 +29,75 @@ namespace Emby.Naming.Video /// Path to file. /// Returns object. public ExtraResult GetExtraInfo(string path) - { - return _options.VideoExtraRules - .Select(i => GetExtraInfo(path, i)) - .FirstOrDefault(i => i.ExtraType != null) ?? new ExtraResult(); - } - - private ExtraResult GetExtraInfo(string path, ExtraRule rule) { var result = new ExtraResult(); - if (rule.MediaType == MediaType.Audio) + for (var i = 0; i < _options.VideoExtraRules.Length; i++) { - if (!AudioFileParser.IsAudioFile(path, _options)) + var rule = _options.VideoExtraRules[i]; + if (rule.MediaType == MediaType.Audio) + { + if (!AudioFileParser.IsAudioFile(path, _options)) + { + continue; + } + } + else if (rule.MediaType == MediaType.Video) + { + if (!new VideoResolver(_options).IsVideoFile(path)) + { + continue; + } + } + + var pathSpan = path.AsSpan(); + if (rule.RuleType == ExtraRuleType.Filename) + { + var filename = Path.GetFileNameWithoutExtension(pathSpan); + + if (filename.Equals(rule.Token, StringComparison.OrdinalIgnoreCase)) + { + result.ExtraType = rule.ExtraType; + result.Rule = rule; + } + } + else if (rule.RuleType == ExtraRuleType.Suffix) + { + var filename = Path.GetFileNameWithoutExtension(pathSpan); + + if (filename.Contains(rule.Token, StringComparison.OrdinalIgnoreCase)) + { + result.ExtraType = rule.ExtraType; + result.Rule = rule; + } + } + else if (rule.RuleType == ExtraRuleType.Regex) + { + var filename = Path.GetFileName(path); + + var regex = new Regex(rule.Token, RegexOptions.IgnoreCase); + + if (regex.IsMatch(filename)) + { + result.ExtraType = rule.ExtraType; + result.Rule = rule; + } + } + else if (rule.RuleType == ExtraRuleType.DirectoryName) + { + var directoryName = Path.GetFileName(Path.GetDirectoryName(pathSpan)); + if (directoryName.Equals(rule.Token, StringComparison.OrdinalIgnoreCase)) + { + result.ExtraType = rule.ExtraType; + result.Rule = rule; + } + } + + if (result.ExtraType != null) { return result; } } - else if (rule.MediaType == MediaType.Video) - { - if (!new VideoResolver(_options).IsVideoFile(path)) - { - return result; - } - } - - if (rule.RuleType == ExtraRuleType.Filename) - { - var filename = Path.GetFileNameWithoutExtension(path); - - if (string.Equals(filename, rule.Token, StringComparison.OrdinalIgnoreCase)) - { - result.ExtraType = rule.ExtraType; - result.Rule = rule; - } - } - else if (rule.RuleType == ExtraRuleType.Suffix) - { - var filename = Path.GetFileNameWithoutExtension(path); - - if (filename.IndexOf(rule.Token, StringComparison.OrdinalIgnoreCase) > 0) - { - result.ExtraType = rule.ExtraType; - result.Rule = rule; - } - } - else if (rule.RuleType == ExtraRuleType.Regex) - { - var filename = Path.GetFileName(path); - - var regex = new Regex(rule.Token, RegexOptions.IgnoreCase); - - if (regex.IsMatch(filename)) - { - result.ExtraType = rule.ExtraType; - result.Rule = rule; - } - } - else if (rule.RuleType == ExtraRuleType.DirectoryName) - { - var directoryName = Path.GetFileName(Path.GetDirectoryName(path)); - if (string.Equals(directoryName, rule.Token, StringComparison.OrdinalIgnoreCase)) - { - result.ExtraType = rule.ExtraType; - result.Rule = rule; - } - } return result; } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 79a6da8f7b..d1c294f4fd 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -1,8 +1,8 @@ using System; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using Emby.Naming.Common; +using MediaBrowser.Common.Extensions; namespace Emby.Naming.Video { @@ -59,15 +59,15 @@ namespace Emby.Naming.Video } bool isStub = false; - string? container = null; + ReadOnlySpan container = null; string? stubType = null; if (!isDirectory) { - var extension = Path.GetExtension(path); + var extension = Path.GetExtension(path.AsSpan()); // Check supported extensions - if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) + if (!_options.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase)) { // It's not supported. Check stub extensions if (!StubResolver.TryResolveFile(path, _options, out stubType)) @@ -86,9 +86,7 @@ namespace Emby.Naming.Video var extraResult = new ExtraResolver(_options).GetExtraInfo(path); - var name = isDirectory - ? Path.GetFileName(path) - : Path.GetFileNameWithoutExtension(path); + var name = Path.GetFileNameWithoutExtension(path); int? year = null; @@ -107,7 +105,7 @@ namespace Emby.Naming.Video return new VideoFileInfo( path: path, - container: container, + container: container.ToString(), isStub: isStub, name: name, year: year, @@ -126,8 +124,8 @@ namespace Emby.Naming.Video /// True if is video file. public bool IsVideoFile(string path) { - var extension = Path.GetExtension(path); - return _options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); + var extension = Path.GetExtension(path.AsSpan()); + return _options.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); } /// @@ -137,8 +135,8 @@ namespace Emby.Naming.Video /// True if is video file stub. public bool IsStubFile(string path) { - var extension = Path.GetExtension(path); - return _options.StubFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); + var extension = Path.GetExtension(path.AsSpan()); + return _options.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); } /// diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index 8c756a7f4c..c331a61124 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -181,11 +181,9 @@ namespace Emby.Server.Implementations.Data foreach (var row in connection.Query("PRAGMA table_info(" + table + ")")) { - if (row[1].SQLiteType != SQLiteType.Null) + if (row.TryGetString(1, out var columnName)) { - var name = row[1].ToString(); - - columnNames.Add(name); + columnNames.Add(columnName); } } diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index a04d630887..db30102074 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using SQLitePCL.pretty; @@ -96,21 +97,42 @@ namespace Emby.Server.Implementations.Data DateTimeStyles.None).ToUniversalTime(); } - public static DateTime? TryReadDateTime(this IResultSetValue result) + public static bool TryReadDateTime(this IReadOnlyList reader, int index, [NotNullWhen(true)] out DateTime? result) { - var dateText = result.ToString(); + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + var dateText = item.ToString(); if (DateTime.TryParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var dateTimeResult)) { - return dateTimeResult.ToUniversalTime(); + result = dateTimeResult.ToUniversalTime(); + return true; } - return null; + return false; } - public static bool IsDBNull(this IReadOnlyList result, int index) + public static bool TryGetGuid(this IReadOnlyList reader, int index, [NotNullWhen(true)] out Guid? result) { - return result[index].SQLiteType == SQLiteType.Null; + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ReadGuidFromBlob(); + return true; + } + + private static bool IsDbNull(this IResultSetValue result) + { + return result.SQLiteType == SQLiteType.Null; } public static string GetString(this IReadOnlyList result, int index) @@ -118,14 +140,48 @@ namespace Emby.Server.Implementations.Data return result[index].ToString(); } + public static bool TryGetString(this IReadOnlyList reader, int index, out string result) + { + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToString(); + return true; + } + public static bool GetBoolean(this IReadOnlyList result, int index) { return result[index].ToBool(); } - public static int GetInt32(this IReadOnlyList result, int index) + public static bool TryGetBoolean(this IReadOnlyList reader, int index, [NotNullWhen(true)] out bool? result) { - return result[index].ToInt(); + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToBool(); + return true; + } + + public static bool TryGetInt(this IReadOnlyList reader, int index, out int? result) + { + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToInt(); + return true; } public static long GetInt64(this IReadOnlyList result, int index) @@ -133,9 +189,43 @@ namespace Emby.Server.Implementations.Data return result[index].ToInt64(); } - public static float GetFloat(this IReadOnlyList result, int index) + public static bool TryGetLong(this IReadOnlyList reader, int index, out long? result) { - return result[index].ToFloat(); + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToInt64(); + return true; + } + + public static bool TryGetFloat(this IReadOnlyList reader, int index, out float? result) + { + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToFloat(); + return true; + } + + public static bool TryGetDouble(this IReadOnlyList reader, int index, out double? result) + { + result = null; + var item = reader[index]; + if (item.IsDbNull()) + { + return false; + } + + result = item.ToDouble(); + return true; } public static Guid GetGuid(this IReadOnlyList result, int index) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 835eb06924..53c9a4cad4 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1332,27 +1332,23 @@ namespace Emby.Server.Implementations.Data if (queryHasStartDate) { - if (!reader.IsDBNull(index)) + if (item is IHasStartDate hasStartDate && reader.TryReadDateTime(index, out var startDate)) { - if (item is IHasStartDate hasStartDate) - { - hasStartDate.StartDate = reader[index].ReadDateTime(); - } + hasStartDate.StartDate = startDate.Value; } index++; } - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var endDate)) { - item.EndDate = reader[index].TryReadDateTime(); + item.EndDate = endDate; } - index++; - - if (!reader.IsDBNull(index)) + var channelId = reader[index]; + if (channelId.SQLiteType != SQLiteType.Null) { - if (!Utf8Parser.TryParse(reader[index].ToBlob(), out Guid value, out _, standardFormat: 'N')) + if (!Utf8Parser.TryParse(channelId.ToBlob(), out Guid value, out _, standardFormat: 'N')) { var str = reader.GetString(index); Logger.LogWarning("{ChannelId} isn't in the expected format", str); @@ -1368,33 +1364,25 @@ namespace Emby.Server.Implementations.Data { if (item is IHasProgramAttributes hasProgramAttributes) { - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isMovie)) { - hasProgramAttributes.IsMovie = reader.GetBoolean(index); + hasProgramAttributes.IsMovie = isMovie.Value; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isSeries)) { - hasProgramAttributes.IsSeries = reader.GetBoolean(index); + hasProgramAttributes.IsSeries = isSeries.Value; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var episodeTitle)) { - hasProgramAttributes.EpisodeTitle = reader.GetString(index); + hasProgramAttributes.EpisodeTitle = episodeTitle; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isRepeat)) { - hasProgramAttributes.IsRepeat = reader.GetBoolean(index); + hasProgramAttributes.IsRepeat = isRepeat.Value; } - - index++; } else { @@ -1402,242 +1390,189 @@ namespace Emby.Server.Implementations.Data } } - if (!reader.IsDBNull(index)) + if (reader.TryGetFloat(index++, out var communityRating)) { - item.CommunityRating = reader.GetFloat(index); + item.CommunityRating = communityRating; } - index++; - if (HasField(query, ItemFields.CustomRating)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var customRating)) { - item.CustomRating = reader.GetString(index); + item.CustomRating = customRating; } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var indexNumber)) { - item.IndexNumber = reader.GetInt32(index); + item.IndexNumber = indexNumber; } - index++; - if (HasField(query, ItemFields.Settings)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isLocked)) { - item.IsLocked = reader.GetBoolean(index); + item.IsLocked = isLocked.Value; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var preferredMetadataLanguage)) { - item.PreferredMetadataLanguage = reader.GetString(index); + item.PreferredMetadataLanguage = preferredMetadataLanguage; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var preferredMetadataCountryCode)) { - item.PreferredMetadataCountryCode = reader.GetString(index); + item.PreferredMetadataCountryCode = preferredMetadataCountryCode; } - - index++; } if (HasField(query, ItemFields.Width)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var width)) { - item.Width = reader.GetInt32(index); + item.Width = width.Value; } - - index++; } if (HasField(query, ItemFields.Height)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var height)) { - item.Height = reader.GetInt32(index); + item.Height = height.Value; } - - index++; } if (HasField(query, ItemFields.DateLastRefreshed)) { - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var dateLastRefreshed)) { - item.DateLastRefreshed = reader[index].ReadDateTime(); + item.DateLastRefreshed = dateLastRefreshed.Value; } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var name)) { - item.Name = reader.GetString(index); + item.Name = name; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var restorePath)) { - item.Path = RestorePath(reader.GetString(index)); + item.Path = RestorePath(restorePath); } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var premiereDate)) { - item.PremiereDate = reader[index].TryReadDateTime(); + item.PremiereDate = premiereDate; } - index++; - if (HasField(query, ItemFields.Overview)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var overview)) { - item.Overview = reader.GetString(index); + item.Overview = overview; } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var parentIndexNumber)) { - item.ParentIndexNumber = reader.GetInt32(index); + item.ParentIndexNumber = parentIndexNumber; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var productionYear)) { - item.ProductionYear = reader.GetInt32(index); + item.ProductionYear = productionYear; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var officialRating)) { - item.OfficialRating = reader.GetString(index); + item.OfficialRating = officialRating; } - index++; - if (HasField(query, ItemFields.SortName)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var forcedSortName)) { - item.ForcedSortName = reader.GetString(index); + item.ForcedSortName = forcedSortName; } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetLong(index++, out var runTimeTicks)) { - item.RunTimeTicks = reader.GetInt64(index); + item.RunTimeTicks = runTimeTicks; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetLong(index++, out var size)) { - item.Size = reader.GetInt64(index); + item.Size = size; } - index++; - if (HasField(query, ItemFields.DateCreated)) { - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var dateCreated)) { - item.DateCreated = reader[index].ReadDateTime(); + item.DateCreated = dateCreated.Value; } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var dateModified)) { - item.DateModified = reader[index].ReadDateTime(); + item.DateModified = dateModified.Value; } - index++; - - item.Id = reader.GetGuid(index); - index++; + item.Id = reader.GetGuid(index++); if (HasField(query, ItemFields.Genres)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var genres)) { - item.Genres = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); + item.Genres = genres.Split('|', StringSplitOptions.RemoveEmptyEntries); } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetGuid(index++, out var parentId)) { - item.ParentId = reader.GetGuid(index); + item.ParentId = parentId.Value; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var audioString)) { - if (Enum.TryParse(reader.GetString(index), true, out ProgramAudio audio)) + if (Enum.TryParse(audioString, true, out ProgramAudio audio)) { item.Audio = audio; } } - index++; - // TODO: Even if not needed by apps, the server needs it internally // But get this excluded from contexts where it is not needed if (hasServiceName) { if (item is LiveTvChannel liveTvChannel) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var serviceName)) { - liveTvChannel.ServiceName = reader.GetString(index); + liveTvChannel.ServiceName = serviceName; } } index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isInMixedFolder)) { - item.IsInMixedFolder = reader.GetBoolean(index); + item.IsInMixedFolder = isInMixedFolder.Value; } - index++; - if (HasField(query, ItemFields.DateLastSaved)) { - if (!reader.IsDBNull(index)) + if (reader.TryReadDateTime(index++, out var dateLastSaved)) { - item.DateLastSaved = reader[index].ReadDateTime(); + item.DateLastSaved = dateLastSaved.Value; } - - index++; } if (HasField(query, ItemFields.Settings)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var lockedFields)) { IEnumerable GetLockedFields(string s) { @@ -1650,37 +1585,31 @@ namespace Emby.Server.Implementations.Data } } - item.LockedFields = GetLockedFields(reader.GetString(index)).ToArray(); + item.LockedFields = GetLockedFields(lockedFields).ToArray(); } - - index++; } if (HasField(query, ItemFields.Studios)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var studios)) { - item.Studios = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); + item.Studios = studios.Split('|', StringSplitOptions.RemoveEmptyEntries); } - - index++; } if (HasField(query, ItemFields.Tags)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var tags)) { - item.Tags = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); + item.Tags = tags.Split('|', StringSplitOptions.RemoveEmptyEntries); } - - index++; } if (hasTrailerTypes) { if (item is Trailer trailer) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var trailerTypes)) { IEnumerable GetTrailerTypes(string s) { @@ -1693,7 +1622,7 @@ namespace Emby.Server.Implementations.Data } } - trailer.TrailerTypes = GetTrailerTypes(reader.GetString(index)).ToArray(); + trailer.TrailerTypes = GetTrailerTypes(trailerTypes).ToArray(); } } @@ -1702,19 +1631,17 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.OriginalTitle)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var originalTitle)) { - item.OriginalTitle = reader.GetString(index); + item.OriginalTitle = originalTitle; } - - index++; } if (item is Video video) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var primaryVersionId)) { - video.PrimaryVersionId = reader.GetString(index); + video.PrimaryVersionId = primaryVersionId; } } @@ -1722,40 +1649,34 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.DateLastMediaAdded)) { - if (item is Folder folder && !reader.IsDBNull(index)) + if (item is Folder folder && reader.TryReadDateTime(index, out var dateLastMediaAdded)) { - folder.DateLastMediaAdded = reader[index].TryReadDateTime(); + folder.DateLastMediaAdded = dateLastMediaAdded; } index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var album)) { - item.Album = reader.GetString(index); + item.Album = album; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetFloat(index++, out var criticRating)) { - item.CriticRating = reader.GetFloat(index); + item.CriticRating = criticRating; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetBoolean(index++, out var isVirtualItem)) { - item.IsVirtualItem = reader.GetBoolean(index); + item.IsVirtualItem = isVirtualItem.Value; } - index++; - if (item is IHasSeries hasSeriesName) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var seriesName)) { - hasSeriesName.SeriesName = reader.GetString(index); + hasSeriesName.SeriesName = seriesName; } } @@ -1765,15 +1686,15 @@ namespace Emby.Server.Implementations.Data { if (item is Episode episode) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var seasonName)) { - episode.SeasonName = reader.GetString(index); + episode.SeasonName = seasonName; } index++; - if (!reader.IsDBNull(index)) + if (reader.TryGetGuid(index, out var seasonId)) { - episode.SeasonId = reader.GetGuid(index); + episode.SeasonId = seasonId.Value; } } else @@ -1789,9 +1710,9 @@ namespace Emby.Server.Implementations.Data { if (hasSeries != null) { - if (!reader.IsDBNull(index)) + if (reader.TryGetGuid(index, out var seriesId)) { - hasSeries.SeriesId = reader.GetGuid(index); + hasSeries.SeriesId = seriesId.Value; } } @@ -1800,56 +1721,48 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.PresentationUniqueKey)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var presentationUniqueKey)) { - item.PresentationUniqueKey = reader.GetString(index); + item.PresentationUniqueKey = presentationUniqueKey; } - - index++; } if (HasField(query, ItemFields.InheritedParentalRatingValue)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var parentalRating)) { - item.InheritedParentalRatingValue = reader.GetInt32(index); + item.InheritedParentalRatingValue = parentalRating.Value; } - - index++; } if (HasField(query, ItemFields.ExternalSeriesId)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var externalSeriesId)) { - item.ExternalSeriesId = reader.GetString(index); + item.ExternalSeriesId = externalSeriesId; } - - index++; } if (HasField(query, ItemFields.Taglines)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var tagLine)) { - item.Tagline = reader.GetString(index); + item.Tagline = tagLine; } - - index++; } - if (item.ProviderIds.Count == 0 && !reader.IsDBNull(index)) + if (item.ProviderIds.Count == 0 && reader.TryGetString(index, out var providerIds)) { - DeserializeProviderIds(reader.GetString(index), item); + DeserializeProviderIds(providerIds, item); } index++; if (query.DtoOptions.EnableImages) { - if (item.ImageInfos.Length == 0 && !reader.IsDBNull(index)) + if (item.ImageInfos.Length == 0 && reader.TryGetString(index, out var imageInfos)) { - item.ImageInfos = DeserializeImages(reader.GetString(index)); + item.ImageInfos = DeserializeImages(imageInfos); } index++; @@ -1857,72 +1770,62 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.ProductionLocations)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var productionLocations)) { - item.ProductionLocations = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries).ToArray(); + item.ProductionLocations = productionLocations.Split('|', StringSplitOptions.RemoveEmptyEntries); } - - index++; } if (HasField(query, ItemFields.ExtraIds)) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var extraIds)) { - item.ExtraIds = SplitToGuids(reader.GetString(index)); + item.ExtraIds = SplitToGuids(extraIds); } - - index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetInt(index++, out var totalBitrate)) { - item.TotalBitrate = reader.GetInt32(index); + item.TotalBitrate = totalBitrate; } - index++; - - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var extraTypeString)) { - if (Enum.TryParse(reader.GetString(index), true, out ExtraType extraType)) + if (Enum.TryParse(extraTypeString, true, out ExtraType extraType)) { item.ExtraType = extraType; } } - index++; - if (hasArtistFields) { - if (item is IHasArtist hasArtists && !reader.IsDBNull(index)) + if (item is IHasArtist hasArtists && reader.TryGetString(index, out var artists)) { - hasArtists.Artists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); + hasArtists.Artists = artists.Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; - if (item is IHasAlbumArtist hasAlbumArtists && !reader.IsDBNull(index)) + if (item is IHasAlbumArtist hasAlbumArtists && reader.TryGetString(index, out var albumArtists)) { - hasAlbumArtists.AlbumArtists = reader.GetString(index).Split('|', StringSplitOptions.RemoveEmptyEntries); + hasAlbumArtists.AlbumArtists = albumArtists.Split('|', StringSplitOptions.RemoveEmptyEntries); } index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index++, out var externalId)) { - item.ExternalId = reader.GetString(index); + item.ExternalId = externalId; } - index++; - if (HasField(query, ItemFields.SeriesPresentationUniqueKey)) { if (hasSeries != null) { - if (!reader.IsDBNull(index)) + if (reader.TryGetString(index, out var seriesPresentationUniqueKey)) { - hasSeries.SeriesPresentationUniqueKey = reader.GetString(index); + hasSeries.SeriesPresentationUniqueKey = seriesPresentationUniqueKey; } } @@ -1931,21 +1834,19 @@ namespace Emby.Server.Implementations.Data if (enableProgramAttributes) { - if (item is LiveTvProgram program && !reader.IsDBNull(index)) + if (item is LiveTvProgram program && reader.TryGetString(index, out var showId)) { - program.ShowId = reader.GetString(index); + program.ShowId = showId; } index++; } - if (!reader.IsDBNull(index)) + if (reader.TryGetGuid(index, out var ownerId)) { - item.OwnerId = reader.GetGuid(index); + item.OwnerId = ownerId.Value; } - index++; - return item; } @@ -2032,14 +1933,14 @@ namespace Emby.Server.Implementations.Data StartPositionTicks = reader.GetInt64(0) }; - if (!reader.IsDBNull(1)) + if (reader.TryGetString(1, out var chapterName)) { - chapter.Name = reader.GetString(1); + chapter.Name = chapterName; } - if (!reader.IsDBNull(2)) + if (reader.TryGetString(2, out var imagePath)) { - chapter.ImagePath = reader.GetString(2); + chapter.ImagePath = imagePath; if (!string.IsNullOrEmpty(chapter.ImagePath)) { @@ -2054,9 +1955,9 @@ namespace Emby.Server.Implementations.Data } } - if (!reader.IsDBNull(3)) + if (reader.TryReadDateTime(3, out var imageDateModified)) { - chapter.ImageDateModified = reader[3].ReadDateTime(); + chapter.ImageDateModified = imageDateModified.Value; } return chapter; @@ -3228,12 +3129,8 @@ namespace Emby.Server.Implementations.Data foreach (var row in statement.ExecuteQuery()) { var id = row.GetGuid(0); - string path = null; - if (!row.IsDBNull(1)) - { - path = row.GetString(1); - } + row.TryGetString(1, out var path); list.Add(new Tuple(id, path)); } @@ -5327,9 +5224,9 @@ AND Type = @InternalPersonType)"); { foreach (var row in statement.ExecuteQuery()) { - if (!row.IsDBNull(0)) + if (row.TryGetString(0, out var result)) { - list.Add(row.GetString(0)); + list.Add(result); } } } @@ -5603,7 +5500,7 @@ AND Type = @InternalPersonType)"); return result; } - private ItemCounts GetItemCounts(IReadOnlyList reader, int countStartColumn, string[] typesToCount) + private static ItemCounts GetItemCounts(IReadOnlyList reader, int countStartColumn, string[] typesToCount) { var counts = new ItemCounts(); @@ -5612,51 +5509,43 @@ AND Type = @InternalPersonType)"); return counts; } - var typeString = reader.IsDBNull(countStartColumn) ? null : reader.GetString(countStartColumn); - - if (string.IsNullOrWhiteSpace(typeString)) + if (!reader.TryGetString(countStartColumn, out var typeString)) { return counts; } - var allTypes = typeString.Split('|', StringSplitOptions.RemoveEmptyEntries) - .ToLookup(x => x); - - foreach (var type in allTypes) + foreach (var typeName in typeString.AsSpan().Split('|')) { - var value = type.Count(); - var typeName = type.Key; - - if (string.Equals(typeName, typeof(Series).FullName, StringComparison.OrdinalIgnoreCase)) + if (typeName.Equals(typeof(Series).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.SeriesCount = value; + counts.SeriesCount++; } - else if (string.Equals(typeName, typeof(Episode).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(Episode).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.EpisodeCount = value; + counts.EpisodeCount++; } - else if (string.Equals(typeName, typeof(Movie).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(Movie).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.MovieCount = value; + counts.MovieCount++; } - else if (string.Equals(typeName, typeof(MusicAlbum).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(MusicAlbum).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.AlbumCount = value; + counts.AlbumCount++; } - else if (string.Equals(typeName, typeof(MusicArtist).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(MusicArtist).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.ArtistCount = value; + counts.ArtistCount++; } - else if (string.Equals(typeName, typeof(Audio).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(Audio).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.SongCount = value; + counts.SongCount++; } - else if (string.Equals(typeName, typeof(Trailer).FullName, StringComparison.OrdinalIgnoreCase)) + else if (typeName.Equals(typeof(Trailer).FullName, StringComparison.OrdinalIgnoreCase)) { - counts.TrailerCount = value; + counts.TrailerCount++; } - counts.ItemCount += value; + counts.ItemCount++; } return counts; @@ -5850,19 +5739,19 @@ AND Type = @InternalPersonType)"); Name = reader.GetString(1) }; - if (!reader.IsDBNull(2)) + if (reader.TryGetString(2, out var role)) { - item.Role = reader.GetString(2); + item.Role = role; } - if (!reader.IsDBNull(3)) + if (reader.TryGetString(3, out var type)) { - item.Type = reader.GetString(3); + item.Type = type; } - if (!reader.IsDBNull(4)) + if (reader.TryGetInt(4, out var sortOrder)) { - item.SortOrder = reader.GetInt32(4); + item.SortOrder = sortOrder; } return item; @@ -6058,150 +5947,150 @@ AND Type = @InternalPersonType)"); item.Type = Enum.Parse(reader[2].ToString(), true); - if (reader[3].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(3, out var codec)) { - item.Codec = reader[3].ToString(); + item.Codec = codec; } - if (reader[4].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(4, out var language)) { - item.Language = reader[4].ToString(); + item.Language = language; } - if (reader[5].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(5, out var channelLayout)) { - item.ChannelLayout = reader[5].ToString(); + item.ChannelLayout = channelLayout; } - if (reader[6].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(6, out var profile)) { - item.Profile = reader[6].ToString(); + item.Profile = profile; } - if (reader[7].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(7, out var aspectRatio)) { - item.AspectRatio = reader[7].ToString(); + item.AspectRatio = aspectRatio; } - if (reader[8].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(8, out var path)) { - item.Path = RestorePath(reader[8].ToString()); + item.Path = RestorePath(path); } item.IsInterlaced = reader.GetBoolean(9); - if (reader[10].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(10, out var bitrate)) { - item.BitRate = reader.GetInt32(10); + item.BitRate = bitrate; } - if (reader[11].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(11, out var channels)) { - item.Channels = reader.GetInt32(11); + item.Channels = channels; } - if (reader[12].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(12, out var sampleRate)) { - item.SampleRate = reader.GetInt32(12); + item.SampleRate = sampleRate; } item.IsDefault = reader.GetBoolean(13); item.IsForced = reader.GetBoolean(14); item.IsExternal = reader.GetBoolean(15); - if (reader[16].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(16, out var width)) { - item.Width = reader.GetInt32(16); + item.Width = width; } - if (reader[17].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(17, out var height)) { - item.Height = reader.GetInt32(17); + item.Height = height; } - if (reader[18].SQLiteType != SQLiteType.Null) + if (reader.TryGetFloat(18, out var averageFrameRate)) { - item.AverageFrameRate = reader.GetFloat(18); + item.AverageFrameRate = averageFrameRate; } - if (reader[19].SQLiteType != SQLiteType.Null) + if (reader.TryGetFloat(19, out var realFrameRate)) { - item.RealFrameRate = reader.GetFloat(19); + item.RealFrameRate = realFrameRate; } - if (reader[20].SQLiteType != SQLiteType.Null) + if (reader.TryGetFloat(20, out var level)) { - item.Level = reader.GetFloat(20); + item.Level = level; } - if (reader[21].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(21, out var pixelFormat)) { - item.PixelFormat = reader[21].ToString(); + item.PixelFormat = pixelFormat; } - if (reader[22].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(22, out var bitDepth)) { - item.BitDepth = reader.GetInt32(22); + item.BitDepth = bitDepth; } - if (reader[23].SQLiteType != SQLiteType.Null) + if (reader.TryGetBoolean(23, out var isAnamorphic)) { - item.IsAnamorphic = reader.GetBoolean(23); + item.IsAnamorphic = isAnamorphic; } - if (reader[24].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(24, out var refFrames)) { - item.RefFrames = reader.GetInt32(24); + item.RefFrames = refFrames; } - if (reader[25].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(25, out var codecTag)) { - item.CodecTag = reader.GetString(25); + item.CodecTag = codecTag; } - if (reader[26].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(26, out var comment)) { - item.Comment = reader.GetString(26); + item.Comment = comment; } - if (reader[27].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(27, out var nalLengthSize)) { - item.NalLengthSize = reader.GetString(27); + item.NalLengthSize = nalLengthSize; } - if (reader[28].SQLiteType != SQLiteType.Null) + if (reader.TryGetBoolean(28, out var isAVC)) { - item.IsAVC = reader[28].ToBool(); + item.IsAVC = isAVC; } - if (reader[29].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(29, out var title)) { - item.Title = reader[29].ToString(); + item.Title = title; } - if (reader[30].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(30, out var timeBase)) { - item.TimeBase = reader[30].ToString(); + item.TimeBase = timeBase; } - if (reader[31].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(31, out var codecTimeBase)) { - item.CodecTimeBase = reader[31].ToString(); + item.CodecTimeBase = codecTimeBase; } - if (reader[32].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(32, out var colorPrimaries)) { - item.ColorPrimaries = reader[32].ToString(); + item.ColorPrimaries = colorPrimaries; } - if (reader[33].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(33, out var colorSpace)) { - item.ColorSpace = reader[33].ToString(); + item.ColorSpace = colorSpace; } - if (reader[34].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(34, out var colorTransfer)) { - item.ColorTransfer = reader[34].ToString(); + item.ColorTransfer = colorTransfer; } if (item.Type == MediaStreamType.Subtitle) @@ -6357,29 +6246,29 @@ AND Type = @InternalPersonType)"); Index = reader[1].ToInt() }; - if (reader[2].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(2, out var codec)) { - item.Codec = reader[2].ToString(); + item.Codec = codec; } - if (reader[2].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(3, out var codecTag)) { - item.CodecTag = reader[3].ToString(); + item.CodecTag = codecTag; } - if (reader[4].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(4, out var comment)) { - item.Comment = reader[4].ToString(); + item.Comment = comment; } - if (reader[6].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(5, out var fileName)) { - item.FileName = reader[5].ToString(); + item.FileName = fileName; } - if (reader[6].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(6, out var mimeType)) { - item.MimeType = reader[6].ToString(); + item.MimeType = mimeType; } return item; diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 6574db6078..479e5e846f 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -355,9 +355,9 @@ namespace Emby.Server.Implementations.Data userData.Key = reader[0].ToString(); // userData.UserId = reader[1].ReadGuidFromBlob(); - if (reader[2].SQLiteType != SQLiteType.Null) + if (reader.TryGetDouble(2, out var rating)) { - userData.Rating = reader[2].ToDouble(); + userData.Rating = rating; } userData.Played = reader[3].ToBool(); @@ -365,19 +365,19 @@ namespace Emby.Server.Implementations.Data userData.IsFavorite = reader[5].ToBool(); userData.PlaybackPositionTicks = reader[6].ToInt64(); - if (reader[7].SQLiteType != SQLiteType.Null) + if (reader.TryReadDateTime(7, out var lastPlayedDate)) { - userData.LastPlayedDate = reader[7].TryReadDateTime(); + userData.LastPlayedDate = lastPlayedDate; } - if (reader[8].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(8, out var audioStreamIndex)) { - userData.AudioStreamIndex = reader[8].ToInt(); + userData.AudioStreamIndex = audioStreamIndex; } - if (reader[9].SQLiteType != SQLiteType.Null) + if (reader.TryGetInt(9, out var subtitleStreamIndex)) { - userData.SubtitleStreamIndex = reader[9].ToInt(); + userData.SubtitleStreamIndex = subtitleStreamIndex; } return userData; diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 024404ceb0..035c5df642 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Net; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Security; @@ -215,7 +215,7 @@ namespace Emby.Server.Implementations.HttpServer.Security auth = httpReq.Request.Headers[HeaderNames.Authorization]; } - return GetAuthorization(auth); + return GetAuthorization(auth.Count > 0 ? auth[0] : null); } /// @@ -232,7 +232,7 @@ namespace Emby.Server.Implementations.HttpServer.Security auth = httpReq.Headers[HeaderNames.Authorization]; } - return GetAuthorization(auth); + return GetAuthorization(auth.Count > 0 ? auth[0] : null); } /// @@ -240,43 +240,43 @@ namespace Emby.Server.Implementations.HttpServer.Security /// /// The authorization header. /// Dictionary{System.StringSystem.String}. - private Dictionary GetAuthorization(string authorizationHeader) + private Dictionary GetAuthorization(ReadOnlySpan authorizationHeader) { if (authorizationHeader == null) { return null; } - var parts = authorizationHeader.Split(' ', 2); + var firstSpace = authorizationHeader.IndexOf(' '); - // There should be at least to parts - if (parts.Length != 2) + // There should be at least two parts + if (firstSpace == -1) { return null; } - var acceptedNames = new[] { "MediaBrowser", "Emby" }; + var name = authorizationHeader[..firstSpace]; - // It has to be a digest request - if (!acceptedNames.Contains(parts[0], StringComparer.OrdinalIgnoreCase)) + if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase) + && name.Equals("Emby", StringComparison.OrdinalIgnoreCase)) { return null; } - // Remove uptil the first space - authorizationHeader = parts[1]; - parts = authorizationHeader.Split(','); + authorizationHeader = authorizationHeader[(firstSpace + 1)..]; var result = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var item in parts) + foreach (var item in authorizationHeader.Split(',')) { - var param = item.Trim().Split('=', 2); + var trimmedItem = item.Trim(); + var firstEqualsSign = trimmedItem.IndexOf('='); - if (param.Length == 2) + if (firstEqualsSign > 0) { - var value = NormalizeValue(param[1].Trim('"')); - result[param[0]] = value; + var key = trimmedItem[..firstEqualsSign].ToString(); + var value = NormalizeValue(trimmedItem[(firstEqualsSign + 1)..].Trim('"').ToString()); + result[key] = value; } } diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 6e688693be..16050185fb 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -165,13 +165,13 @@ namespace Emby.Server.Implementations.Library.Resolvers protected void SetVideoType(Video video, VideoFileInfo videoInfo) { - var extension = Path.GetExtension(video.Path); - video.VideoType = string.Equals(extension, ".iso", StringComparison.OrdinalIgnoreCase) || - string.Equals(extension, ".img", StringComparison.OrdinalIgnoreCase) ? - VideoType.Iso : - VideoType.VideoFile; + var extension = Path.GetExtension(video.Path.AsSpan()); + video.VideoType = extension.Equals(".iso", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".img", StringComparison.OrdinalIgnoreCase) + ? VideoType.Iso + : VideoType.VideoFile; - video.IsShortcut = string.Equals(extension, ".strm", StringComparison.OrdinalIgnoreCase); + video.IsShortcut = extension.Equals(".strm", StringComparison.OrdinalIgnoreCase); video.IsPlaceHolder = videoInfo.IsStub; if (videoInfo.IsStub) @@ -193,11 +193,11 @@ namespace Emby.Server.Implementations.Library.Resolvers { if (video.VideoType == VideoType.Iso) { - if (video.Path.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1) + if (video.Path.Contains("dvd", StringComparison.OrdinalIgnoreCase)) { video.IsoType = IsoType.Dvd; } - else if (video.Path.IndexOf("bluray", StringComparison.OrdinalIgnoreCase) != -1) + else if (video.Path.Contains("bluray", StringComparison.OrdinalIgnoreCase)) { video.IsoType = IsoType.BluRay; } diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index 4bc12f44a4..ca7e748581 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -297,50 +297,49 @@ namespace Emby.Server.Implementations.Security AccessToken = reader[1].ToString() }; - if (reader[2].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(2, out var deviceId)) { - info.DeviceId = reader[2].ToString(); + info.DeviceId = deviceId; } - if (reader[3].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(3, out var appName)) { - info.AppName = reader[3].ToString(); + info.AppName = appName; } - if (reader[4].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(4, out var appVersion)) { - info.AppVersion = reader[4].ToString(); + info.AppVersion = appVersion; } - if (reader[5].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(6, out var userId)) { - info.DeviceName = reader[5].ToString(); + info.UserId = new Guid(userId); } - if (reader[6].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(7, out var userName)) { - info.UserId = new Guid(reader[6].ToString()); - } - - if (reader[7].SQLiteType != SQLiteType.Null) - { - info.UserName = reader[7].ToString(); + info.UserName = userName; } info.DateCreated = reader[8].ReadDateTime(); - if (reader[9].SQLiteType != SQLiteType.Null) + if (reader.TryReadDateTime(9, out var dateLastActivity)) { - info.DateLastActivity = reader[9].ReadDateTime(); + info.DateLastActivity = dateLastActivity.Value; } else { info.DateLastActivity = info.DateCreated; } - if (reader[10].SQLiteType != SQLiteType.Null) + if (reader.TryGetString(10, out var customName)) { - info.DeviceName = reader[10].ToString(); + info.DeviceName = customName; + } + else if (reader.TryGetString(5, out var deviceName)) + { + info.DeviceName = deviceName; } return info; @@ -361,9 +360,9 @@ namespace Emby.Server.Implementations.Security foreach (var row in statement.ExecuteQuery()) { - if (row[0].SQLiteType != SQLiteType.Null) + if (row.TryGetString(0, out var customName)) { - result.CustomName = row[0].ToString(); + result.CustomName = customName; } } diff --git a/Jellyfin.sln b/Jellyfin.sln index 8626a4b1ba..ffcec0439b 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -81,6 +81,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Providers.Tests", "tests\Jellyfin.Providers.Tests\Jellyfin.Providers.Tests.csproj", "{A964008C-2136-4716-B6CB-B3426C22320A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -223,6 +225,14 @@ Global {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.Build.0 = Debug|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.ActiveCfg = Release|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.Build.0 = Release|Any CPU + {50928738-D268-43A3-BACA-3513D9AA6B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50928738-D268-43A3-BACA-3513D9AA6B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50928738-D268-43A3-BACA-3513D9AA6B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50928738-D268-43A3-BACA-3513D9AA6B8E}.Release|Any CPU.Build.0 = Release|Any CPU + {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A964008C-2136-4716-B6CB-B3426C22320A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A964008C-2136-4716-B6CB-B3426C22320A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -240,6 +250,7 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {A964008C-2136-4716-B6CB-B3426C22320A} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/MediaBrowser.Common/Extensions/EnumerableExtensions.cs b/MediaBrowser.Common/Extensions/EnumerableExtensions.cs new file mode 100644 index 0000000000..2b8a6c395b --- /dev/null +++ b/MediaBrowser.Common/Extensions/EnumerableExtensions.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; + +namespace MediaBrowser.Common.Extensions +{ + /// + /// Static extensions for the interface. + /// + public static class EnumerableExtensions + { + /// + /// Determines whether the value is contained in the source collection. + /// + /// An instance of the interface. + /// The value to look for in the collection. + /// The string comparison. + /// A value indicating whether the value is contained in the collection. + /// The source is null. + public static bool Contains(this IEnumerable source, ReadOnlySpan value, StringComparison stringComparison) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (source is IList list) + { + int len = list.Count; + for (int i = 0; i < len; i++) + { + if (value.Equals(list[i], stringComparison)) + { + return true; + } + } + + return false; + } + + foreach (string element in source) + { + if (value.Equals(element, stringComparison)) + { + return true; + } + } + + return false; + } + } +} diff --git a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs index 7ad8c24e89..31475e22f4 100644 --- a/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs +++ b/MediaBrowser.LocalMetadata/Images/LocalImageProvider.cs @@ -466,7 +466,7 @@ namespace MediaBrowser.LocalMetadata.Images return added; } - private bool AddImage(IEnumerable files, List images, string name, ImageType type) + private bool AddImage(List files, List images, string name, ImageType type) { var image = GetImage(files, name); @@ -484,9 +484,20 @@ namespace MediaBrowser.LocalMetadata.Images return false; } - private FileSystemMetadata? GetImage(IEnumerable files, string name) + private static FileSystemMetadata? GetImage(IReadOnlyList files, string name) { - return files.FirstOrDefault(i => !i.IsDirectory && string.Equals(name, _fileSystem.GetFileNameWithoutExtension(i), StringComparison.OrdinalIgnoreCase) && i.Length > 0); + for (var i = 0; i < files.Count; i++) + { + var file = files[i]; + if (!file.IsDirectory + && file.Length > 0 + && Path.GetFileNameWithoutExtension(file.FullName.AsSpan()).Equals(name, StringComparison.OrdinalIgnoreCase)) + { + return file; + } + } + + return null; } } } diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs index e9f999c6d0..186c777473 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs @@ -15,17 +15,6 @@ namespace MediaBrowser.Providers.MediaInfo { private readonly ILocalizationManager _localization; - private static readonly HashSet SubtitleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) - { - ".srt", - ".ssa", - ".ass", - ".sub", - ".smi", - ".sami", - ".vtt" - }; - public SubtitleResolver(ILocalizationManager localization) { _localization = localization; @@ -88,6 +77,115 @@ namespace MediaBrowser.Providers.MediaInfo return list; } + public void AddExternalSubtitleStreams( + List streams, + string videoPath, + int startIndex, + string[] files) + { + var videoFileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(videoPath); + + foreach (var fullName in files) + { + var extension = Path.GetExtension(fullName.AsSpan()); + if (!IsSubtitleExtension(extension)) + { + continue; + } + + var fileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(fullName); + + MediaStream mediaStream; + + // The subtitle filename must either be equal to the video filename or start with the video filename followed by a dot + if (videoFileNameWithoutExtension.Equals(fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)) + { + mediaStream = new MediaStream + { + Index = startIndex++, + Type = MediaStreamType.Subtitle, + IsExternal = true, + Path = fullName + }; + } + else if (fileNameWithoutExtension.Length >= videoFileNameWithoutExtension.Length + && fileNameWithoutExtension[videoFileNameWithoutExtension.Length] == '.' + && fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)) + { + var isForced = fullName.Contains(".forced.", StringComparison.OrdinalIgnoreCase) + || fullName.Contains(".foreign.", StringComparison.OrdinalIgnoreCase); + + var isDefault = fullName.Contains(".default.", StringComparison.OrdinalIgnoreCase); + + // Support xbmc naming conventions - 300.spanish.srt + var languageSpan = fileNameWithoutExtension; + while (languageSpan.Length > 0) + { + var lastDot = languageSpan.LastIndexOf('.'); + var currentSlice = languageSpan[lastDot..]; + if (currentSlice.Equals(".default", StringComparison.OrdinalIgnoreCase) + || currentSlice.Equals(".forced", StringComparison.OrdinalIgnoreCase) + || currentSlice.Equals(".foreign", StringComparison.OrdinalIgnoreCase)) + { + languageSpan = languageSpan[..lastDot]; + continue; + } + + languageSpan = languageSpan[(lastDot + 1)..]; + break; + } + + var language = languageSpan.ToString(); + // Try to translate to three character code + // Be flexible and check against both the full and three character versions + var culture = _localization.FindLanguageInfo(language); + + if (culture != null) + { + language = culture.ThreeLetterISOLanguageName; + } + + mediaStream = new MediaStream + { + Index = startIndex++, + Type = MediaStreamType.Subtitle, + IsExternal = true, + Path = fullName, + Language = language, + IsForced = isForced, + IsDefault = isDefault + }; + } + else + { + continue; + } + + mediaStream.Codec = extension.TrimStart('.').ToString().ToLowerInvariant(); + + streams.Add(mediaStream); + } + } + + private static bool IsSubtitleExtension(ReadOnlySpan extension) + { + return extension.Equals(".srt", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".ssa", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".ass", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".sub", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".vtt", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".smi", StringComparison.OrdinalIgnoreCase) + || extension.Equals(".sami", StringComparison.OrdinalIgnoreCase); + } + + private static ReadOnlySpan NormalizeFilenameForSubtitleComparison(string filename) + { + // Try to account for sloppy file naming + filename = filename.Replace("_", string.Empty, StringComparison.Ordinal); + filename = filename.Replace(" ", string.Empty, StringComparison.Ordinal); + return Path.GetFileNameWithoutExtension(filename.AsSpan()); + } + private void AddExternalSubtitleStreams( List streams, string folder, @@ -100,104 +198,5 @@ namespace MediaBrowser.Providers.MediaInfo AddExternalSubtitleStreams(streams, videoPath, startIndex, files); } - - public void AddExternalSubtitleStreams( - List streams, - string videoPath, - int startIndex, - string[] files) - { - var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(videoPath); - videoFileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(videoFileNameWithoutExtension); - - foreach (var fullName in files) - { - var extension = Path.GetExtension(fullName); - - if (!SubtitleExtensions.Contains(extension)) - { - continue; - } - - var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName); - fileNameWithoutExtension = NormalizeFilenameForSubtitleComparison(fileNameWithoutExtension); - - if (!string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase) && - !fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - var codec = Path.GetExtension(fullName).ToLowerInvariant().TrimStart('.'); - - if (string.Equals(codec, "txt", StringComparison.OrdinalIgnoreCase)) - { - codec = "srt"; - } - - // If the subtitle file matches the video file name - if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)) - { - streams.Add(new MediaStream - { - Index = startIndex++, - Type = MediaStreamType.Subtitle, - IsExternal = true, - Path = fullName, - Codec = codec - }); - } - else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase)) - { - var isForced = fullName.IndexOf(".forced.", StringComparison.OrdinalIgnoreCase) != -1 || - fullName.IndexOf(".foreign.", StringComparison.OrdinalIgnoreCase) != -1; - - var isDefault = fullName.IndexOf(".default.", StringComparison.OrdinalIgnoreCase) != -1; - - // Support xbmc naming conventions - 300.spanish.srt - var language = fileNameWithoutExtension - .Replace(".forced", string.Empty, StringComparison.OrdinalIgnoreCase) - .Replace(".foreign", string.Empty, StringComparison.OrdinalIgnoreCase) - .Replace(".default", string.Empty, StringComparison.OrdinalIgnoreCase) - .Split('.') - .LastOrDefault(); - - // Try to translate to three character code - // Be flexible and check against both the full and three character versions - var culture = _localization.FindLanguageInfo(language); - - if (culture != null) - { - language = culture.ThreeLetterISOLanguageName; - } - - streams.Add(new MediaStream - { - Index = startIndex++, - Type = MediaStreamType.Subtitle, - IsExternal = true, - Path = fullName, - Codec = codec, - Language = language, - IsForced = isForced, - IsDefault = isDefault - }); - } - } - } - - private string NormalizeFilenameForSubtitleComparison(string filename) - { - // Try to account for sloppy file naming - filename = filename.Replace("_", string.Empty, StringComparison.Ordinal); - filename = filename.Replace(" ", string.Empty, StringComparison.Ordinal); - - // can't normalize this due to languages such as pt-br - // filename = filename.Replace("-", string.Empty); - - // filename = filename.Replace(".", string.Empty); - - return filename; - } } } diff --git a/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj new file mode 100644 index 0000000000..670289f376 --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj @@ -0,0 +1,37 @@ + + + + net5.0 + false + true + enable + AllEnabledByDefault + ../jellyfin-tests.ruleset + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs new file mode 100644 index 0000000000..80b0bc3702 --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs @@ -0,0 +1,96 @@ +#pragma warning disable CA1002 // Do not expose generic lists + +using System.Collections.Generic; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Providers.MediaInfo; +using Moq; +using Xunit; + +namespace Jellyfin.Providers.Tests.MediaInfo +{ + public class SubtitleResolverTests + { + public static IEnumerable AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles_TestData() + { + var index = 0; + yield return new object[] + { + new List(), + "/video/My.Video.mkv", + index, + new[] + { + "/video/My.Video.mp3", + "/video/My.Video.png", + "/video/My.Video.srt", + "/video/My.Video.txt", + "/video/My.Video.vtt", + "/video/My.Video.ass", + "/video/My.Video.sub", + "/video/My.Video.ssa", + "/video/My.Video.smi", + "/video/My.Video.sami", + "/video/My.Video.en.srt", + "/video/My.Video.default.en.srt", + "/video/My.Video.default.forced.en.srt", + "/video/My.Video.en.default.forced.srt", + "/video/My.Video.With.Additional.Garbage.en.srt", + "/video/My.Video With Additional Garbage.srt" + }, + new List + { + CreateMediaStream("/video/My.Video.srt", "srt", null, index++), + CreateMediaStream("/video/My.Video.vtt", "vtt", null, index++), + CreateMediaStream("/video/My.Video.ass", "ass", null, index++), + CreateMediaStream("/video/My.Video.sub", "sub", null, index++), + CreateMediaStream("/video/My.Video.ssa", "ssa", null, index++), + CreateMediaStream("/video/My.Video.smi", "smi", null, index++), + CreateMediaStream("/video/My.Video.sami", "sami", null, index++), + CreateMediaStream("/video/My.Video.en.srt", "srt", "en", index++), + CreateMediaStream("/video/My.Video.default.en.srt", "srt", "en", index++, isDefault: true), + CreateMediaStream("/video/My.Video.default.forced.en.srt", "srt", "en", index++, isForced: true, isDefault: true), + CreateMediaStream("/video/My.Video.en.default.forced.srt", "srt", "en", index++, isForced: true, isDefault: true), + CreateMediaStream("/video/My.Video.With.Additional.Garbage.en.srt", "srt", "en", index), + } + }; + } + + [Theory] + [MemberData(nameof(AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles_TestData))] + public void AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles(List streams, string videoPath, int startIndex, string[] files, List expectedResult) + { + new SubtitleResolver(Mock.Of()).AddExternalSubtitleStreams(streams, videoPath, startIndex, files); + + Assert.Equal(expectedResult.Count, streams.Count); + for (var i = 0; i < expectedResult.Count; i++) + { + var expected = expectedResult[i]; + var actual = streams[i]; + + Assert.Equal(expected.Index, actual.Index); + Assert.Equal(expected.Type, actual.Type); + Assert.Equal(expected.IsExternal, actual.IsExternal); + Assert.Equal(expected.Path, actual.Path); + Assert.Equal(expected.IsDefault, actual.IsDefault); + Assert.Equal(expected.IsForced, actual.IsForced); + Assert.Equal(expected.Language, actual.Language); + } + } + + private static MediaStream CreateMediaStream(string path, string codec, string? language, int index, bool isForced = false, bool isDefault = false) + { + return new () + { + Index = index, + Codec = codec, + Type = MediaStreamType.Subtitle, + IsExternal = true, + Path = path, + IsDefault = isDefault, + IsForced = isForced, + Language = language + }; + } + } +} From eaafbdd623feed3125c2ce7e3c44ec7b26b42a81 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 16 May 2021 14:52:56 +0200 Subject: [PATCH 1662/1930] Remove some leftover junk from a project that isn't in the sln --- Jellyfin.sln | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Jellyfin.sln b/Jellyfin.sln index ffcec0439b..9fbd9d266e 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -225,10 +225,6 @@ Global {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.Build.0 = Debug|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.ActiveCfg = Release|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.Build.0 = Release|Any CPU - {50928738-D268-43A3-BACA-3513D9AA6B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {50928738-D268-43A3-BACA-3513D9AA6B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {50928738-D268-43A3-BACA-3513D9AA6B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {50928738-D268-43A3-BACA-3513D9AA6B8E}.Release|Any CPU.Build.0 = Release|Any CPU {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A964008C-2136-4716-B6CB-B3426C22320A}.Debug|Any CPU.Build.0 = Debug|Any CPU {A964008C-2136-4716-B6CB-B3426C22320A}.Release|Any CPU.ActiveCfg = Release|Any CPU From 415e8fc0f3b7f214fbcbdc8fa39a863b06690243 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 16 May 2021 14:54:36 +0200 Subject: [PATCH 1663/1930] Forward --- Emby.Naming/Emby.Naming.csproj | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index a93ddbcb8a..3224ff4129 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -23,12 +23,12 @@ - + - - + + From 652909e8a57075866e56c270852e34714bf06c06 Mon Sep 17 00:00:00 2001 From: Claus Vium Date: Sun, 16 May 2021 15:27:31 +0200 Subject: [PATCH 1664/1930] Update Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs Co-authored-by: Cody Robibero --- .../HttpServer/Security/AuthorizationContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index 035c5df642..fbf9254d16 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -258,7 +258,7 @@ namespace Emby.Server.Implementations.HttpServer.Security var name = authorizationHeader[..firstSpace]; if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase) - && name.Equals("Emby", StringComparison.OrdinalIgnoreCase)) + && !name.Equals("Emby", StringComparison.OrdinalIgnoreCase)) { return null; } From be4aeb5c2cb7fa6e05810aa1d0c935b5166fb64a Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 16 May 2021 19:05:56 +0200 Subject: [PATCH 1665/1930] Rename SQL extension methods --- .../Data/SqliteExtensions.cs | 8 ++-- .../Data/SqliteItemRepository.cs | 44 +++++++++---------- .../Data/SqliteUserDataRepository.cs | 4 +- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index db30102074..51a53c6cbe 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetInt(this IReadOnlyList reader, int index, out int? result) + public static bool TryGetInt32(this IReadOnlyList reader, int index, [NotNullWhen(true)] out int? result) { result = null; var item = reader[index]; @@ -189,7 +189,7 @@ namespace Emby.Server.Implementations.Data return result[index].ToInt64(); } - public static bool TryGetLong(this IReadOnlyList reader, int index, out long? result) + public static bool TryGetInt64(this IReadOnlyList reader, int index, [NotNullWhen(true)] out long? result) { result = null; var item = reader[index]; @@ -202,7 +202,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetFloat(this IReadOnlyList reader, int index, out float? result) + public static bool TryGetSingle(this IReadOnlyList reader, int index, [NotNullWhen(true)] out float? result) { result = null; var item = reader[index]; @@ -215,7 +215,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetDouble(this IReadOnlyList reader, int index, out double? result) + public static bool TryGetDouble(this IReadOnlyList reader, int index, [NotNullWhen(true)] out double? result) { result = null; var item = reader[index]; diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 53c9a4cad4..996cdf1337 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1390,7 +1390,7 @@ namespace Emby.Server.Implementations.Data } } - if (reader.TryGetFloat(index++, out var communityRating)) + if (reader.TryGetSingle(index++, out var communityRating)) { item.CommunityRating = communityRating; } @@ -1403,7 +1403,7 @@ namespace Emby.Server.Implementations.Data } } - if (reader.TryGetInt(index++, out var indexNumber)) + if (reader.TryGetInt32(index++, out var indexNumber)) { item.IndexNumber = indexNumber; } @@ -1428,7 +1428,7 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.Width)) { - if (reader.TryGetInt(index++, out var width)) + if (reader.TryGetInt32(index++, out var width)) { item.Width = width.Value; } @@ -1436,7 +1436,7 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.Height)) { - if (reader.TryGetInt(index++, out var height)) + if (reader.TryGetInt32(index++, out var height)) { item.Height = height.Value; } @@ -1473,12 +1473,12 @@ namespace Emby.Server.Implementations.Data } } - if (reader.TryGetInt(index++, out var parentIndexNumber)) + if (reader.TryGetInt32(index++, out var parentIndexNumber)) { item.ParentIndexNumber = parentIndexNumber; } - if (reader.TryGetInt(index++, out var productionYear)) + if (reader.TryGetInt32(index++, out var productionYear)) { item.ProductionYear = productionYear; } @@ -1496,12 +1496,12 @@ namespace Emby.Server.Implementations.Data } } - if (reader.TryGetLong(index++, out var runTimeTicks)) + if (reader.TryGetInt64(index++, out var runTimeTicks)) { item.RunTimeTicks = runTimeTicks; } - if (reader.TryGetLong(index++, out var size)) + if (reader.TryGetInt64(index++, out var size)) { item.Size = size; } @@ -1662,7 +1662,7 @@ namespace Emby.Server.Implementations.Data item.Album = album; } - if (reader.TryGetFloat(index++, out var criticRating)) + if (reader.TryGetSingle(index++, out var criticRating)) { item.CriticRating = criticRating; } @@ -1729,7 +1729,7 @@ namespace Emby.Server.Implementations.Data if (HasField(query, ItemFields.InheritedParentalRatingValue)) { - if (reader.TryGetInt(index++, out var parentalRating)) + if (reader.TryGetInt32(index++, out var parentalRating)) { item.InheritedParentalRatingValue = parentalRating.Value; } @@ -1784,7 +1784,7 @@ namespace Emby.Server.Implementations.Data } } - if (reader.TryGetInt(index++, out var totalBitrate)) + if (reader.TryGetInt32(index++, out var totalBitrate)) { item.TotalBitrate = totalBitrate; } @@ -5749,7 +5749,7 @@ AND Type = @InternalPersonType)"); item.Type = type; } - if (reader.TryGetInt(4, out var sortOrder)) + if (reader.TryGetInt32(4, out var sortOrder)) { item.SortOrder = sortOrder; } @@ -5979,17 +5979,17 @@ AND Type = @InternalPersonType)"); item.IsInterlaced = reader.GetBoolean(9); - if (reader.TryGetInt(10, out var bitrate)) + if (reader.TryGetInt32(10, out var bitrate)) { item.BitRate = bitrate; } - if (reader.TryGetInt(11, out var channels)) + if (reader.TryGetInt32(11, out var channels)) { item.Channels = channels; } - if (reader.TryGetInt(12, out var sampleRate)) + if (reader.TryGetInt32(12, out var sampleRate)) { item.SampleRate = sampleRate; } @@ -5998,27 +5998,27 @@ AND Type = @InternalPersonType)"); item.IsForced = reader.GetBoolean(14); item.IsExternal = reader.GetBoolean(15); - if (reader.TryGetInt(16, out var width)) + if (reader.TryGetInt32(16, out var width)) { item.Width = width; } - if (reader.TryGetInt(17, out var height)) + if (reader.TryGetInt32(17, out var height)) { item.Height = height; } - if (reader.TryGetFloat(18, out var averageFrameRate)) + if (reader.TryGetSingle(18, out var averageFrameRate)) { item.AverageFrameRate = averageFrameRate; } - if (reader.TryGetFloat(19, out var realFrameRate)) + if (reader.TryGetSingle(19, out var realFrameRate)) { item.RealFrameRate = realFrameRate; } - if (reader.TryGetFloat(20, out var level)) + if (reader.TryGetSingle(20, out var level)) { item.Level = level; } @@ -6028,7 +6028,7 @@ AND Type = @InternalPersonType)"); item.PixelFormat = pixelFormat; } - if (reader.TryGetInt(22, out var bitDepth)) + if (reader.TryGetInt32(22, out var bitDepth)) { item.BitDepth = bitDepth; } @@ -6038,7 +6038,7 @@ AND Type = @InternalPersonType)"); item.IsAnamorphic = isAnamorphic; } - if (reader.TryGetInt(24, out var refFrames)) + if (reader.TryGetInt32(24, out var refFrames)) { item.RefFrames = refFrames; } diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 479e5e846f..e0ebd0a6cf 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -370,12 +370,12 @@ namespace Emby.Server.Implementations.Data userData.LastPlayedDate = lastPlayedDate; } - if (reader.TryGetInt(8, out var audioStreamIndex)) + if (reader.TryGetInt32(8, out var audioStreamIndex)) { userData.AudioStreamIndex = audioStreamIndex; } - if (reader.TryGetInt(9, out var subtitleStreamIndex)) + if (reader.TryGetInt32(9, out var subtitleStreamIndex)) { userData.SubtitleStreamIndex = subtitleStreamIndex; } From 81ac11828bbf9310a507af034b0d749323db3688 Mon Sep 17 00:00:00 2001 From: cvium Date: Sun, 16 May 2021 20:16:47 +0200 Subject: [PATCH 1666/1930] Fix ArrayIndexOutOfBounds --- MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs index 186c777473..b086ef07bb 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleResolver.cs @@ -108,7 +108,7 @@ namespace MediaBrowser.Providers.MediaInfo Path = fullName }; } - else if (fileNameWithoutExtension.Length >= videoFileNameWithoutExtension.Length + else if (fileNameWithoutExtension.Length > videoFileNameWithoutExtension.Length && fileNameWithoutExtension[videoFileNameWithoutExtension.Length] == '.' && fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)) { From 96e05e5b669e0d275b98bebfd9dd422dcc8f7103 Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Mon, 17 May 2021 12:55:27 +0200 Subject: [PATCH 1667/1930] Add tests for NoralizeLanguage --- Jellyfin.sln | 7 +++++ .../Tmdb/People/TmdbPersonImageProvider.cs | 2 +- .../Plugins/Tmdb/TmdbUtils.cs | 2 +- .../Jellyfin.Providers.Tests.csproj | 30 +++++++++++++++++++ .../Tmdb/TmdbUtilsTests.cs | 27 +++++++++++++++++ 5 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj create mode 100644 tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs diff --git a/Jellyfin.sln b/Jellyfin.sln index 8626a4b1ba..bfb43a23d0 100644 --- a/Jellyfin.sln +++ b/Jellyfin.sln @@ -81,6 +81,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Tests", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Server.Integration.Tests", "tests\Jellyfin.Server.Integration.Tests\Jellyfin.Server.Integration.Tests.csproj", "{68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Providers.Tests", "tests\Jellyfin.Providers.Tests\Jellyfin.Providers.Tests.csproj", "{CE21845F-74AD-42F6-B7BA-90506E6CD09E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -223,6 +225,10 @@ Global {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Debug|Any CPU.Build.0 = Debug|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.ActiveCfg = Release|Any CPU {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E}.Release|Any CPU.Build.0 = Release|Any CPU + {CE21845F-74AD-42F6-B7BA-90506E6CD09E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE21845F-74AD-42F6-B7BA-90506E6CD09E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE21845F-74AD-42F6-B7BA-90506E6CD09E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE21845F-74AD-42F6-B7BA-90506E6CD09E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -240,6 +246,7 @@ Global {42816EA8-4511-4CBF-A9C7-7791D5DDDAE6} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {3ADBCD8C-C0F2-4956-8FDC-35D686B74CF9} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} {68B0B823-A5AC-4E8B-82EA-965AAC7BF76E} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} + {CE21845F-74AD-42F6-B7BA-90506E6CD09E} = {FBBB5129-006E-4AD7-BAD5-8B7CA1D10ED6} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3448830C-EBDC-426C-85CD-7BBB9651A7FE} diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index d523d0315d..99a43966f3 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -47,8 +47,8 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) { - var language = item.GetPreferredMetadataLanguage(); var person = (Person)item; + var language = item.GetPreferredMetadataLanguage(); if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 7c64035fe4..b713736a0f 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -149,7 +149,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb if (parts.Length == 2) { // TMDB doesn't support Switzerland (de-CH, it-CH or fr-CH) so use the language (de, it or fr) without country code - if (string.Equals(parts[1], "ch", StringComparison.Ordinal)) + if (string.Equals(parts[1], "CH", StringComparison.OrdinalIgnoreCase)) { return parts[0]; } diff --git a/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj new file mode 100644 index 0000000000..2d8174b880 --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Jellyfin.Providers.Tests.csproj @@ -0,0 +1,30 @@ + + + + net5.0 + false + true + enable + AllEnabledByDefault + ../jellyfin-tests.ruleset + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs new file mode 100644 index 0000000000..f6a7c676f4 --- /dev/null +++ b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs @@ -0,0 +1,27 @@ +using MediaBrowser.Providers.Plugins.Tmdb; +using Xunit; + +namespace Jellyfin.Providers.Tests.Tmdb +{ + public static class TmdbUtilsTests + { + [Theory] + [InlineData("de", "de")] + [InlineData("En", "En")] + [InlineData("de-de", "de-DE")] + [InlineData("en-US", "en-US")] + [InlineData("de-CH", "de")] + public static void NormalizeLanguage_Valid_Success(string input, string expected) + { + Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input)); + } + + [Theory] + [InlineData(null, null)] + [InlineData("", "")] + public static void NormalizeLanguage_Invalid_Equal(string? input, string? expected) + { + Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input!)); + } + } +} From 0cb69e28b906947c2daf9dfd7b5e213bea9e05b9 Mon Sep 17 00:00:00 2001 From: siankatabg Date: Sun, 16 May 2021 19:23:07 +0000 Subject: [PATCH 1668/1930] Translated using Weblate (Bulgarian) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bg/ --- Emby.Server.Implementations/Localization/Core/bg-BG.json | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/bg-BG.json b/Emby.Server.Implementations/Localization/Core/bg-BG.json index 9db3b50d91..bc25531d30 100644 --- a/Emby.Server.Implementations/Localization/Core/bg-BG.json +++ b/Emby.Server.Implementations/Localization/Core/bg-BG.json @@ -39,7 +39,7 @@ "MixedContent": "Смесено съдържание", "Movies": "Филми", "Music": "Музика", - "MusicVideos": "Музикални клипове", + "MusicVideos": "Музикални видеа", "NameInstallFailed": "{0} не можа да се инсталира", "NameSeasonNumber": "Сезон {0}", "NameSeasonUnknown": "Неразпознат сезон", @@ -62,7 +62,7 @@ "NotificationOptionVideoPlaybackStopped": "Възпроизвеждането на видео е спряно", "Photos": "Снимки", "Playlists": "Списъци", - "Plugin": "Приставка", + "Plugin": "Добавка", "PluginInstalledWithName": "{0} е инсталиранa", "PluginUninstalledWithName": "{0} е деинсталиранa", "PluginUpdatedWithName": "{0} е обновенa", @@ -116,5 +116,7 @@ "TasksMaintenanceCategory": "Поддръжка", "Undefined": "Неопределено", "Forced": "Принудително", - "Default": "По подразбиране" + "Default": "По подразбиране", + "TaskCleanActivityLogDescription": "Изтрива записите в дневника с активност по стари от конфигурираната възраст.", + "TaskCleanActivityLog": "Изчисти дневника с активност" } From 48bb3383521f8cfea968981d3241ed6d355b89cc Mon Sep 17 00:00:00 2001 From: BaronGreenback Date: Mon, 17 May 2021 23:34:50 +0100 Subject: [PATCH 1669/1930] Enable child items to be returned if a musicAlbum --- MediaBrowser.Controller/Entities/Folder.cs | 25 ++++++++++++++++--- .../Entities/InternalItemsQuery.cs | 5 ++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index cac5026f70..c907e09eb3 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -939,7 +939,13 @@ namespace MediaBrowser.Controller.Entities } else { - items = GetChildren(user, true).Where(filter); + // need to pass this param to the children. + var childQuery = new InternalItemsQuery + { + DisplayAlbumFolders = query.DisplayAlbumFolders + }; + + items = GetChildren(user, true, childQuery).Where(filter); } return PostFilterAndSort(items, query, true); @@ -1275,10 +1281,23 @@ namespace MediaBrowser.Controller.Entities /// /// Adds the children to list. /// - /// true if XXXX, false otherwise private void AddChildren(User user, bool includeLinkedChildren, Dictionary result, bool recursive, InternalItemsQuery query) { - foreach (var child in GetEligibleChildrenForRecursiveChildren(user)) + // If Query.AlbumFolders is set, then enforce the format as per the db in that it permits sub-folders in music albums. + IEnumerable children = null; + if ((query?.DisplayAlbumFolders ?? false) && (this is MusicAlbum)) + { + children = Children; + query = null; + } + + // If there are not sub-folders, proceed as normal. + if (children == null) + { + children = GetEligibleChildrenForRecursiveChildren(user); + } + + foreach (var child in children) { bool? isVisibleToUser = null; diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 270217356f..d2716117bf 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -265,6 +265,11 @@ namespace MediaBrowser.Controller.Entities public bool? IsDeadPerson { get; set; } + /// + /// Gets or sets a value indicating whether album sub-folders should be returned if they exist. + /// + public bool? DisplayAlbumFolders { get; set; } + public InternalItemsQuery() { AlbumArtistIds = Array.Empty(); From be17028e22c6fbb1ce71a8aa9ece9b8ebc9aac3d Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 17 May 2021 18:34:44 -0600 Subject: [PATCH 1670/1930] Remove erroneous newline --- deployment/Dockerfile.debian.amd64 | 3 +-- deployment/Dockerfile.debian.arm64 | 3 +-- deployment/Dockerfile.debian.armhf | 3 +-- deployment/Dockerfile.linux.amd64 | 3 +-- deployment/Dockerfile.linux.amd64-musl | 3 +-- deployment/Dockerfile.linux.arm64 | 3 +-- deployment/Dockerfile.linux.armhf | 3 +-- deployment/Dockerfile.macos | 3 +-- deployment/Dockerfile.portable | 3 +-- deployment/Dockerfile.ubuntu.amd64 | 3 +-- deployment/Dockerfile.ubuntu.arm64 | 3 +-- deployment/Dockerfile.ubuntu.armhf | 3 +-- deployment/Dockerfile.windows.amd64 | 3 +-- 13 files changed, 13 insertions(+), 26 deletions(-) diff --git a/deployment/Dockerfile.debian.amd64 b/deployment/Dockerfile.debian.amd64 index 99adf7e1c3..0923645007 100644 --- a/deployment/Dockerfile.debian.amd64 +++ b/deployment/Dockerfile.debian.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.arm64 b/deployment/Dockerfile.debian.arm64 index 4e10a12f22..eef272d5be 100644 --- a/deployment/Dockerfile.debian.arm64 +++ b/deployment/Dockerfile.debian.arm64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.debian.armhf b/deployment/Dockerfile.debian.armhf index 17cd01d3e1..154481d64a 100644 --- a/deployment/Dockerfile.debian.armhf +++ b/deployment/Dockerfile.debian.armhf @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64 b/deployment/Dockerfile.linux.amd64 index 4e5d6486f9..171ebe3728 100644 --- a/deployment/Dockerfile.linux.amd64 +++ b/deployment/Dockerfile.linux.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.amd64-musl b/deployment/Dockerfile.linux.amd64-musl index 3dbe00a581..a0a5f69235 100644 --- a/deployment/Dockerfile.linux.amd64-musl +++ b/deployment/Dockerfile.linux.amd64-musl @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.arm64 b/deployment/Dockerfile.linux.arm64 index 0e17c0c4a4..ae59802cd4 100644 --- a/deployment/Dockerfile.linux.arm64 +++ b/deployment/Dockerfile.linux.arm64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.linux.armhf b/deployment/Dockerfile.linux.armhf index 7df4e51b5f..236b35ce5e 100644 --- a/deployment/Dockerfile.linux.armhf +++ b/deployment/Dockerfile.linux.armhf @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.macos b/deployment/Dockerfile.macos index e3479ae9c2..2e80d4a6ec 100644 --- a/deployment/Dockerfile.macos +++ b/deployment/Dockerfile.macos @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.portable b/deployment/Dockerfile.portable index f1774839a8..852a6b553c 100644 --- a/deployment/Dockerfile.portable +++ b/deployment/Dockerfile.portable @@ -15,8 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.amd64 b/deployment/Dockerfile.ubuntu.amd64 index f723c4cdd1..bffeb7307e 100644 --- a/deployment/Dockerfile.ubuntu.amd64 +++ b/deployment/Dockerfile.ubuntu.amd64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.arm64 b/deployment/Dockerfile.ubuntu.arm64 index a810844c0c..e90da4636b 100644 --- a/deployment/Dockerfile.ubuntu.arm64 +++ b/deployment/Dockerfile.ubuntu.arm64 @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.ubuntu.armhf b/deployment/Dockerfile.ubuntu.armhf index 3838bab828..aae262ee61 100644 --- a/deployment/Dockerfile.ubuntu.armhf +++ b/deployment/Dockerfile.ubuntu.armhf @@ -16,8 +16,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet diff --git a/deployment/Dockerfile.windows.amd64 b/deployment/Dockerfile.windows.amd64 index 007d2648b2..c847b1621d 100644 --- a/deployment/Dockerfile.windows.amd64 +++ b/deployment/Dockerfile.windows.amd64 @@ -15,8 +15,7 @@ RUN apt-get update \ # Install dotnet repository # https://dotnet.microsoft.com/download/linux-package-manager/debian9/sdk-current -RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz - -O dotnet-sdk.tar.gz \ +RUN wget https://download.visualstudio.microsoft.com/download/pr/ef13f9da-46dc-4de9-a05e-5a4c20574189/be95913ebf1fb6c66833ca40060d3f65/dotnet-sdk-5.0.203-linux-x64.tar.gz -O dotnet-sdk.tar.gz \ && mkdir -p dotnet-sdk \ && tar -xzf dotnet-sdk.tar.gz -C dotnet-sdk \ && ln -s $( pwd )/dotnet-sdk/dotnet /usr/bin/dotnet From 7a17de84d9eac292547db5e78516f692f48f97fd Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 17 May 2021 21:35:58 -0400 Subject: [PATCH 1671/1930] Add optional to nextUpDateCutoff help text --- Jellyfin.Api/Controllers/TvShowsController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 5e90e37f39..dc2f7d1918 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -65,7 +65,7 @@ namespace Jellyfin.Api.Controllers /// Optional. The max number of images to return, per image type. /// Optional. The image types to include in the output. /// Optional. Include user data. - /// Starting date of shows to show in Next Up section. + /// Optional. Starting date of shows to show in Next Up section. /// Whether to enable the total records count. Defaults to true. /// Whether to disable sending the first episode in a series as next up. /// A with the next up episodes. From 2b321d8b89bda1da80f6630a05f7d87fc6c747dd Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Tue, 18 May 2021 12:23:26 +0200 Subject: [PATCH 1672/1930] Enable nullable for InternalItemsQuery --- .../Data/SqliteItemRepository.cs | 4 +- .../Entities/InternalItemsQuery.cs | 87 +++++++++---------- 2 files changed, 44 insertions(+), 47 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 835eb06924..4ae7a842c6 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -4427,7 +4427,7 @@ namespace Emby.Server.Implementations.Data whereClauses.Add(string.Join(" AND ", excludeIds)); } - if (query.ExcludeProviderIds.Count > 0) + if (query.ExcludeProviderIds != null && query.ExcludeProviderIds.Count > 0) { var excludeIds = new List(); @@ -4457,7 +4457,7 @@ namespace Emby.Server.Implementations.Data } } - if (query.HasAnyProviderId.Count > 0) + if (query.HasAnyProviderId != null && query.HasAnyProviderId.Count > 0) { var hasProviderIds = new List(); diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index c060210296..75fea365ba 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -1,5 +1,3 @@ -#nullable disable - #pragma warning disable CS1591 using System; @@ -20,9 +18,9 @@ namespace MediaBrowser.Controller.Entities public int? Limit { get; set; } - public User User { get; set; } + public User? User { get; set; } - public BaseItem SimilarTo { get; set; } + public BaseItem? SimilarTo { get; set; } public bool? IsFolder { get; set; } @@ -58,23 +56,23 @@ namespace MediaBrowser.Controller.Entities public bool? CollapseBoxSetItems { get; set; } - public string NameStartsWithOrGreater { get; set; } + public string? NameStartsWithOrGreater { get; set; } - public string NameStartsWith { get; set; } + public string? NameStartsWith { get; set; } - public string NameLessThan { get; set; } + public string? NameLessThan { get; set; } - public string NameContains { get; set; } + public string? NameContains { get; set; } - public string MinSortName { get; set; } + public string? MinSortName { get; set; } - public string PresentationUniqueKey { get; set; } + public string? PresentationUniqueKey { get; set; } - public string Path { get; set; } + public string? Path { get; set; } - public string Name { get; set; } + public string? Name { get; set; } - public string Person { get; set; } + public string? Person { get; set; } public Guid[] PersonIds { get; set; } @@ -82,7 +80,7 @@ namespace MediaBrowser.Controller.Entities public Guid[] ExcludeItemIds { get; set; } - public string AdjacentTo { get; set; } + public string? AdjacentTo { get; set; } public string[] PersonTypes { get; set; } @@ -182,13 +180,13 @@ namespace MediaBrowser.Controller.Entities public Guid ParentId { get; set; } - public string ParentType { get; set; } + public string? ParentType { get; set; } public Guid[] AncestorIds { get; set; } public Guid[] TopParentIds { get; set; } - public BaseItem Parent + public BaseItem? Parent { set { @@ -213,9 +211,9 @@ namespace MediaBrowser.Controller.Entities public SeriesStatus[] SeriesStatuses { get; set; } - public string ExternalSeriesId { get; set; } + public string? ExternalSeriesId { get; set; } - public string ExternalId { get; set; } + public string? ExternalId { get; set; } public Guid[] AlbumIds { get; set; } @@ -223,9 +221,9 @@ namespace MediaBrowser.Controller.Entities public Guid[] ExcludeArtistIds { get; set; } - public string AncestorWithPresentationUniqueKey { get; set; } + public string? AncestorWithPresentationUniqueKey { get; set; } - public string SeriesPresentationUniqueKey { get; set; } + public string? SeriesPresentationUniqueKey { get; set; } public bool GroupByPresentationUniqueKey { get; set; } @@ -235,7 +233,7 @@ namespace MediaBrowser.Controller.Entities public bool ForceDirect { get; set; } - public Dictionary ExcludeProviderIds { get; set; } + public Dictionary? ExcludeProviderIds { get; set; } public bool EnableGroupByMetadataKey { get; set; } @@ -253,13 +251,13 @@ namespace MediaBrowser.Controller.Entities public int MinSimilarityScore { get; set; } - public string HasNoAudioTrackWithLanguage { get; set; } + public string? HasNoAudioTrackWithLanguage { get; set; } - public string HasNoInternalSubtitleTrackWithLanguage { get; set; } + public string? HasNoInternalSubtitleTrackWithLanguage { get; set; } - public string HasNoExternalSubtitleTrackWithLanguage { get; set; } + public string? HasNoExternalSubtitleTrackWithLanguage { get; set; } - public string HasNoSubtitleTrackWithLanguage { get; set; } + public string? HasNoSubtitleTrackWithLanguage { get; set; } public bool? IsDeadArtist { get; set; } @@ -283,12 +281,10 @@ namespace MediaBrowser.Controller.Entities ExcludeInheritedTags = Array.Empty(); ExcludeItemIds = Array.Empty(); ExcludeItemTypes = Array.Empty(); - ExcludeProviderIds = new Dictionary(StringComparer.OrdinalIgnoreCase); ExcludeTags = Array.Empty(); GenreIds = Array.Empty(); Genres = Array.Empty(); GroupByPresentationUniqueKey = true; - HasAnyProviderId = new Dictionary(StringComparer.OrdinalIgnoreCase); ImageTypes = Array.Empty(); IncludeItemTypes = Array.Empty(); ItemIds = Array.Empty(); @@ -309,32 +305,33 @@ namespace MediaBrowser.Controller.Entities Years = Array.Empty(); } - public InternalItemsQuery(User user) + public InternalItemsQuery(User? user) : this() { - SetUser(user); + if (user != null) + { + SetUser(user); + } } public void SetUser(User user) { - if (user != null) + MaxParentalRating = user.MaxParentalAgeRating; + + if (MaxParentalRating.HasValue) { - MaxParentalRating = user.MaxParentalAgeRating; - - if (MaxParentalRating.HasValue) - { - BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems) - .Where(i => i != UnratedItem.Other.ToString()) - .Select(e => Enum.Parse(e, true)).ToArray(); - } - - ExcludeInheritedTags = user.GetPreference(PreferenceKind.BlockedTags); - - User = user; + string other = UnratedItem.Other.ToString(); + BlockUnratedItems = user.GetPreference(PreferenceKind.BlockUnratedItems) + .Where(i => i != other) + .Select(e => Enum.Parse(e, true)).ToArray(); } + + ExcludeInheritedTags = user.GetPreference(PreferenceKind.BlockedTags); + + User = user; } - public Dictionary HasAnyProviderId { get; set; } + public Dictionary? HasAnyProviderId { get; set; } public Guid[] AlbumArtistIds { get; set; } @@ -356,8 +353,8 @@ namespace MediaBrowser.Controller.Entities public int? MinWidth { get; set; } - public string SearchTerm { get; set; } + public string? SearchTerm { get; set; } - public string SeriesTimerId { get; set; } + public string? SeriesTimerId { get; set; } } } From 8407c3d558b33ea56c17d8a6bce81757eba805d9 Mon Sep 17 00:00:00 2001 From: MrTimscampi Date: Tue, 18 May 2021 12:37:00 +0200 Subject: [PATCH 1673/1930] Properly detect Dolby Vision files derived from AV1, AVC and HEVC --- MediaBrowser.Model/Entities/MediaStream.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index e644c9ba72..c67f30d045 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -104,6 +104,19 @@ namespace MediaBrowser.Model.Entities return "HDR"; } + // For some Dolby Vision files, no color transfer is provided, so check the codec + + var codecTag = CodecTag; + + if (string.Equals(codecTag, "dva1", StringComparison.OrdinalIgnoreCase) + || string.Equals(codecTag, "dvav", StringComparison.OrdinalIgnoreCase) + || string.Equals(codecTag, "dvh1", StringComparison.OrdinalIgnoreCase) + || string.Equals(codecTag, "dvhe", StringComparison.OrdinalIgnoreCase) + || string.Equals(codecTag, "dav1", StringComparison.OrdinalIgnoreCase)) + { + return "HDR"; + } + return "SDR"; } } From 6353966abdc31a7806c6d4d62154cf3da7c86adf Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Tue, 18 May 2021 13:17:34 +0200 Subject: [PATCH 1674/1930] Fix cache key --- MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs index 125b1b604a..79ec6139d1 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs @@ -281,7 +281,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb /// The TMDb person information or null if not found. public async Task GetPersonAsync(int personTmdbId, string language, CancellationToken cancellationToken) { - var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}"; + var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}-{language}"; if (_memoryCache.TryGetValue(key, out Person person)) { return person; From ee7a95e088520f835a4d179c7c5faec5eaa8f9ff Mon Sep 17 00:00:00 2001 From: David Ullmer Date: Tue, 18 May 2021 13:44:38 +0200 Subject: [PATCH 1675/1930] Move GetMetadataLanguage --- .../Plugins/Tmdb/People/TmdbPersonImageProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs index 99a43966f3..e4c908a62c 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonImageProvider.cs @@ -48,13 +48,13 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.People public async Task> GetImages(BaseItem item, CancellationToken cancellationToken) { var person = (Person)item; - var language = item.GetPreferredMetadataLanguage(); if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId)) { return Enumerable.Empty(); } + var language = item.GetPreferredMetadataLanguage(); var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), language, cancellationToken).ConfigureAwait(false); if (personResult?.Images?.Profiles == null) { From 1027792b16996e3fe7e4835805204e8c91beda01 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 19 May 2021 08:51:46 +0200 Subject: [PATCH 1676/1930] Review changes --- Emby.Naming/Video/VideoResolver.cs | 4 ++-- .../Data/SqliteExtensions.cs | 22 +++++++++---------- .../Data/SqliteItemRepository.cs | 21 +++++++++--------- .../Video/VideoResolverTests.cs | 6 ++++- .../MediaInfo/SubtitleResolverTests.cs | 8 +++---- 5 files changed, 33 insertions(+), 28 deletions(-) diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index d1c294f4fd..27e73208c6 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -59,7 +59,7 @@ namespace Emby.Naming.Video } bool isStub = false; - ReadOnlySpan container = null; + ReadOnlySpan container = ReadOnlySpan.Empty; string? stubType = null; if (!isDirectory) @@ -105,7 +105,7 @@ namespace Emby.Naming.Video return new VideoFileInfo( path: path, - container: container.ToString(), + container: container.IsEmpty ? null : container.ToString(), isStub: isStub, name: name, year: year, diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index 51a53c6cbe..3499713e1d 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.Data return true; } - private static bool IsDbNull(this IResultSetValue result) + public static bool IsDbNull(this IResultSetValue result) { return result.SQLiteType == SQLiteType.Null; } @@ -158,12 +158,12 @@ namespace Emby.Server.Implementations.Data return result[index].ToBool(); } - public static bool TryGetBoolean(this IReadOnlyList reader, int index, [NotNullWhen(true)] out bool? result) + public static bool TryGetBoolean(this IReadOnlyList reader, int index, [NotNullWhen(true)] out bool result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -171,12 +171,12 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetInt32(this IReadOnlyList reader, int index, [NotNullWhen(true)] out int? result) + public static bool TryGetInt32(this IReadOnlyList reader, int index, [NotNullWhen(true)] out int result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -189,12 +189,12 @@ namespace Emby.Server.Implementations.Data return result[index].ToInt64(); } - public static bool TryGetInt64(this IReadOnlyList reader, int index, [NotNullWhen(true)] out long? result) + public static bool TryGetInt64(this IReadOnlyList reader, int index, [NotNullWhen(true)] out long result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -202,12 +202,12 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetSingle(this IReadOnlyList reader, int index, [NotNullWhen(true)] out float? result) + public static bool TryGetSingle(this IReadOnlyList reader, int index, [NotNullWhen(true)] out float result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -215,12 +215,12 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetDouble(this IReadOnlyList reader, int index, [NotNullWhen(true)] out double? result) + public static bool TryGetDouble(this IReadOnlyList reader, int index, [NotNullWhen(true)] out double result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 996cdf1337..69e67d1332 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1346,7 +1346,7 @@ namespace Emby.Server.Implementations.Data } var channelId = reader[index]; - if (channelId.SQLiteType != SQLiteType.Null) + if (!channelId.IsDbNull()) { if (!Utf8Parser.TryParse(channelId.ToBlob(), out Guid value, out _, standardFormat: 'N')) { @@ -1366,12 +1366,12 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetBoolean(index++, out var isMovie)) { - hasProgramAttributes.IsMovie = isMovie.Value; + hasProgramAttributes.IsMovie = isMovie; } if (reader.TryGetBoolean(index++, out var isSeries)) { - hasProgramAttributes.IsSeries = isSeries.Value; + hasProgramAttributes.IsSeries = isSeries; } if (reader.TryGetString(index++, out var episodeTitle)) @@ -1381,7 +1381,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetBoolean(index++, out var isRepeat)) { - hasProgramAttributes.IsRepeat = isRepeat.Value; + hasProgramAttributes.IsRepeat = isRepeat; } } else @@ -1412,7 +1412,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetBoolean(index++, out var isLocked)) { - item.IsLocked = isLocked.Value; + item.IsLocked = isLocked; } if (reader.TryGetString(index++, out var preferredMetadataLanguage)) @@ -1430,7 +1430,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetInt32(index++, out var width)) { - item.Width = width.Value; + item.Width = width; } } @@ -1438,7 +1438,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetInt32(index++, out var height)) { - item.Height = height.Value; + item.Height = height; } } @@ -1536,6 +1536,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetString(index++, out var audioString)) { + // TODO Span overload coming in the future https://github.com/dotnet/runtime/issues/1916 if (Enum.TryParse(audioString, true, out ProgramAudio audio)) { item.Audio = audio; @@ -1559,7 +1560,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetBoolean(index++, out var isInMixedFolder)) { - item.IsInMixedFolder = isInMixedFolder.Value; + item.IsInMixedFolder = isInMixedFolder; } if (HasField(query, ItemFields.DateLastSaved)) @@ -1669,7 +1670,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetBoolean(index++, out var isVirtualItem)) { - item.IsVirtualItem = isVirtualItem.Value; + item.IsVirtualItem = isVirtualItem; } if (item is IHasSeries hasSeriesName) @@ -1731,7 +1732,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetInt32(index++, out var parentalRating)) { - item.InheritedParentalRatingValue = parentalRating.Value; + item.InheritedParentalRatingValue = parentalRating; } } diff --git a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs index 9bbbe29709..c56046f039 100644 --- a/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs +++ b/tests/Jellyfin.Naming.Tests/Video/VideoResolverTests.cs @@ -148,7 +148,7 @@ namespace Jellyfin.Naming.Tests.Video yield return new object[] { new VideoFileInfo( - path: @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - Ozlem.mp4", + path: @"/server/Movies/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - JEFF/Rain Man 1988 REMASTERED 1080p BluRay x264 AAC - JEFF.mp4", container: "mp4", name: "Rain Man", year: 1988) @@ -200,6 +200,10 @@ namespace Jellyfin.Naming.Tests.Video Assert.NotNull(results[0]); Assert.NotNull(results[1]); Assert.Null(results[2]); + foreach (var result in results) + { + Assert.Null(result?.Container); + } } } } diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs index 80b0bc3702..b160e676e4 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/SubtitleResolverTests.cs @@ -38,7 +38,7 @@ namespace Jellyfin.Providers.Tests.MediaInfo "/video/My.Video.With.Additional.Garbage.en.srt", "/video/My.Video With Additional Garbage.srt" }, - new List + new[] { CreateMediaStream("/video/My.Video.srt", "srt", null, index++), CreateMediaStream("/video/My.Video.vtt", "vtt", null, index++), @@ -58,12 +58,12 @@ namespace Jellyfin.Providers.Tests.MediaInfo [Theory] [MemberData(nameof(AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles_TestData))] - public void AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles(List streams, string videoPath, int startIndex, string[] files, List expectedResult) + public void AddExternalSubtitleStreams_GivenMixedFilenames_ReturnsValidSubtitles(List streams, string videoPath, int startIndex, string[] files, MediaStream[] expectedResult) { new SubtitleResolver(Mock.Of()).AddExternalSubtitleStreams(streams, videoPath, startIndex, files); - Assert.Equal(expectedResult.Count, streams.Count); - for (var i = 0; i < expectedResult.Count; i++) + Assert.Equal(expectedResult.Length, streams.Count); + for (var i = 0; i < expectedResult.Length; i++) { var expected = expectedResult[i]; var actual = streams[i]; From 7e6a45c402988cba27c36cc6b1b339a4a52b732a Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 19 May 2021 19:33:24 +0200 Subject: [PATCH 1677/1930] Review changes --- .../Data/SqliteExtensions.cs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index 3499713e1d..a8f3feb589 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -97,12 +97,12 @@ namespace Emby.Server.Implementations.Data DateTimeStyles.None).ToUniversalTime(); } - public static bool TryReadDateTime(this IReadOnlyList reader, int index, [NotNullWhen(true)] out DateTime? result) + public static bool TryReadDateTime(this IReadOnlyList reader, int index, out DateTime result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -114,15 +114,16 @@ namespace Emby.Server.Implementations.Data return true; } + result = default; return false; } - public static bool TryGetGuid(this IReadOnlyList reader, int index, [NotNullWhen(true)] out Guid? result) + public static bool TryGetGuid(this IReadOnlyList reader, int index, out Guid result) { - result = null; var item = reader[index]; if (item.IsDbNull()) { + result = default; return false; } @@ -158,7 +159,7 @@ namespace Emby.Server.Implementations.Data return result[index].ToBool(); } - public static bool TryGetBoolean(this IReadOnlyList reader, int index, [NotNullWhen(true)] out bool result) + public static bool TryGetBoolean(this IReadOnlyList reader, int index, out bool result) { var item = reader[index]; if (item.IsDbNull()) @@ -171,7 +172,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetInt32(this IReadOnlyList reader, int index, [NotNullWhen(true)] out int result) + public static bool TryGetInt32(this IReadOnlyList reader, int index, out int result) { var item = reader[index]; if (item.IsDbNull()) @@ -189,7 +190,7 @@ namespace Emby.Server.Implementations.Data return result[index].ToInt64(); } - public static bool TryGetInt64(this IReadOnlyList reader, int index, [NotNullWhen(true)] out long result) + public static bool TryGetInt64(this IReadOnlyList reader, int index, out long result) { var item = reader[index]; if (item.IsDbNull()) @@ -202,7 +203,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetSingle(this IReadOnlyList reader, int index, [NotNullWhen(true)] out float result) + public static bool TryGetSingle(this IReadOnlyList reader, int index, out float result) { var item = reader[index]; if (item.IsDbNull()) @@ -215,7 +216,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetDouble(this IReadOnlyList reader, int index, [NotNullWhen(true)] out double result) + public static bool TryGetDouble(this IReadOnlyList reader, int index, out double result) { var item = reader[index]; if (item.IsDbNull()) From e0f793799afccd4e2d640dbf5554f72d8a8f8b02 Mon Sep 17 00:00:00 2001 From: cvium Date: Wed, 19 May 2021 19:52:45 +0200 Subject: [PATCH 1678/1930] Fix build --- .../Data/SqliteItemRepository.cs | 20 +++++++++---------- .../Security/AuthenticationRepository.cs | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 69e67d1332..99275a7496 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1334,7 +1334,7 @@ namespace Emby.Server.Implementations.Data { if (item is IHasStartDate hasStartDate && reader.TryReadDateTime(index, out var startDate)) { - hasStartDate.StartDate = startDate.Value; + hasStartDate.StartDate = startDate; } index++; @@ -1446,7 +1446,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryReadDateTime(index++, out var dateLastRefreshed)) { - item.DateLastRefreshed = dateLastRefreshed.Value; + item.DateLastRefreshed = dateLastRefreshed; } } @@ -1510,13 +1510,13 @@ namespace Emby.Server.Implementations.Data { if (reader.TryReadDateTime(index++, out var dateCreated)) { - item.DateCreated = dateCreated.Value; + item.DateCreated = dateCreated; } } if (reader.TryReadDateTime(index++, out var dateModified)) { - item.DateModified = dateModified.Value; + item.DateModified = dateModified; } item.Id = reader.GetGuid(index++); @@ -1531,7 +1531,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetGuid(index++, out var parentId)) { - item.ParentId = parentId.Value; + item.ParentId = parentId; } if (reader.TryGetString(index++, out var audioString)) @@ -1567,7 +1567,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryReadDateTime(index++, out var dateLastSaved)) { - item.DateLastSaved = dateLastSaved.Value; + item.DateLastSaved = dateLastSaved; } } @@ -1695,7 +1695,7 @@ namespace Emby.Server.Implementations.Data index++; if (reader.TryGetGuid(index, out var seasonId)) { - episode.SeasonId = seasonId.Value; + episode.SeasonId = seasonId; } } else @@ -1713,7 +1713,7 @@ namespace Emby.Server.Implementations.Data { if (reader.TryGetGuid(index, out var seriesId)) { - hasSeries.SeriesId = seriesId.Value; + hasSeries.SeriesId = seriesId; } } @@ -1845,7 +1845,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryGetGuid(index, out var ownerId)) { - item.OwnerId = ownerId.Value; + item.OwnerId = ownerId; } return item; @@ -1958,7 +1958,7 @@ namespace Emby.Server.Implementations.Data if (reader.TryReadDateTime(3, out var imageDateModified)) { - chapter.ImageDateModified = imageDateModified.Value; + chapter.ImageDateModified = imageDateModified; } return chapter; diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index ca7e748581..76f863c951 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -326,7 +326,7 @@ namespace Emby.Server.Implementations.Security if (reader.TryReadDateTime(9, out var dateLastActivity)) { - info.DateLastActivity = dateLastActivity.Value; + info.DateLastActivity = dateLastActivity; } else { From c6ca722e57c7b83c5105bbf9b0de63b616d556de Mon Sep 17 00:00:00 2001 From: Sanaf Raw Date: Tue, 18 May 2021 20:00:59 +0000 Subject: [PATCH 1679/1930] Translated using Weblate (Bengali) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/bn/ --- Emby.Server.Implementations/Localization/Core/bn.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/bn.json b/Emby.Server.Implementations/Localization/Core/bn.json index f0e42a052b..c3fbe24082 100644 --- a/Emby.Server.Implementations/Localization/Core/bn.json +++ b/Emby.Server.Implementations/Localization/Core/bn.json @@ -1,7 +1,7 @@ { "DeviceOnlineWithName": "{0}-এর সাথে সংযুক্ত হয়েছে", "DeviceOfflineWithName": "{0}-এর সাথে সংযোগ বিচ্ছিন্ন হয়েছে", - "Collections": "কলেক্শন", + "Collections": "সংগ্রহ", "ChapterNameValue": "অধ্যায় {0}", "Channels": "চ্যানেল", "CameraImageUploadedFrom": "{0} থেকে একটি নতুন ক্যামেরার চিত্র আপলোড করা হয়েছে", From 26d7fc828075dbaa3068ac9c323ebef3370fd023 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 20 May 2021 22:10:19 +0200 Subject: [PATCH 1680/1930] Enable nullable reference types for MediaBrowser.MediaEncoding.Subtitles --- .../Attachments/AttachmentExtractor.cs | 1 + .../BdInfo/BdInfoDirectoryInfo.cs | 6 +- .../BdInfo/BdInfoFileInfo.cs | 2 +- .../Encoder/EncoderValidator.cs | 15 ++-- .../Encoder/MediaEncoder.cs | 1 + .../MediaBrowser.MediaEncoding.csproj | 1 + .../Probing/FFProbeHelpers.cs | 2 + .../Probing/InternalMediaInfoResult.cs | 2 + .../Probing/MediaChapter.cs | 1 + .../Probing/MediaFormatInfo.cs | 2 + .../Probing/MediaStreamInfo.cs | 2 + .../Probing/ProbeResultNormalizer.cs | 1 + .../Subtitles/AssParser.cs | 2 - .../Subtitles/ParserValues.cs | 1 - .../Subtitles/SrtParser.cs | 2 - .../Subtitles/SsaParser.cs | 2 - .../Subtitles/SubtitleEditParser.cs | 2 - .../Subtitles/SubtitleEncoder.cs | 72 ++++++++++--------- 18 files changed, 65 insertions(+), 52 deletions(-) diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index e8aeabf9d0..a0ec3bd90d 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs index ef9943722d..e86e518be6 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoDirectoryInfo.cs @@ -9,9 +9,9 @@ namespace MediaBrowser.MediaEncoding.BdInfo { public class BdInfoDirectoryInfo : IDirectoryInfo { - private readonly IFileSystem _fileSystem = null; + private readonly IFileSystem _fileSystem; - private readonly FileSystemMetadata _impl = null; + private readonly FileSystemMetadata _impl; public BdInfoDirectoryInfo(IFileSystem fileSystem, string path) { @@ -29,7 +29,7 @@ namespace MediaBrowser.MediaEncoding.BdInfo public string FullName => _impl.FullName; - public IDirectoryInfo Parent + public IDirectoryInfo? Parent { get { diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs index 0a8af8e9c8..41143c2593 100644 --- a/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoFileInfo.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.MediaEncoding.BdInfo { public class BdInfoFileInfo : BDInfo.IO.IFileInfo { - private FileSystemMetadata _impl = null; + private FileSystemMetadata _impl; public BdInfoFileInfo(FileSystemMetadata impl) { diff --git a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs index 9e24176033..f782e65bd1 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs @@ -121,11 +121,11 @@ namespace MediaBrowser.MediaEncoding.Encoder // When changing this, also change the minimum library versions in _ffmpegMinimumLibraryVersions public static Version MinVersion { get; } = new Version(4, 0); - public static Version MaxVersion { get; } = null; + public static Version? MaxVersion { get; } = null; public bool ValidateVersion() { - string output = null; + string output; try { output = GetProcessOutput(_encoderPath, "-version"); @@ -133,6 +133,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { _logger.LogError(ex, "Error validating encoder"); + return false; } if (string.IsNullOrWhiteSpace(output)) @@ -207,7 +208,7 @@ namespace MediaBrowser.MediaEncoding.Encoder /// /// The output from "ffmpeg -version". /// The FFmpeg version. - internal Version GetFFmpegVersion(string output) + internal Version? GetFFmpegVersion(string output) { // For pre-built binaries the FFmpeg version should be mentioned at the very start of the output var match = Regex.Match(output, @"^ffmpeg version n?((?:[0-9]+\.?)+)"); @@ -275,7 +276,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private IEnumerable GetHwaccelTypes() { - string output = null; + string? output = null; try { output = GetProcessOutput(_encoderPath, "-hwaccels"); @@ -303,7 +304,7 @@ namespace MediaBrowser.MediaEncoding.Encoder return false; } - string output = null; + string output; try { output = GetProcessOutput(_encoderPath, "-h filter=" + filter); @@ -311,6 +312,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { _logger.LogError(ex, "Error detecting the given filter"); + return false; } if (output.Contains("Filter " + filter, StringComparison.Ordinal)) @@ -331,7 +333,7 @@ namespace MediaBrowser.MediaEncoding.Encoder private IEnumerable GetCodecs(Codec codec) { string codecstr = codec == Codec.Encoder ? "encoders" : "decoders"; - string output = null; + string output; try { output = GetProcessOutput(_encoderPath, "-" + codecstr); @@ -339,6 +341,7 @@ namespace MediaBrowser.MediaEncoding.Encoder catch (Exception ex) { _logger.LogError(ex, "Error detecting available {Codec}", codecstr); + return Enumerable.Empty(); } if (string.IsNullOrWhiteSpace(output)) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 62c0c0bb1f..cdb778bf2d 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index 39fb0b47c1..7733e715f2 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -10,6 +10,7 @@ false true true + enable AllEnabledByDefault ../jellyfin.ruleset diff --git a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs index da37687e8f..1fa90bb213 100644 --- a/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs +++ b/MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Globalization; diff --git a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs index 0e319c1a8b..d4d153b083 100644 --- a/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs +++ b/MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using System.Text.Json.Serialization; diff --git a/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs b/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs index de062d06b0..a1cef7a9f2 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaChapter.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs index 8af122ef9b..d50da37b89 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaFormatInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using System.Text.Json.Serialization; diff --git a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs index 7b7744163c..c9c8c34c2e 100644 --- a/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs +++ b/MediaBrowser.MediaEncoding/Probing/MediaStreamInfo.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Collections.Generic; using System.Text.Json.Serialization; diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 884ec0a293..2ec9dc3467 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs index 8219aa7b47..08ee5c72e5 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/AssParser.cs @@ -1,5 +1,3 @@ -#nullable enable - using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core.SubtitleFormats; diff --git a/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs b/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs index dca5c1e8ac..cec1aaf080 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs @@ -1,4 +1,3 @@ -#nullable enable #pragma warning disable CS1591 namespace MediaBrowser.MediaEncoding.Subtitles diff --git a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs index 19fb951dc5..78d54ca51f 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs @@ -1,5 +1,3 @@ -#nullable enable - using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core.SubtitleFormats; diff --git a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs index 36dc2e01fc..17c2ae40e0 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs @@ -1,5 +1,3 @@ -#nullable enable - using Microsoft.Extensions.Logging; using Nikse.SubtitleEdit.Core.SubtitleFormats; diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs index 82ec6ca217..639a34d993 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs @@ -1,5 +1,3 @@ -#nullable enable - using System.Globalization; using System.IO; using System.Linq; diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 39bec8da1c..608ebf4436 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -71,8 +72,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - var reader = GetReader(inputFormat, true); - + var reader = GetReader(inputFormat); var trackInfo = reader.Parse(stream, cancellationToken); FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps); @@ -139,10 +139,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles .ConfigureAwait(false); var inputFormat = subtitle.format; - var writer = TryGetWriter(outputFormat); // Return the original if we don't have any way of converting it - if (writer == null) + if (!TryGetWriter(outputFormat, out var writer)) { return subtitle.stream; } @@ -239,7 +238,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec) .TrimStart('.'); - if (GetReader(currentFormat, false) == null) + if (TryGetReader(currentFormat, out _)) { // Convert var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt"); @@ -257,37 +256,41 @@ namespace MediaBrowser.MediaEncoding.Subtitles return new SubtitleInfo(subtitleStream.Path, mediaSource.Protocol, currentFormat, true); } - private ISubtitleParser GetReader(string format, bool throwIfMissing) + private bool TryGetReader(string format, [NotNullWhen(true)] out ISubtitleParser? value) { - if (string.IsNullOrEmpty(format)) - { - throw new ArgumentNullException(nameof(format)); - } - if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase)) { - return new SrtParser(_logger); + value = new SrtParser(_logger); + return true; } if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase)) { - return new SsaParser(_logger); + value = new SsaParser(_logger); + return true; } if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase)) { - return new AssParser(_logger); + value = new AssParser(_logger); + return true; } - if (throwIfMissing) - { - throw new ArgumentException("Unsupported format: " + format); - } - - return null; + value = null; + return false; } - private ISubtitleWriter TryGetWriter(string format) + private ISubtitleParser GetReader(string format) + { + if (TryGetReader(format, out var reader)) + { + return reader; + } + + throw new ArgumentException("Unsupported format: " + format); + } + + private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value) { if (string.IsNullOrEmpty(format)) { @@ -296,32 +299,35 @@ namespace MediaBrowser.MediaEncoding.Subtitles if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase)) { - return new JsonWriter(); + value = new JsonWriter(); + return true; } if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase)) { - return new SrtWriter(); + value = new SrtWriter(); + return true; } if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase)) { - return new VttWriter(); + value = new VttWriter(); + return true; } if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase)) { - return new TtmlWriter(); + value = new TtmlWriter(); + return true; } - return null; + value = null; + return false; } private ISubtitleWriter GetWriter(string format) { - var writer = TryGetWriter(format); - - if (writer != null) + if (TryGetWriter(format, out var writer)) { return writer; } @@ -391,7 +397,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw new ArgumentNullException(nameof(outputPath)); } - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath))); var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false); @@ -549,7 +555,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles throw new ArgumentNullException(nameof(outputPath)); } - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); + Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath))); var processArgs = string.Format( CultureInfo.InvariantCulture, @@ -715,7 +721,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false)) { - var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName; + var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName ?? string.Empty; // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal)) @@ -725,7 +731,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles charset = string.Empty; } - _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path); + _logger.LogDebug("charset {0} detected for {Path}", charset, path); return charset; } From 7e8428e588b3f0a0574da44081098c64fe1a47d7 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Thu, 20 May 2021 21:28:18 +0200 Subject: [PATCH 1681/1930] Enable nullable reference types for Emby.Server.Implementations --- .../AppBase/BaseApplicationPaths.cs | 8 ++------ .../AppBase/BaseConfigurationManager.cs | 2 ++ .../AppBase/ConfigurationHelper.cs | 2 -- .../ApplicationHost.cs | 2 ++ .../Channels/ChannelManager.cs | 2 ++ .../Collections/CollectionImageProvider.cs | 4 ++-- .../Collections/CollectionManager.cs | 2 ++ .../ServerConfigurationManager.cs | 2 ++ .../Cryptography/CryptographyProvider.cs | 2 -- .../Data/BaseSqliteRepository.cs | 2 ++ .../Data/ManagedConnection.cs | 2 +- .../Data/SqliteExtensions.cs | 1 + .../Data/SqliteItemRepository.cs | 2 ++ .../Data/SqliteUserDataRepository.cs | 2 ++ .../Data/TypeMapper.cs | 6 +++--- .../Devices/DeviceId.cs | 2 ++ .../Devices/DeviceManager.cs | 2 ++ Emby.Server.Implementations/Dto/DtoService.cs | 2 ++ .../Emby.Server.Implementations.csproj | 1 + .../EntryPoints/ExternalPortForwarding.cs | 2 ++ .../EntryPoints/LibraryChangedNotifier.cs | 2 ++ .../EntryPoints/RecordingNotifier.cs | 2 ++ .../EntryPoints/UdpServerEntryPoint.cs | 2 -- .../EntryPoints/UserDataChangeNotifier.cs | 2 ++ .../Security/AuthorizationContext.cs | 20 +++++++++---------- .../HttpServer/Security/SessionContext.cs | 4 ++-- .../HttpServer/WebSocketConnection.cs | 2 -- .../HttpServer/WebSocketManager.cs | 2 ++ .../IO/FileRefresher.cs | 2 ++ .../IO/LibraryMonitor.cs | 2 ++ .../IO/ManagedFileSystem.cs | 6 +++--- .../IO/MbLinkShortcutHandler.cs | 2 +- .../IO/StreamHelper.cs | 2 +- .../IStartupOptions.cs | 1 - .../Images/BaseDynamicImageProvider.cs | 2 ++ .../Images/CollectionFolderImageProvider.cs | 2 ++ .../Images/DynamicImageProvider.cs | 2 ++ .../Images/FolderImageProvider.cs | 2 ++ .../Images/GenreImageProvider.cs | 2 ++ .../Images/PlaylistImageProvider.cs | 2 ++ .../Library/ExclusiveLiveStream.cs | 2 ++ .../Library/IgnorePatterns.cs | 2 -- .../Library/LibraryManager.cs | 2 ++ .../Library/LiveStreamHelper.cs | 2 ++ .../Library/MediaSourceManager.cs | 2 ++ .../Library/MediaStreamSelector.cs | 2 ++ .../Library/MusicManager.cs | 2 ++ .../Library/PathExtensions.cs | 2 -- .../Library/ResolverHelper.cs | 2 -- .../Library/Resolvers/Audio/AudioResolver.cs | 2 ++ .../Resolvers/Audio/MusicAlbumResolver.cs | 2 ++ .../Resolvers/Audio/MusicArtistResolver.cs | 2 ++ .../Library/Resolvers/BaseVideoResolver.cs | 2 ++ .../Library/Resolvers/Books/BookResolver.cs | 2 ++ .../Library/Resolvers/FolderResolver.cs | 2 ++ .../Library/Resolvers/ItemResolver.cs | 2 ++ .../Resolvers/Movies/BoxSetResolver.cs | 2 ++ .../Library/Resolvers/Movies/MovieResolver.cs | 2 ++ .../Library/Resolvers/PhotoAlbumResolver.cs | 2 ++ .../Library/Resolvers/PhotoResolver.cs | 2 ++ .../Library/Resolvers/PlaylistResolver.cs | 2 ++ .../Resolvers/SpecialFolderResolver.cs | 2 ++ .../Library/Resolvers/TV/EpisodeResolver.cs | 2 ++ .../Library/Resolvers/TV/SeasonResolver.cs | 2 ++ .../Library/Resolvers/TV/SeriesResolver.cs | 2 ++ .../Library/Resolvers/VideoResolver.cs | 2 ++ .../Library/SearchEngine.cs | 2 ++ .../Library/UserDataManager.cs | 2 ++ .../Library/UserViewManager.cs | 2 ++ .../LiveTv/EmbyTV/DirectRecorder.cs | 2 ++ .../LiveTv/EmbyTV/EmbyTV.cs | 2 ++ .../LiveTv/EmbyTV/EncodedRecorder.cs | 2 ++ .../LiveTv/EmbyTV/EpgChannelData.cs | 7 +++---- .../LiveTv/EmbyTV/ItemDataProvider.cs | 2 ++ .../LiveTv/EmbyTV/RecordingHelper.cs | 2 ++ .../LiveTv/EmbyTV/TimerManager.cs | 2 ++ .../LiveTv/Listings/SchedulesDirect.cs | 2 ++ .../LiveTv/Listings/XmlTvListingsProvider.cs | 2 ++ .../LiveTv/LiveTvDtoService.cs | 2 ++ .../LiveTv/LiveTvManager.cs | 2 ++ .../LiveTv/LiveTvMediaSourceProvider.cs | 2 ++ .../LiveTv/TunerHosts/BaseTunerHost.cs | 2 ++ .../LiveTv/TunerHosts/HdHomerun/Channels.cs | 2 ++ .../TunerHosts/HdHomerun/DiscoverResponse.cs | 2 ++ .../TunerHosts/HdHomerun/HdHomerunHost.cs | 2 ++ .../TunerHosts/HdHomerun/HdHomerunManager.cs | 2 ++ .../HdHomerun/HdHomerunUdpStream.cs | 2 ++ .../LiveTv/TunerHosts/LiveStream.cs | 2 ++ .../LiveTv/TunerHosts/M3UTunerHost.cs | 2 ++ .../LiveTv/TunerHosts/M3uParser.cs | 2 ++ .../LiveTv/TunerHosts/SharedHttpStream.cs | 2 ++ .../Localization/LocalizationManager.cs | 2 ++ .../MediaEncoder/EncodingManager.cs | 2 ++ .../Net/SocketFactory.cs | 2 ++ Emby.Server.Implementations/Net/UdpSocket.cs | 2 ++ .../Playlists/PlaylistManager.cs | 2 ++ .../Plugins/PluginManager.cs | 2 -- .../QuickConnect/QuickConnectManager.cs | 2 ++ .../ScheduledTasks/ScheduledTaskWorker.cs | 2 ++ .../ScheduledTasks/TaskManager.cs | 2 ++ .../ScheduledTasks/Tasks/ChapterImagesTask.cs | 6 ++++-- .../Tasks/CleanActivityLogTask.cs | 4 ++-- .../ScheduledTasks/Triggers/DailyTrigger.cs | 2 ++ .../Triggers/IntervalTrigger.cs | 2 ++ .../ScheduledTasks/Triggers/StartupTrigger.cs | 2 ++ .../ScheduledTasks/Triggers/WeeklyTrigger.cs | 2 ++ .../Security/AuthenticationRepository.cs | 2 ++ .../Serialization/MyXmlSerializer.cs | 10 ++++++---- .../Session/SessionManager.cs | 2 ++ .../Session/SessionWebSocketListener.cs | 2 ++ .../Session/WebSocketController.cs | 1 - .../Sorting/AiredEpisodeOrderComparer.cs | 2 +- .../Sorting/AlbumArtistComparer.cs | 4 ++-- .../Sorting/AlbumComparer.cs | 4 ++-- .../Sorting/ArtistComparer.cs | 4 ++-- .../Sorting/CommunityRatingComparer.cs | 2 +- .../Sorting/CriticRatingComparer.cs | 6 +++--- .../Sorting/DateCreatedComparer.cs | 2 +- .../Sorting/DateLastMediaAddedComparer.cs | 1 + .../Sorting/DatePlayedComparer.cs | 2 ++ .../Sorting/IsFavoriteOrLikeComparer.cs | 1 + .../Sorting/IsFolderComparer.cs | 6 +++--- .../Sorting/IsPlayedComparer.cs | 2 ++ .../Sorting/IsUnplayedComparer.cs | 2 ++ .../Sorting/NameComparer.cs | 2 +- .../Sorting/OfficialRatingComparer.cs | 2 +- .../Sorting/PlayCountComparer.cs | 2 ++ .../Sorting/PremiereDateComparer.cs | 9 +++++++-- .../Sorting/ProductionYearComparer.cs | 9 +++++++-- .../Sorting/RandomComparer.cs | 2 +- .../Sorting/RuntimeComparer.cs | 2 ++ .../Sorting/SeriesSortNameComparer.cs | 2 ++ .../Sorting/SortNameComparer.cs | 2 ++ .../Sorting/StartDateComparer.cs | 2 ++ .../Sorting/StudioComparer.cs | 2 ++ Emby.Server.Implementations/SyncPlay/Group.cs | 2 ++ .../SyncPlay/SyncPlayManager.cs | 2 ++ .../TV/TVSeriesManager.cs | 2 ++ Emby.Server.Implementations/Udp/UdpServer.cs | 2 ++ .../Updates/InstallationManager.cs | 2 ++ .../Controllers/DynamicHlsController.cs | 4 ++-- Jellyfin.Api/Helpers/TranscodingJobHelper.cs | 4 +++- .../PlaybackDtos/TranscodingThrottler.cs | 3 ++- .../Migrations/Routines/MigrateUserDb.cs | 11 ++++++---- .../Extensions/StringExtensions.cs | 1 + .../Net/ISessionContext.cs | 4 ++-- .../Sorting/IBaseItemComparer.cs | 2 +- MediaBrowser.Model/IO/IFileSystem.cs | 7 +++---- MediaBrowser.Model/IO/IShortcutHandler.cs | 2 +- MediaBrowser.Model/IO/IStreamHelper.cs | 2 +- MediaBrowser.Model/Tasks/ITaskTrigger.cs | 2 +- 151 files changed, 300 insertions(+), 99 deletions(-) diff --git a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs index 660bbb2deb..6edfad575a 100644 --- a/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs +++ b/Emby.Server.Implementations/AppBase/BaseApplicationPaths.cs @@ -33,7 +33,7 @@ namespace Emby.Server.Implementations.AppBase CachePath = cacheDirectoryPath; WebPath = webDirectoryPath; - DataPath = Path.Combine(ProgramDataPath, "data"); + _dataPath = Directory.CreateDirectory(Path.Combine(ProgramDataPath, "data")).FullName; } /// @@ -55,11 +55,7 @@ namespace Emby.Server.Implementations.AppBase /// Gets the folder path to the data directory. /// /// The data directory. - public string DataPath - { - get => _dataPath; - private set => _dataPath = Directory.CreateDirectory(value).FullName; - } + public string DataPath => _dataPath; /// public string VirtualDataPath => "%AppDataPath%"; diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 4f72c8ce15..8c919db431 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs index 29bac66340..de770f59ec 100644 --- a/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs +++ b/Emby.Server.Implementations/AppBase/ConfigurationHelper.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.IO; using System.Linq; diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 75d8fc113d..82995deb30 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Channels/ChannelManager.cs b/Emby.Server.Implementations/Channels/ChannelManager.cs index 7324b0ee9f..448f124034 100644 --- a/Emby.Server.Implementations/Channels/ChannelManager.cs +++ b/Emby.Server.Implementations/Channels/ChannelManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs index c69a07e83e..ca84094024 100644 --- a/Emby.Server.Implementations/Collections/CollectionImageProvider.cs +++ b/Emby.Server.Implementations/Collections/CollectionImageProvider.cs @@ -82,9 +82,9 @@ namespace Emby.Server.Implementations.Collections return null; }) .Where(i => i != null) - .GroupBy(x => x.Id) + .GroupBy(x => x!.Id) // We removed the null values .Select(x => x.First()) - .ToList(); + .ToList()!; // Again... the list doesn't contain any null values } /// diff --git a/Emby.Server.Implementations/Collections/CollectionManager.cs b/Emby.Server.Implementations/Collections/CollectionManager.cs index c56f334481..82d80fc83c 100644 --- a/Emby.Server.Implementations/Collections/CollectionManager.cs +++ b/Emby.Server.Implementations/Collections/CollectionManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs index 7a8ed8c29f..ff5602f243 100644 --- a/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/Emby.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Globalization; using System.IO; diff --git a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs index 12a9e44e70..4a9b280852 100644 --- a/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs +++ b/Emby.Server.Implementations/Cryptography/CryptographyProvider.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; using System.Security.Cryptography; diff --git a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs index c331a61124..6f23a0888e 100644 --- a/Emby.Server.Implementations/Data/BaseSqliteRepository.cs +++ b/Emby.Server.Implementations/Data/BaseSqliteRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs index 5c094ddd2d..10c6f837e6 100644 --- a/Emby.Server.Implementations/Data/ManagedConnection.cs +++ b/Emby.Server.Implementations/Data/ManagedConnection.cs @@ -9,7 +9,7 @@ namespace Emby.Server.Implementations.Data { public class ManagedConnection : IDisposable { - private SQLiteDatabaseConnection _db; + private SQLiteDatabaseConnection? _db; private readonly SemaphoreSlim _writeLock; private bool _disposed = false; diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index a8f3feb589..e532825af5 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index b3d8860a9e..5b4bbb3395 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index e0ebd0a6cf..1756bcae08 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Data/TypeMapper.cs b/Emby.Server.Implementations/Data/TypeMapper.cs index 7044b1d194..7f1306d15a 100644 --- a/Emby.Server.Implementations/Data/TypeMapper.cs +++ b/Emby.Server.Implementations/Data/TypeMapper.cs @@ -13,7 +13,7 @@ namespace Emby.Server.Implementations.Data /// This holds all the types in the running assemblies /// so that we can de-serialize properly when we don't have strong types. /// - private readonly ConcurrentDictionary _typeMap = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _typeMap = new ConcurrentDictionary(); /// /// Gets the type. @@ -21,7 +21,7 @@ namespace Emby.Server.Implementations.Data /// Name of the type. /// Type. /// typeName is null. - public Type GetType(string typeName) + public Type? GetType(string typeName) { if (string.IsNullOrEmpty(typeName)) { @@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Data /// /// Name of the type. /// Type. - private Type LookupType(string typeName) + private Type? LookupType(string typeName) { return AppDomain.CurrentDomain.GetAssemblies() .Select(a => a.GetType(typeName)) diff --git a/Emby.Server.Implementations/Devices/DeviceId.cs b/Emby.Server.Implementations/Devices/DeviceId.cs index fa6ac95fd3..3d15b3e768 100644 --- a/Emby.Server.Implementations/Devices/DeviceId.cs +++ b/Emby.Server.Implementations/Devices/DeviceId.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Devices/DeviceManager.cs b/Emby.Server.Implementations/Devices/DeviceManager.cs index da5047d244..2637addce7 100644 --- a/Emby.Server.Implementations/Devices/DeviceManager.cs +++ b/Emby.Server.Implementations/Devices/DeviceManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Dto/DtoService.cs b/Emby.Server.Implementations/Dto/DtoService.cs index 4ae35039ab..7411239a1e 100644 --- a/Emby.Server.Implementations/Dto/DtoService.cs +++ b/Emby.Server.Implementations/Dto/DtoService.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 14f6f565c4..113863519b 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -44,6 +44,7 @@ false true true + enable AD0001 AllEnabledByDefault diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index 14201ead29..cc3e4a2c24 100644 --- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs index ae1b51b4c3..5bb4100ba9 100644 --- a/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/LibraryChangedNotifier.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs index 824bb85f44..e0ca02d986 100644 --- a/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/RecordingNotifier.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 3624e079f5..211941f443 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Net.Sockets; using System.Threading; diff --git a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 1989e9ed25..332fb33858 100644 --- a/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/Emby.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs index fbf9254d16..c87f7dbbde 100644 --- a/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/AuthorizationContext.cs @@ -27,7 +27,7 @@ namespace Emby.Server.Implementations.HttpServer.Security { if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached)) { - return (AuthorizationInfo)cached; + return (AuthorizationInfo)cached!; // Cache should never contain null } return GetAuthorization(requestContext); @@ -55,15 +55,15 @@ namespace Emby.Server.Implementations.HttpServer.Security } private AuthorizationInfo GetAuthorizationInfoFromDictionary( - in Dictionary auth, + in Dictionary? auth, in IHeaderDictionary headers, in IQueryCollection queryString) { - string deviceId = null; - string device = null; - string client = null; - string version = null; - string token = null; + string? deviceId = null; + string? device = null; + string? client = null; + string? version = null; + string? token = null; if (auth != null) { @@ -206,7 +206,7 @@ namespace Emby.Server.Implementations.HttpServer.Security /// /// The HTTP req. /// Dictionary{System.StringSystem.String}. - private Dictionary GetAuthorizationDictionary(HttpContext httpReq) + private Dictionary? GetAuthorizationDictionary(HttpContext httpReq) { var auth = httpReq.Request.Headers["X-Emby-Authorization"]; @@ -223,7 +223,7 @@ namespace Emby.Server.Implementations.HttpServer.Security /// /// The HTTP req. /// Dictionary{System.StringSystem.String}. - private Dictionary GetAuthorizationDictionary(HttpRequest httpReq) + private Dictionary? GetAuthorizationDictionary(HttpRequest httpReq) { var auth = httpReq.Headers["X-Emby-Authorization"]; @@ -240,7 +240,7 @@ namespace Emby.Server.Implementations.HttpServer.Security ///
/// The authorization header. /// Dictionary{System.StringSystem.String}. - private Dictionary GetAuthorization(ReadOnlySpan authorizationHeader) + private Dictionary? GetAuthorization(ReadOnlySpan authorizationHeader) { if (authorizationHeader == null) { diff --git a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs index dd77b45d89..c375f36ce4 100644 --- a/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/Emby.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -36,14 +36,14 @@ namespace Emby.Server.Implementations.HttpServer.Security return GetSession((HttpContext)requestContext); } - public User GetUser(HttpContext requestContext) + public User? GetUser(HttpContext requestContext) { var session = GetSession(requestContext); return session == null || session.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(session.UserId); } - public User GetUser(object requestContext) + public User? GetUser(object requestContext) { return GetUser(((HttpRequest)requestContext).HttpContext); } diff --git a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs index 06acb56061..8f7d606692 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Buffers; using System.IO.Pipelines; diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 1bee1ac310..861c0a95e3 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/IO/FileRefresher.cs b/Emby.Server.Implementations/IO/FileRefresher.cs index 7435e9d0bf..47a83d77ce 100644 --- a/Emby.Server.Implementations/IO/FileRefresher.cs +++ b/Emby.Server.Implementations/IO/FileRefresher.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/IO/LibraryMonitor.cs b/Emby.Server.Implementations/IO/LibraryMonitor.cs index 3353fae9d8..aa80bccd72 100644 --- a/Emby.Server.Implementations/IO/LibraryMonitor.cs +++ b/Emby.Server.Implementations/IO/LibraryMonitor.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 27096ed334..6a554e68ab 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -61,7 +61,7 @@ namespace Emby.Server.Implementations.IO /// The filename. /// System.String. /// filename - public virtual string ResolveShortcut(string filename) + public virtual string? ResolveShortcut(string filename) { if (string.IsNullOrEmpty(filename)) { @@ -601,7 +601,7 @@ namespace Emby.Server.Implementations.IO return GetFiles(path, null, false, recursive); } - public virtual IEnumerable GetFiles(string path, IReadOnlyList extensions, bool enableCaseSensitiveExtensions, bool recursive = false) + public virtual IEnumerable GetFiles(string path, IReadOnlyList? extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { var enumerationOptions = GetEnumerationOptions(recursive); @@ -655,7 +655,7 @@ namespace Emby.Server.Implementations.IO return GetFilePaths(path, null, false, recursive); } - public virtual IEnumerable GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false) + public virtual IEnumerable GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive = false) { var enumerationOptions = GetEnumerationOptions(recursive); diff --git a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs index e6696b8c4c..76c58d5dcd 100644 --- a/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs +++ b/Emby.Server.Implementations/IO/MbLinkShortcutHandler.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.IO public string Extension => ".mblink"; - public string Resolve(string shortcutPath) + public string? Resolve(string shortcutPath) { if (string.IsNullOrEmpty(shortcutPath)) { diff --git a/Emby.Server.Implementations/IO/StreamHelper.cs b/Emby.Server.Implementations/IO/StreamHelper.cs index c16ebd61b7..e4f5f4cf0b 100644 --- a/Emby.Server.Implementations/IO/StreamHelper.cs +++ b/Emby.Server.Implementations/IO/StreamHelper.cs @@ -11,7 +11,7 @@ namespace Emby.Server.Implementations.IO { public class StreamHelper : IStreamHelper { - public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken) + public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action? onStarted, CancellationToken cancellationToken) { byte[] buffer = ArrayPool.Shared.Rent(bufferSize); try diff --git a/Emby.Server.Implementations/IStartupOptions.cs b/Emby.Server.Implementations/IStartupOptions.cs index f719dc5f89..a430b9e720 100644 --- a/Emby.Server.Implementations/IStartupOptions.cs +++ b/Emby.Server.Implementations/IStartupOptions.cs @@ -1,5 +1,4 @@ #pragma warning disable CS1591 -#nullable enable namespace Emby.Server.Implementations { diff --git a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs index 6fa3c1c618..833fb0b7a1 100644 --- a/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/BaseDynamicImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs b/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs index 161b4c4528..ff5f26ce09 100644 --- a/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs +++ b/Emby.Server.Implementations/Images/CollectionFolderImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Images/DynamicImageProvider.cs b/Emby.Server.Implementations/Images/DynamicImageProvider.cs index 50c5314820..900b3fd9c6 100644 --- a/Emby.Server.Implementations/Images/DynamicImageProvider.cs +++ b/Emby.Server.Implementations/Images/DynamicImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Images/FolderImageProvider.cs b/Emby.Server.Implementations/Images/FolderImageProvider.cs index 0224ab32a0..859017f869 100644 --- a/Emby.Server.Implementations/Images/FolderImageProvider.cs +++ b/Emby.Server.Implementations/Images/FolderImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Images/GenreImageProvider.cs b/Emby.Server.Implementations/Images/GenreImageProvider.cs index 3817882312..6da431c68e 100644 --- a/Emby.Server.Implementations/Images/GenreImageProvider.cs +++ b/Emby.Server.Implementations/Images/GenreImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Images/PlaylistImageProvider.cs b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs index a4c106e879..b8f0f0d65c 100644 --- a/Emby.Server.Implementations/Images/PlaylistImageProvider.cs +++ b/Emby.Server.Implementations/Images/PlaylistImageProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs index 236453e805..6c65b58999 100644 --- a/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs +++ b/Emby.Server.Implementations/Library/ExclusiveLiveStream.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/IgnorePatterns.cs b/Emby.Server.Implementations/Library/IgnorePatterns.cs index e30a675931..5384c04b3b 100644 --- a/Emby.Server.Implementations/Library/IgnorePatterns.cs +++ b/Emby.Server.Implementations/Library/IgnorePatterns.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Linq; using DotNet.Globbing; diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 4d207471a2..f8d8197d46 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/LiveStreamHelper.cs b/Emby.Server.Implementations/Library/LiveStreamHelper.cs index c2951dd155..4ef7923db3 100644 --- a/Emby.Server.Implementations/Library/LiveStreamHelper.cs +++ b/Emby.Server.Implementations/Library/LiveStreamHelper.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 85d6d3043e..38e81d14c4 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs index 28fa062396..b833122ea0 100644 --- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs +++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/MusicManager.cs b/Emby.Server.Implementations/Library/MusicManager.cs index f8bae4fd1a..06300adebc 100644 --- a/Emby.Server.Implementations/Library/MusicManager.cs +++ b/Emby.Server.Implementations/Library/MusicManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/PathExtensions.cs b/Emby.Server.Implementations/Library/PathExtensions.cs index 0de4edb7e7..86b8039fab 100644 --- a/Emby.Server.Implementations/Library/PathExtensions.cs +++ b/Emby.Server.Implementations/Library/PathExtensions.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Diagnostics.CodeAnalysis; using MediaBrowser.Common.Providers; diff --git a/Emby.Server.Implementations/Library/ResolverHelper.cs b/Emby.Server.Implementations/Library/ResolverHelper.cs index 1d9b448741..ac75e5d3a1 100644 --- a/Emby.Server.Implementations/Library/ResolverHelper.cs +++ b/Emby.Server.Implementations/Library/ResolverHelper.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.IO; using System.Linq; diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index 4ad84579d8..e893d63350 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index bf32381ebf..8e1eccb10a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 60f82806fb..3d2ae95d24 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Linq; using System.Threading.Tasks; diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 16050185fb..a3dcdc9441 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs index 0525c7e307..68076730b3 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Books/BookResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs index 7dbce7a6ef..7aaee017dd 100644 --- a/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/FolderResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; diff --git a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs index 92fb2a753a..fa45ccf840 100644 --- a/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/ItemResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs index 295e9e120b..69d71d0d9a 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/BoxSetResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.IO; using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 16bf4dc4a0..02c5287646 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.IO; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 204c8a62e7..534bc80ddc 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs index 3cb6542cf7..57bf40e9ec 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PhotoResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs index 5f051321f6..ecd44be477 100644 --- a/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/PlaylistResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs index 99f3041909..7b4e143348 100644 --- a/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index 6f29bc6494..d6ae910565 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Linq; using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 768e2e4f5b..7d707df182 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + using System.Globalization; using Emby.Naming.TV; using MediaBrowser.Controller.Entities.TV; diff --git a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 8fc3e3e75c..a1562abd31 100644 --- a/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs index 62268fce90..9599faea4b 100644 --- a/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/VideoResolver.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/Library/SearchEngine.cs b/Emby.Server.Implementations/Library/SearchEngine.cs index bcdf854ca3..26e615fa08 100644 --- a/Emby.Server.Implementations/Library/SearchEngine.cs +++ b/Emby.Server.Implementations/Library/SearchEngine.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/UserDataManager.cs b/Emby.Server.Implementations/Library/UserDataManager.cs index 827e3c64b3..667e466133 100644 --- a/Emby.Server.Implementations/Library/UserDataManager.cs +++ b/Emby.Server.Implementations/Library/UserDataManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Library/UserViewManager.cs b/Emby.Server.Implementations/Library/UserViewManager.cs index ac041bcf6c..e2da672a3c 100644 --- a/Emby.Server.Implementations/Library/UserViewManager.cs +++ b/Emby.Server.Implementations/Library/UserViewManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 7a6b1d8b61..3fcadf5b1b 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 28a2095e16..7970631201 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 9372b0f6c3..26e4ef1ed9 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs index 8c27ca76e3..0ec52a9598 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/EpgChannelData.cs @@ -6,7 +6,6 @@ using MediaBrowser.Controller.LiveTv; namespace Emby.Server.Implementations.LiveTv.EmbyTV { - internal class EpgChannelData { @@ -39,13 +38,13 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV } } - public ChannelInfo GetChannelById(string id) + public ChannelInfo? GetChannelById(string id) => _channelsById.GetValueOrDefault(id); - public ChannelInfo GetChannelByNumber(string number) + public ChannelInfo? GetChannelByNumber(string number) => _channelsByNumber.GetValueOrDefault(number); - public ChannelInfo GetChannelByName(string name) + public ChannelInfo? GetChannelByName(string name) => _channelsByName.GetValueOrDefault(name); public static string NormalizeName(string value) diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs index 1cac9cb963..bdab8c3e4b 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/ItemDataProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs index 32245f899e..1088638691 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/RecordingHelper.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs index 1efa90e256..6c52a9a73d 100644 --- a/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs +++ b/Emby.Server.Implementations/LiveTv/EmbyTV/TimerManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs index 9af65cabba..00d02873c5 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs index 6824aa4423..ebad4eddf1 100644 --- a/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs +++ b/Emby.Server.Implementations/LiveTv/Listings/XmlTvListingsProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs index 6af49dd45e..21e1409ac0 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvDtoService.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs index 1145d8aa1e..1f16289002 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs index 3a738fd5d2..ecd28097d3 100644 --- a/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs +++ b/Emby.Server.Implementations/LiveTv/LiveTvMediaSourceProvider.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index fbcd4ef372..00a37bb022 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs index 740cbb66ee..0f04531896 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/Channels.cs @@ -1,3 +1,5 @@ +#nullable disable + namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun { internal class Channels diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs index 09d77f8382..42068cd340 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/DiscoverResponse.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index bbac6e0551..c5700db715 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index a7fda1d72e..3016eeda24 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs index b16ccc561a..50a2d9abb3 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunUdpStream.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs index f8baf55da7..96a678c1d3 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/LiveStream.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index 4b170b2e4e..69035dac96 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs index 84d4161499..48a0c3cd37 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/M3uParser.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs index eeb2426f4f..137ed27e20 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/SharedHttpStream.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 220e423bf5..dd5dee1d16 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs index 031b5d2e72..8aaa1f7bbe 100644 --- a/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/Emby.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index 0781a0e333..1377286168 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs index 4e25768cf6..a8b18d2925 100644 --- a/Emby.Server.Implementations/Net/UdpSocket.cs +++ b/Emby.Server.Implementations/Net/UdpSocket.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Playlists/PlaylistManager.cs b/Emby.Server.Implementations/Playlists/PlaylistManager.cs index 2d1a559f16..9a1ca99467 100644 --- a/Emby.Server.Implementations/Playlists/PlaylistManager.cs +++ b/Emby.Server.Implementations/Playlists/PlaylistManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index 14df20936c..48281b75f6 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -1,5 +1,3 @@ -#nullable enable - using System; using System.Collections.Generic; using System.Globalization; diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs index 0259dc436b..7cfd1fced9 100644 --- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs +++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Concurrent; using System.Globalization; diff --git a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs index 101d9b5377..ccbd4289ea 100644 --- a/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs +++ b/Emby.Server.Implementations/ScheduledTasks/ScheduledTaskWorker.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs index af316e1083..4f0df75bf8 100644 --- a/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs +++ b/Emby.Server.Implementations/ScheduledTasks/TaskManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs index 2312c85d97..baeb86a221 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/ChapterImagesTask.cs @@ -140,8 +140,10 @@ namespace Emby.Server.Implementations.ScheduledTasks previouslyFailedImages.Add(key); var parentPath = Path.GetDirectoryName(failHistoryPath); - - Directory.CreateDirectory(parentPath); + if (parentPath != null) + { + Directory.CreateDirectory(parentPath); + } string text = string.Join('|', previouslyFailedImages); File.WriteAllText(failHistoryPath, text); diff --git a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs index 4abbf784b2..50ba9bc899 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Tasks/CleanActivityLogTask.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -75,4 +75,4 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks return Enumerable.Empty(); } } -} \ No newline at end of file +} diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs index 3b40320ab8..3b63536a42 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/DailyTrigger.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Model.Tasks; diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs index b04fd7c7e2..e13782fe02 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/IntervalTrigger.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Linq; using System.Threading; diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs index 7cd5493da8..ced14195bb 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/StartupTrigger.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs index 0c0ebec082..a67f940b75 100644 --- a/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs +++ b/Emby.Server.Implementations/ScheduledTasks/Triggers/WeeklyTrigger.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Threading; using MediaBrowser.Model.Tasks; diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index 76f863c951..30823ab8f5 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs index 27024e4e1c..8d8b82f0a4 100644 --- a/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs +++ b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs @@ -19,7 +19,9 @@ namespace Emby.Server.Implementations.Serialization new ConcurrentDictionary(); private static XmlSerializer GetSerializer(Type type) - => _serializers.GetOrAdd(type.FullName, _ => new XmlSerializer(type)); + => _serializers.GetOrAdd( + type.FullName ?? throw new ArgumentException($"Invalid type {type}."), + _ => new XmlSerializer(type)); /// /// Serializes to writer. @@ -38,7 +40,7 @@ namespace Emby.Server.Implementations.Serialization /// The type. /// The stream. /// System.Object. - public object DeserializeFromStream(Type type, Stream stream) + public object? DeserializeFromStream(Type type, Stream stream) { using (var reader = XmlReader.Create(stream)) { @@ -81,7 +83,7 @@ namespace Emby.Server.Implementations.Serialization /// The type. /// The file. /// System.Object. - public object DeserializeFromFile(Type type, string file) + public object? DeserializeFromFile(Type type, string file) { using (var stream = File.OpenRead(file)) { @@ -95,7 +97,7 @@ namespace Emby.Server.Implementations.Serialization /// The type. /// The buffer. /// System.Object. - public object DeserializeFromBytes(Type type, byte[] buffer) + public object? DeserializeFromBytes(Type type, byte[] buffer) { using (var stream = new MemoryStream(buffer, 0, buffer.Length, false, true)) { diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index 6844152ea5..ef467da7ed 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs index 39c369a01d..e9e3ca7f4b 100644 --- a/Emby.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/Emby.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Server.Implementations/Session/WebSocketController.cs b/Emby.Server.Implementations/Session/WebSocketController.cs index a653b58c2b..ed1dfca592 100644 --- a/Emby.Server.Implementations/Session/WebSocketController.cs +++ b/Emby.Server.Implementations/Session/WebSocketController.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 #pragma warning disable SA1600 -#nullable enable using System; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs index 60698e803d..2b0ab536f9 100644 --- a/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs +++ b/Emby.Server.Implementations/Sorting/AiredEpisodeOrderComparer.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { if (x == null) { diff --git a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs index 7657cc74e1..42e644970c 100644 --- a/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs +++ b/Emby.Server.Implementations/Sorting/AlbumArtistComparer.cs @@ -18,7 +18,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); } @@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.Sorting /// /// The x. /// System.String. - private static string GetValue(BaseItem x) + private static string? GetValue(BaseItem? x) { var audio = x as IHasAlbumArtist; diff --git a/Emby.Server.Implementations/Sorting/AlbumComparer.cs b/Emby.Server.Implementations/Sorting/AlbumComparer.cs index 7dfdd9ecff..1db3f5e9ca 100644 --- a/Emby.Server.Implementations/Sorting/AlbumComparer.cs +++ b/Emby.Server.Implementations/Sorting/AlbumComparer.cs @@ -17,7 +17,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); } @@ -27,7 +27,7 @@ namespace Emby.Server.Implementations.Sorting ///
/// The x. /// System.String. - private static string GetValue(BaseItem x) + private static string? GetValue(BaseItem? x) { var audio = x as Audio; diff --git a/Emby.Server.Implementations/Sorting/ArtistComparer.cs b/Emby.Server.Implementations/Sorting/ArtistComparer.cs index 756d3c5b6c..98bee3fd9f 100644 --- a/Emby.Server.Implementations/Sorting/ArtistComparer.cs +++ b/Emby.Server.Implementations/Sorting/ArtistComparer.cs @@ -15,7 +15,7 @@ namespace Emby.Server.Implementations.Sorting public string Name => ItemSortBy.Artist; /// - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase); } @@ -25,7 +25,7 @@ namespace Emby.Server.Implementations.Sorting ///
/// The x. /// System.String. - private static string GetValue(BaseItem x) + private static string? GetValue(BaseItem? x) { if (!(x is Audio audio)) { diff --git a/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs b/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs index 980954ba03..5f142fa4bb 100644 --- a/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs +++ b/Emby.Server.Implementations/Sorting/CommunityRatingComparer.cs @@ -21,7 +21,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { if (x == null) { diff --git a/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs b/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs index fa136c36d0..d20dedc2d4 100644 --- a/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs +++ b/Emby.Server.Implementations/Sorting/CriticRatingComparer.cs @@ -15,14 +15,14 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return GetValue(x).CompareTo(GetValue(y)); } - private static float GetValue(BaseItem x) + private static float GetValue(BaseItem? x) { - return x.CriticRating ?? 0; + return x?.CriticRating ?? 0; } /// diff --git a/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs b/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs index cbca300d2f..d3f10f78cb 100644 --- a/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs +++ b/Emby.Server.Implementations/Sorting/DateCreatedComparer.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { if (x == null) { diff --git a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs index 03ff19d21c..b1cb123ce1 100644 --- a/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs +++ b/Emby.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs index 16bd2aff86..08a44319f2 100644 --- a/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs +++ b/Emby.Server.Implementations/Sorting/DatePlayedComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using Jellyfin.Data.Entities; using MediaBrowser.Controller.Entities; diff --git a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs index 0c4e82d011..73e628cf75 100644 --- a/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs +++ b/Emby.Server.Implementations/Sorting/IsFavoriteOrLikeComparer.cs @@ -1,3 +1,4 @@ +#nullable disable #pragma warning disable CS1591 using Jellyfin.Data.Entities; diff --git a/Emby.Server.Implementations/Sorting/IsFolderComparer.cs b/Emby.Server.Implementations/Sorting/IsFolderComparer.cs index a35192eff8..3c5ddeefaa 100644 --- a/Emby.Server.Implementations/Sorting/IsFolderComparer.cs +++ b/Emby.Server.Implementations/Sorting/IsFolderComparer.cs @@ -20,7 +20,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return GetValue(x).CompareTo(GetValue(y)); } @@ -30,9 +30,9 @@ namespace Emby.Server.Implementations.Sorting /// /// The x. /// System.String. - private static int GetValue(BaseItem x) + private static int GetValue(BaseItem? x) { - return x.IsFolder ? 0 : 1; + return x?.IsFolder ?? true ? 0 : 1; } } } diff --git a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs index d95948406f..7d77a8bc5a 100644 --- a/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs +++ b/Emby.Server.Implementations/Sorting/IsPlayedComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using Jellyfin.Data.Entities; diff --git a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs index 1632c5a7a9..926835f906 100644 --- a/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs +++ b/Emby.Server.Implementations/Sorting/IsUnplayedComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using Jellyfin.Data.Entities; diff --git a/Emby.Server.Implementations/Sorting/NameComparer.cs b/Emby.Server.Implementations/Sorting/NameComparer.cs index da020d8d8e..4de81a69e3 100644 --- a/Emby.Server.Implementations/Sorting/NameComparer.cs +++ b/Emby.Server.Implementations/Sorting/NameComparer.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { if (x == null) { diff --git a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs index 76bb798b5f..a81f78ebfc 100644 --- a/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs +++ b/Emby.Server.Implementations/Sorting/OfficialRatingComparer.cs @@ -29,7 +29,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { if (x == null) { diff --git a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs index 5c28303229..04e4865cbf 100644 --- a/Emby.Server.Implementations/Sorting/PlayCountComparer.cs +++ b/Emby.Server.Implementations/Sorting/PlayCountComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + using Jellyfin.Data.Entities; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; diff --git a/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs b/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs index 92ac04dc66..c98f97bf1e 100644 --- a/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs +++ b/Emby.Server.Implementations/Sorting/PremiereDateComparer.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return GetDate(x).CompareTo(GetDate(y)); } @@ -26,8 +26,13 @@ namespace Emby.Server.Implementations.Sorting ///
/// The x. /// DateTime. - private static DateTime GetDate(BaseItem x) + private static DateTime GetDate(BaseItem? x) { + if (x == null) + { + return DateTime.MinValue; + } + if (x.PremiereDate.HasValue) { return x.PremiereDate.Value; diff --git a/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs b/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs index e2857df0b9..df9f9957d6 100644 --- a/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs +++ b/Emby.Server.Implementations/Sorting/ProductionYearComparer.cs @@ -15,7 +15,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return GetValue(x).CompareTo(GetValue(y)); } @@ -25,8 +25,13 @@ namespace Emby.Server.Implementations.Sorting ///
/// The x. /// DateTime. - private static int GetValue(BaseItem x) + private static int GetValue(BaseItem? x) { + if (x == null) + { + return 0; + } + if (x.ProductionYear.HasValue) { return x.ProductionYear.Value; diff --git a/Emby.Server.Implementations/Sorting/RandomComparer.cs b/Emby.Server.Implementations/Sorting/RandomComparer.cs index 7739d04182..af3bc27508 100644 --- a/Emby.Server.Implementations/Sorting/RandomComparer.cs +++ b/Emby.Server.Implementations/Sorting/RandomComparer.cs @@ -16,7 +16,7 @@ namespace Emby.Server.Implementations.Sorting /// The x. /// The y. /// System.Int32. - public int Compare(BaseItem x, BaseItem y) + public int Compare(BaseItem? x, BaseItem? y) { return Guid.NewGuid().CompareTo(Guid.NewGuid()); } diff --git a/Emby.Server.Implementations/Sorting/RuntimeComparer.cs b/Emby.Server.Implementations/Sorting/RuntimeComparer.cs index dde44333d5..1293153031 100644 --- a/Emby.Server.Implementations/Sorting/RuntimeComparer.cs +++ b/Emby.Server.Implementations/Sorting/RuntimeComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Sorting; diff --git a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs index b9205ee076..4123a59f8b 100644 --- a/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs +++ b/Emby.Server.Implementations/Sorting/SeriesSortNameComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Sorting/SortNameComparer.cs b/Emby.Server.Implementations/Sorting/SortNameComparer.cs index f745e193b4..8d30716d39 100644 --- a/Emby.Server.Implementations/Sorting/SortNameComparer.cs +++ b/Emby.Server.Implementations/Sorting/SortNameComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Sorting; diff --git a/Emby.Server.Implementations/Sorting/StartDateComparer.cs b/Emby.Server.Implementations/Sorting/StartDateComparer.cs index 558a3d3513..c3df7c47e6 100644 --- a/Emby.Server.Implementations/Sorting/StartDateComparer.cs +++ b/Emby.Server.Implementations/Sorting/StartDateComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Sorting/StudioComparer.cs b/Emby.Server.Implementations/Sorting/StudioComparer.cs index 5766dc542b..01445c5254 100644 --- a/Emby.Server.Implementations/Sorting/StudioComparer.cs +++ b/Emby.Server.Implementations/Sorting/StudioComparer.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/SyncPlay/Group.cs b/Emby.Server.Implementations/SyncPlay/Group.cs index 7c2ad2477a..12efff261b 100644 --- a/Emby.Server.Implementations/SyncPlay/Group.cs +++ b/Emby.Server.Implementations/SyncPlay/Group.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Linq; diff --git a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs index 72c0a838e2..993456196d 100644 --- a/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs +++ b/Emby.Server.Implementations/SyncPlay/SyncPlayManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/Emby.Server.Implementations/TV/TVSeriesManager.cs b/Emby.Server.Implementations/TV/TVSeriesManager.cs index 829df64bfb..a837f09cac 100644 --- a/Emby.Server.Implementations/TV/TVSeriesManager.cs +++ b/Emby.Server.Implementations/TV/TVSeriesManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #pragma warning disable CS1591 using System; diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs index db5265e79d..750f001680 100644 --- a/Emby.Server.Implementations/Udp/UdpServer.cs +++ b/Emby.Server.Implementations/Udp/UdpServer.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Net; using System.Net.Sockets; diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index 653b1381b9..2351b7d8c6 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -1,3 +1,5 @@ +#nullable disable + #nullable enable using System; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index b4154b361e..45559fce9a 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1762,9 +1762,9 @@ namespace Jellyfin.Api.Controllers private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem) { - var folder = Path.GetDirectoryName(playlist); + var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", nameof(playlist)); - var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty; + var filePrefix = Path.GetFileNameWithoutExtension(playlist); try { diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs index 0879cbd18f..7cb0159936 100644 --- a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs +++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs @@ -380,7 +380,9 @@ namespace Jellyfin.Api.Helpers /// The output file path. private void DeleteHlsPartialStreamFiles(string outputFilePath) { - var directory = Path.GetDirectoryName(outputFilePath); + var directory = Path.GetDirectoryName(outputFilePath) + ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputFilePath)); + var name = Path.GetFileNameWithoutExtension(outputFilePath); var filesToDelete = _fileSystem.GetFilePaths(directory) diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs index e33e552edb..7b32d76ba7 100644 --- a/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs +++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingThrottler.cs @@ -145,7 +145,8 @@ namespace Jellyfin.Api.Models.PlaybackDtos var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0; var downloadPositionTicks = job.DownloadPositionTicks ?? 0; - var path = job.Path; + var path = job.Path ?? throw new ArgumentException("Path can't be null."); + var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks; if (downloadPositionTicks > 0 && transcodingPositionTicks > 0) diff --git a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs index a15a381772..96bd2ccc40 100644 --- a/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs +++ b/Jellyfin.Server/Migrations/Routines/MigrateUserDb.cs @@ -82,11 +82,14 @@ namespace Jellyfin.Server.Migrations.Routines var userDataDir = Path.Combine(_paths.UserConfigurationDirectoryPath, mockup.Name); - var config = File.Exists(Path.Combine(userDataDir, "config.xml")) - ? (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), Path.Combine(userDataDir, "config.xml")) + var configPath = Path.Combine(userDataDir, "config.xml"); + var config = File.Exists(configPath) + ? (UserConfiguration?)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), configPath) ?? new UserConfiguration() : new UserConfiguration(); - var policy = File.Exists(Path.Combine(userDataDir, "policy.xml")) - ? (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), Path.Combine(userDataDir, "policy.xml")) + + var policyPath = Path.Combine(userDataDir, "policy.xml"); + var policy = File.Exists(policyPath) + ? (UserPolicy?)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), policyPath) ?? new UserPolicy() : new UserPolicy(); policy.AuthenticationProviderId = policy.AuthenticationProviderId?.Replace( "Emby.Server.Implementations.Library", diff --git a/MediaBrowser.Controller/Extensions/StringExtensions.cs b/MediaBrowser.Controller/Extensions/StringExtensions.cs index 48bd9522a8..1853896eec 100644 --- a/MediaBrowser.Controller/Extensions/StringExtensions.cs +++ b/MediaBrowser.Controller/Extensions/StringExtensions.cs @@ -1,6 +1,7 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; diff --git a/MediaBrowser.Controller/Net/ISessionContext.cs b/MediaBrowser.Controller/Net/ISessionContext.cs index a60dc2ea19..6b896b41f4 100644 --- a/MediaBrowser.Controller/Net/ISessionContext.cs +++ b/MediaBrowser.Controller/Net/ISessionContext.cs @@ -10,10 +10,10 @@ namespace MediaBrowser.Controller.Net { SessionInfo GetSession(object requestContext); - User GetUser(object requestContext); + User? GetUser(object requestContext); SessionInfo GetSession(HttpContext requestContext); - User GetUser(HttpContext requestContext); + User? GetUser(HttpContext requestContext); } } diff --git a/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs b/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs index 727cbe639c..07fe1ea8a9 100644 --- a/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs +++ b/MediaBrowser.Controller/Sorting/IBaseItemComparer.cs @@ -6,7 +6,7 @@ namespace MediaBrowser.Controller.Sorting /// /// Interface IBaseItemComparer. /// - public interface IBaseItemComparer : IComparer + public interface IBaseItemComparer : IComparer { /// /// Gets the name. diff --git a/MediaBrowser.Model/IO/IFileSystem.cs b/MediaBrowser.Model/IO/IFileSystem.cs index e5c26430a8..be4f1e16b5 100644 --- a/MediaBrowser.Model/IO/IFileSystem.cs +++ b/MediaBrowser.Model/IO/IFileSystem.cs @@ -1,4 +1,3 @@ -#nullable disable #pragma warning disable CS1591 using System; @@ -25,7 +24,7 @@ namespace MediaBrowser.Model.IO /// /// The filename. /// System.String. - string ResolveShortcut(string filename); + string? ResolveShortcut(string filename); /// /// Creates the shortcut. @@ -160,7 +159,7 @@ namespace MediaBrowser.Model.IO /// All found files. IEnumerable GetFiles(string path, bool recursive = false); - IEnumerable GetFiles(string path, IReadOnlyList extensions, bool enableCaseSensitiveExtensions, bool recursive); + IEnumerable GetFiles(string path, IReadOnlyList? extensions, bool enableCaseSensitiveExtensions, bool recursive); /// /// Gets the file system entries. @@ -186,7 +185,7 @@ namespace MediaBrowser.Model.IO /// IEnumerable<System.String>. IEnumerable GetFilePaths(string path, bool recursive = false); - IEnumerable GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive); + IEnumerable GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive); /// /// Gets the file system entry paths. diff --git a/MediaBrowser.Model/IO/IShortcutHandler.cs b/MediaBrowser.Model/IO/IShortcutHandler.cs index 14d5c4b62f..2c364a962f 100644 --- a/MediaBrowser.Model/IO/IShortcutHandler.cs +++ b/MediaBrowser.Model/IO/IShortcutHandler.cs @@ -15,7 +15,7 @@ namespace MediaBrowser.Model.IO /// /// The shortcut path. /// System.String. - string Resolve(string shortcutPath); + string? Resolve(string shortcutPath); /// /// Creates the specified shortcut path. diff --git a/MediaBrowser.Model/IO/IStreamHelper.cs b/MediaBrowser.Model/IO/IStreamHelper.cs index 0e09db16e8..f900da5567 100644 --- a/MediaBrowser.Model/IO/IStreamHelper.cs +++ b/MediaBrowser.Model/IO/IStreamHelper.cs @@ -9,7 +9,7 @@ namespace MediaBrowser.Model.IO { public interface IStreamHelper { - Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken); + Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action? onStarted, CancellationToken cancellationToken); Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken); diff --git a/MediaBrowser.Model/Tasks/ITaskTrigger.cs b/MediaBrowser.Model/Tasks/ITaskTrigger.cs index cbd60cca18..db9fba6964 100644 --- a/MediaBrowser.Model/Tasks/ITaskTrigger.cs +++ b/MediaBrowser.Model/Tasks/ITaskTrigger.cs @@ -11,7 +11,7 @@ namespace MediaBrowser.Model.Tasks /// /// Fires when the trigger condition is satisfied and the task should run. /// - event EventHandler Triggered; + event EventHandler? Triggered; /// /// Gets or sets the options of this task. From 9b8eb1ba53b8fc18b32217d4e1208b7b9604b644 Mon Sep 17 00:00:00 2001 From: Bond_009 Date: Fri, 21 May 2021 13:43:49 +0200 Subject: [PATCH 1682/1930] Remove dead code --- MediaBrowser.Controller/Library/Profiler.cs | 85 ----------- MediaBrowser.Model/Querying/EpisodeQuery.cs | 75 ---------- .../Querying/MovieRecommendationQuery.cs | 47 ------ .../Querying/UpcomingEpisodesQuery.cs | 64 --------- MediaBrowser.Model/Sync/SyncCategory.cs | 22 --- MediaBrowser.Model/Sync/SyncJob.cs | 135 ------------------ MediaBrowser.Model/Sync/SyncJobStatus.cs | 15 -- MediaBrowser.Model/Sync/SyncTarget.cs | 20 --- MediaBrowser.Model/Users/UserAction.cs | 24 ---- 9 files changed, 487 deletions(-) delete mode 100644 MediaBrowser.Controller/Library/Profiler.cs delete mode 100644 MediaBrowser.Model/Querying/EpisodeQuery.cs delete mode 100644 MediaBrowser.Model/Querying/MovieRecommendationQuery.cs delete mode 100644 MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs delete mode 100644 MediaBrowser.Model/Sync/SyncCategory.cs delete mode 100644 MediaBrowser.Model/Sync/SyncJob.cs delete mode 100644 MediaBrowser.Model/Sync/SyncJobStatus.cs delete mode 100644 MediaBrowser.Model/Sync/SyncTarget.cs delete mode 100644 MediaBrowser.Model/Users/UserAction.cs diff --git a/MediaBrowser.Controller/Library/Profiler.cs b/MediaBrowser.Controller/Library/Profiler.cs deleted file mode 100644 index 583fd73c3a..0000000000 --- a/MediaBrowser.Controller/Library/Profiler.cs +++ /dev/null @@ -1,85 +0,0 @@ -#nullable disable - -using System; -using System.Diagnostics; -using System.Globalization; -using Microsoft.Extensions.Logging; - -namespace MediaBrowser.Controller.Library -{ - /// - /// Class Profiler. - /// - public class Profiler : IDisposable - { - /// - /// The name. - /// - private readonly string _name; - - /// - /// The stopwatch. - /// - private readonly Stopwatch _stopwatch; - - /// - /// The _logger. - /// - private readonly ILogger _logger; - - /// - /// Initializes a new instance of the class. - /// - /// The name. - /// The logger. - public Profiler(string name, ILogger logger) - { - this._name = name; - - _logger = logger; - - _stopwatch = new Stopwatch(); - _stopwatch.Start(); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - _stopwatch.Stop(); - string message; - if (_stopwatch.ElapsedMilliseconds > 300000) - { - message = string.Format( - CultureInfo.InvariantCulture, - "{0} took {1} minutes.", - _name, - ((float)_stopwatch.ElapsedMilliseconds / 60000).ToString("F", CultureInfo.InvariantCulture)); - } - else - { - message = string.Format( - CultureInfo.InvariantCulture, - "{0} took {1} seconds.", - _name, - ((float)_stopwatch.ElapsedMilliseconds / 1000).ToString("#0.000", CultureInfo.InvariantCulture)); - } - - _logger.LogInformation(message); - } - } - } -} diff --git a/MediaBrowser.Model/Querying/EpisodeQuery.cs b/MediaBrowser.Model/Querying/EpisodeQuery.cs deleted file mode 100644 index 56a7f33201..0000000000 --- a/MediaBrowser.Model/Querying/EpisodeQuery.cs +++ /dev/null @@ -1,75 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; - -namespace MediaBrowser.Model.Querying -{ - public class EpisodeQuery - { - public EpisodeQuery() - { - Fields = Array.Empty(); - } - - /// - /// Gets or sets the user identifier. - /// - /// The user identifier. - public string UserId { get; set; } - - /// - /// Gets or sets the season identifier. - /// - /// The season identifier. - public string SeasonId { get; set; } - - /// - /// Gets or sets the series identifier. - /// - /// The series identifier. - public string SeriesId { get; set; } - - /// - /// Gets or sets a value indicating whether this instance is missing. - /// - /// null if [is missing] contains no value, true if [is missing]; otherwise, false. - public bool? IsMissing { get; set; } - - /// - /// Gets or sets a value indicating whether this instance is virtual unaired. - /// - /// null if [is virtual unaired] contains no value, true if [is virtual unaired]; otherwise, false. - public bool? IsVirtualUnaired { get; set; } - - /// - /// Gets or sets the season number. - /// - /// The season number. - public int? SeasonNumber { get; set; } - - /// - /// Gets or sets the fields. - /// - /// The fields. - public ItemFields[] Fields { get; set; } - - /// - /// Gets or sets the start index. - /// - /// The start index. - public int? StartIndex { get; set; } - - /// - /// Gets or sets the limit. - /// - /// The limit. - public int? Limit { get; set; } - - /// - /// Gets or sets the start item identifier. - /// - /// The start item identifier. - public string StartItemId { get; set; } - } -} diff --git a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs b/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs deleted file mode 100644 index b800f5de5f..0000000000 --- a/MediaBrowser.Model/Querying/MovieRecommendationQuery.cs +++ /dev/null @@ -1,47 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; - -namespace MediaBrowser.Model.Querying -{ - public class MovieRecommendationQuery - { - public MovieRecommendationQuery() - { - ItemLimit = 10; - CategoryLimit = 6; - Fields = Array.Empty(); - } - - /// - /// Gets or sets the user identifier. - /// - /// The user identifier. - public string UserId { get; set; } - - /// - /// Gets or sets the parent identifier. - /// - /// The parent identifier. - public string ParentId { get; set; } - - /// - /// Gets or sets the item limit. - /// - /// The item limit. - public int ItemLimit { get; set; } - - /// - /// Gets or sets the category limit. - /// - /// The category limit. - public int CategoryLimit { get; set; } - - /// - /// Gets or sets the fields. - /// - /// The fields. - public ItemFields[] Fields { get; set; } - } -} diff --git a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs b/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs deleted file mode 100644 index 2cf0f0d5f8..0000000000 --- a/MediaBrowser.Model/Querying/UpcomingEpisodesQuery.cs +++ /dev/null @@ -1,64 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; -using MediaBrowser.Model.Entities; - -namespace MediaBrowser.Model.Querying -{ - public class UpcomingEpisodesQuery - { - public UpcomingEpisodesQuery() - { - EnableImageTypes = Array.Empty(); - } - - /// - /// Gets or sets the user id. - /// - /// The user id. - public string UserId { get; set; } - - /// - /// Gets or sets the parent identifier. - /// - /// The parent identifier. - public string ParentId { get; set; } - - /// - /// Gets or sets the start index. Use for paging. - /// - /// The start index. - public int? StartIndex { get; set; } - - /// - /// Gets or sets the maximum number of items to return. - /// - /// The limit. - public int? Limit { get; set; } - - /// - /// Gets or sets the fields to return within the items, in addition to basic information. - /// - /// The fields. - public ItemFields[] Fields { get; set; } - - /// - /// Gets or sets a value indicating whether [enable images]. - /// - /// null if [enable images] contains no value, true if [enable images]; otherwise, false. - public bool? EnableImages { get; set; } - - /// - /// Gets or sets the image type limit. - /// - /// The image type limit. - public int? ImageTypeLimit { get; set; } - - /// - /// Gets or sets the enable image types. - /// - /// The enable image types. - public ImageType[] EnableImageTypes { get; set; } - } -} diff --git a/MediaBrowser.Model/Sync/SyncCategory.cs b/MediaBrowser.Model/Sync/SyncCategory.cs deleted file mode 100644 index 1248c2f739..0000000000 --- a/MediaBrowser.Model/Sync/SyncCategory.cs +++ /dev/null @@ -1,22 +0,0 @@ -#pragma warning disable CS1591 - -namespace MediaBrowser.Model.Sync -{ - public enum SyncCategory - { - /// - /// The latest. - /// - Latest = 0, - - /// - /// The next up. - /// - NextUp = 1, - - /// - /// The resume. - /// - Resume = 2 - } -} diff --git a/MediaBrowser.Model/Sync/SyncJob.cs b/MediaBrowser.Model/Sync/SyncJob.cs deleted file mode 100644 index 3e396e5d13..0000000000 --- a/MediaBrowser.Model/Sync/SyncJob.cs +++ /dev/null @@ -1,135 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; - -namespace MediaBrowser.Model.Sync -{ - public class SyncJob - { - public SyncJob() - { - RequestedItemIds = Array.Empty(); - } - - /// - /// Gets or sets the identifier. - /// - /// The identifier. - public string Id { get; set; } - - /// - /// Gets or sets the device identifier. - /// - /// The device identifier. - public string TargetId { get; set; } - - /// - /// Gets or sets the name of the target. - /// - /// The name of the target. - public string TargetName { get; set; } - - /// - /// Gets or sets the quality. - /// - /// The quality. - public string Quality { get; set; } - - /// - /// Gets or sets the bitrate. - /// - /// The bitrate. - public int? Bitrate { get; set; } - - /// - /// Gets or sets the profile. - /// - /// The profile. - public string Profile { get; set; } - - /// - /// Gets or sets the category. - /// - /// The category. - public SyncCategory? Category { get; set; } - - /// - /// Gets or sets the parent identifier. - /// - /// The parent identifier. - public string ParentId { get; set; } - - /// - /// Gets or sets the current progress. - /// - /// The current progress. - public double? Progress { get; set; } - - /// - /// Gets or sets the name. - /// - /// The name. - public string Name { get; set; } - - /// - /// Gets or sets the status. - /// - /// The status. - public SyncJobStatus Status { get; set; } - - /// - /// Gets or sets the user identifier. - /// - /// The user identifier. - public string UserId { get; set; } - - /// - /// Gets or sets a value indicating whether [unwatched only]. - /// - /// true if [unwatched only]; otherwise, false. - public bool UnwatchedOnly { get; set; } - - /// - /// Gets or sets a value indicating whether [synchronize new content]. - /// - /// true if [synchronize new content]; otherwise, false. - public bool SyncNewContent { get; set; } - - /// - /// Gets or sets the item limit. - /// - /// The item limit. - public int? ItemLimit { get; set; } - - /// - /// Gets or sets the requested item ids. - /// - /// The requested item ids. - public Guid[] RequestedItemIds { get; set; } - - /// - /// Gets or sets the date created. - /// - /// The date created. - public DateTime DateCreated { get; set; } - - /// - /// Gets or sets the date last modified. - /// - /// The date last modified. - public DateTime DateLastModified { get; set; } - - /// - /// Gets or sets the item count. - /// - /// The item count. - public int ItemCount { get; set; } - - public string ParentName { get; set; } - - public string PrimaryImageItemId { get; set; } - - public string PrimaryImageTag { get; set; } - } -} diff --git a/MediaBrowser.Model/Sync/SyncJobStatus.cs b/MediaBrowser.Model/Sync/SyncJobStatus.cs deleted file mode 100644 index 226a47d4c0..0000000000 --- a/MediaBrowser.Model/Sync/SyncJobStatus.cs +++ /dev/null @@ -1,15 +0,0 @@ -#pragma warning disable CS1591 - -namespace MediaBrowser.Model.Sync -{ - public enum SyncJobStatus - { - Queued = 0, - Converting = 1, - ReadyToTransfer = 2, - Transferring = 3, - Completed = 4, - CompletedWithError = 5, - Failed = 6 - } -} diff --git a/MediaBrowser.Model/Sync/SyncTarget.cs b/MediaBrowser.Model/Sync/SyncTarget.cs deleted file mode 100644 index 9e6bbbc009..0000000000 --- a/MediaBrowser.Model/Sync/SyncTarget.cs +++ /dev/null @@ -1,20 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -namespace MediaBrowser.Model.Sync -{ - public class SyncTarget - { - /// - /// Gets or sets the name. - /// - /// The name. - public string Name { get; set; } - - /// - /// Gets or sets the identifier. - /// - /// The identifier. - public string Id { get; set; } - } -} diff --git a/MediaBrowser.Model/Users/UserAction.cs b/MediaBrowser.Model/Users/UserAction.cs deleted file mode 100644 index 7646db4a82..0000000000 --- a/MediaBrowser.Model/Users/UserAction.cs +++ /dev/null @@ -1,24 +0,0 @@ -#nullable disable -#pragma warning disable CS1591 - -using System; - -namespace MediaBrowser.Model.Users -{ - public class UserAction - { - public string Id { get; set; } - - public string ServerId { get; set; } - - public Guid UserId { get; set; } - - public Guid ItemId { get; set; } - - public UserActionType Type { get; set; } - - public DateTime Date { get; set; } - - public long? PositionTicks { get; set; } - } -} From d6ab9ab328a661be079035e977b6df3e38774bac Mon Sep 17 00:00:00 2001 From: TokieSan Date: Thu, 20 May 2021 12:30:56 +0000 Subject: [PATCH 1683/1930] Translated using Weblate (Arabic) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/ar/ --- Emby.Server.Implementations/Localization/Core/ar.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Emby.Server.Implementations/Localization/Core/ar.json b/Emby.Server.Implementations/Localization/Core/ar.json index 9f84d3a3cf..3d6e159b13 100644 --- a/Emby.Server.Implementations/Localization/Core/ar.json +++ b/Emby.Server.Implementations/Localization/Core/ar.json @@ -116,5 +116,7 @@ "TaskCleanLogs": "حذف دليل السجل", "TaskCleanActivityLogDescription": "يحذف سجل الأنشطة الأقدم من الوقت الموضوع.", "TaskCleanActivityLog": "حذف سجل الأنشطة", - "Default": "الإعدادات الافتراضية" + "Default": "الإعدادات الافتراضية", + "Undefined": "غير معرف", + "Forced": "ملحقة" } From 19e2e0b7b81c2c5734e947e4d6fa7b57bd4163e3 Mon Sep 17 00:00:00 2001 From: Marius Lindvall Date: Thu, 20 May 2021 11:58:30 +0000 Subject: [PATCH 1684/1930] Translated using Weblate (Norwegian Nynorsk) Translation: Jellyfin/Jellyfin Translate-URL: https://translate.jellyfin.org/projects/jellyfin/jellyfin-core/nn/ --- Emby.Server.Implementations/Localization/Core/nn.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Emby.Server.Implementations/Localization/Core/nn.json b/Emby.Server.Implementations/Localization/Core/nn.json index f5683f35b7..32d4f3a8b6 100644 --- a/Emby.Server.Implementations/Localization/Core/nn.json +++ b/Emby.Server.Implementations/Localization/Core/nn.json @@ -29,9 +29,9 @@ "Collections": "Samlingar", "ChapterNameValue": "Kapittel {0}", "Channels": "Kanalar", - "CameraImageUploadedFrom": "Eit nytt kamera bilete har blitt lasta opp frå {0}", + "CameraImageUploadedFrom": "Eit nytt kamerabilete har blitt lasta opp frå {0}", "Books": "Bøker", - "AuthenticationSucceededWithUserName": "{0} Har logga inn", + "AuthenticationSucceededWithUserName": "{0} har logga inn", "Artists": "Artistar", "Application": "Program", "AppDeviceValues": "App: {0}, Eining: {1}", From 3b59064f972d3435f1e4fe1859b85866f400d7df Mon Sep 17 00:00:00 2001 From: cvium Date: Fri, 21 May 2021 19:35:00 +0200 Subject: [PATCH 1685/1930] Bump SQLitePCL.pretty.netstandard to 3.0.1 --- .../Data/ManagedConnection.cs | 4 +-- .../Data/SqliteExtensions.cs | 33 +++++++++---------- .../Data/SqliteItemRepository.cs | 14 ++++---- .../Data/SqliteUserDataRepository.cs | 2 +- .../Emby.Server.Implementations.csproj | 2 +- .../Security/AuthenticationRepository.cs | 2 +- 6 files changed, 28 insertions(+), 29 deletions(-) diff --git a/Emby.Server.Implementations/Data/ManagedConnection.cs b/Emby.Server.Implementations/Data/ManagedConnection.cs index 10c6f837e6..afc8966f9c 100644 --- a/Emby.Server.Implementations/Data/ManagedConnection.cs +++ b/Emby.Server.Implementations/Data/ManagedConnection.cs @@ -54,12 +54,12 @@ namespace Emby.Server.Implementations.Data return _db.RunInTransaction(action, mode); } - public IEnumerable> Query(string sql) + public IEnumerable> Query(string sql) { return _db.Query(sql); } - public IEnumerable> Query(string sql, params object[] values) + public IEnumerable> Query(string sql, params object[] values) { return _db.Query(sql, values); } diff --git a/Emby.Server.Implementations/Data/SqliteExtensions.cs b/Emby.Server.Implementations/Data/SqliteExtensions.cs index e532825af5..3289e76098 100644 --- a/Emby.Server.Implementations/Data/SqliteExtensions.cs +++ b/Emby.Server.Implementations/Data/SqliteExtensions.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using SQLitePCL.pretty; @@ -66,7 +65,7 @@ namespace Emby.Server.Implementations.Data }); } - public static Guid ReadGuidFromBlob(this IResultSetValue result) + public static Guid ReadGuidFromBlob(this ResultSetValue result) { return new Guid(result.ToBlob()); } @@ -87,7 +86,7 @@ namespace Emby.Server.Implementations.Data private static string GetDateTimeKindFormat(DateTimeKind kind) => (kind == DateTimeKind.Utc) ? DatetimeFormatUtc : DatetimeFormatLocal; - public static DateTime ReadDateTime(this IResultSetValue result) + public static DateTime ReadDateTime(this ResultSetValue result) { var dateText = result.ToString(); @@ -98,7 +97,7 @@ namespace Emby.Server.Implementations.Data DateTimeStyles.None).ToUniversalTime(); } - public static bool TryReadDateTime(this IReadOnlyList reader, int index, out DateTime result) + public static bool TryReadDateTime(this IReadOnlyList reader, int index, out DateTime result) { var item = reader[index]; if (item.IsDbNull()) @@ -119,7 +118,7 @@ namespace Emby.Server.Implementations.Data return false; } - public static bool TryGetGuid(this IReadOnlyList reader, int index, out Guid result) + public static bool TryGetGuid(this IReadOnlyList reader, int index, out Guid result) { var item = reader[index]; if (item.IsDbNull()) @@ -132,17 +131,17 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool IsDbNull(this IResultSetValue result) + public static bool IsDbNull(this ResultSetValue result) { return result.SQLiteType == SQLiteType.Null; } - public static string GetString(this IReadOnlyList result, int index) + public static string GetString(this IReadOnlyList result, int index) { return result[index].ToString(); } - public static bool TryGetString(this IReadOnlyList reader, int index, out string result) + public static bool TryGetString(this IReadOnlyList reader, int index, out string result) { result = null; var item = reader[index]; @@ -155,12 +154,12 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool GetBoolean(this IReadOnlyList result, int index) + public static bool GetBoolean(this IReadOnlyList result, int index) { return result[index].ToBool(); } - public static bool TryGetBoolean(this IReadOnlyList reader, int index, out bool result) + public static bool TryGetBoolean(this IReadOnlyList reader, int index, out bool result) { var item = reader[index]; if (item.IsDbNull()) @@ -173,7 +172,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetInt32(this IReadOnlyList reader, int index, out int result) + public static bool TryGetInt32(this IReadOnlyList reader, int index, out int result) { var item = reader[index]; if (item.IsDbNull()) @@ -186,12 +185,12 @@ namespace Emby.Server.Implementations.Data return true; } - public static long GetInt64(this IReadOnlyList result, int index) + public static long GetInt64(this IReadOnlyList result, int index) { return result[index].ToInt64(); } - public static bool TryGetInt64(this IReadOnlyList reader, int index, out long result) + public static bool TryGetInt64(this IReadOnlyList reader, int index, out long result) { var item = reader[index]; if (item.IsDbNull()) @@ -204,7 +203,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetSingle(this IReadOnlyList reader, int index, out float result) + public static bool TryGetSingle(this IReadOnlyList reader, int index, out float result) { var item = reader[index]; if (item.IsDbNull()) @@ -217,7 +216,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static bool TryGetDouble(this IReadOnlyList reader, int index, out double result) + public static bool TryGetDouble(this IReadOnlyList reader, int index, out double result) { var item = reader[index]; if (item.IsDbNull()) @@ -230,7 +229,7 @@ namespace Emby.Server.Implementations.Data return true; } - public static Guid GetGuid(this IReadOnlyList result, int index) + public static Guid GetGuid(this IReadOnlyList result, int index) { return result[index].ReadGuidFromBlob(); } @@ -442,7 +441,7 @@ namespace Emby.Server.Implementations.Data } } - public static IEnumerable> ExecuteQuery(this IStatement statement) + public static IEnumerable> ExecuteQuery(this IStatement statement) { while (statement.MoveNext()) { diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 5b4bbb3395..2d060dd652 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -1284,12 +1284,12 @@ namespace Emby.Server.Implementations.Data return true; } - private BaseItem GetItem(IReadOnlyList reader, InternalItemsQuery query) + private BaseItem GetItem(IReadOnlyList reader, InternalItemsQuery query) { return GetItem(reader, query, HasProgramAttributes(query), HasEpisodeAttributes(query), HasServiceName(query), HasStartDate(query), HasTrailerTypes(query), HasArtistFields(query), HasSeriesFields(query)); } - private BaseItem GetItem(IReadOnlyList reader, InternalItemsQuery query, bool enableProgramAttributes, bool hasEpisodeAttributes, bool hasServiceName, bool queryHasStartDate, bool hasTrailerTypes, bool hasArtistFields, bool hasSeriesFields) + private BaseItem GetItem(IReadOnlyList reader, InternalItemsQuery query, bool enableProgramAttributes, bool hasEpisodeAttributes, bool hasServiceName, bool queryHasStartDate, bool hasTrailerTypes, bool hasArtistFields, bool hasSeriesFields) { var typeString = reader.GetString(0); @@ -1929,7 +1929,7 @@ namespace Emby.Server.Implementations.Data /// The reader. /// The item. /// ChapterInfo. - private ChapterInfo GetChapter(IReadOnlyList reader, BaseItem item) + private ChapterInfo GetChapter(IReadOnlyList reader, BaseItem item) { var chapter = new ChapterInfo { @@ -5503,7 +5503,7 @@ AND Type = @InternalPersonType)"); return result; } - private static ItemCounts GetItemCounts(IReadOnlyList reader, int countStartColumn, string[] typesToCount) + private static ItemCounts GetItemCounts(IReadOnlyList reader, int countStartColumn, string[] typesToCount) { var counts = new ItemCounts(); @@ -5734,7 +5734,7 @@ AND Type = @InternalPersonType)"); } } - private PersonInfo GetPerson(IReadOnlyList reader) + private PersonInfo GetPerson(IReadOnlyList reader) { var item = new PersonInfo { @@ -5941,7 +5941,7 @@ AND Type = @InternalPersonType)"); /// /// The reader. /// ChapterInfo. - private MediaStream GetMediaStream(IReadOnlyList reader) + private MediaStream GetMediaStream(IReadOnlyList reader) { var item = new MediaStream { @@ -6242,7 +6242,7 @@ AND Type = @InternalPersonType)"); /// /// The reader. /// MediaAttachment. - private MediaAttachment GetMediaAttachment(IReadOnlyList reader) + private MediaAttachment GetMediaAttachment(IReadOnlyList reader) { var item = new MediaAttachment { diff --git a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs index 1756bcae08..ef9af1dcd0 100644 --- a/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteUserDataRepository.cs @@ -350,7 +350,7 @@ namespace Emby.Server.Implementations.Data /// Read a row from the specified reader into the provided userData object. /// /// - private UserItemData ReadRow(IReadOnlyList reader) + private UserItemData ReadRow(IReadOnlyList reader) { var userData = new UserItemData(); diff --git a/Emby.Server.Implementations/Emby.Server.Implementations.csproj b/Emby.Server.Implementations/Emby.Server.Implementations.csproj index 113863519b..a72a87462c 100644 --- a/Emby.Server.Implementations/Emby.Server.Implementations.csproj +++ b/Emby.Server.Implementations/Emby.Server.Implementations.csproj @@ -31,7 +31,7 @@ - + diff --git a/Emby.Server.Implementations/Security/AuthenticationRepository.cs b/Emby.Server.Implementations/Security/AuthenticationRepository.cs index 30823ab8f5..e8eac315b6 100644 --- a/Emby.Server.Implementations/Security/AuthenticationRepository.cs +++ b/Emby.Server.Implementations/Security/AuthenticationRepository.cs @@ -291,7 +291,7 @@ namespace Emby.Server.Implementations.Security return result; } - private static AuthenticationInfo Get(IReadOnlyList reader) + private static AuthenticationInfo Get(IReadOnlyList reader) { var info = new AuthenticationInfo { From e01ce826e096e44473a7d86fd6f55b6f59137fc7 Mon Sep 17 00:00:00 2001 From: crobibero Date: Sun, 23 May 2021 08:38:05 -0600 Subject: [PATCH 1686/1930] Allow sorting for AlbumArtist --- Jellyfin.Api/Controllers/ArtistsController.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/ArtistsController.cs b/Jellyfin.Api/Controllers/ArtistsController.cs index 85d7c50d34..154a567020 100644 --- a/Jellyfin.Api/Controllers/ArtistsController.cs +++ b/Jellyfin.Api/Controllers/ArtistsController.cs @@ -281,6 +281,8 @@ namespace Jellyfin.Api.Controllers /// Optional filter by items whose name is sorted equally or greater than a given input string. /// Optional filter by items whose name is sorted equally than a given input string. /// Optional filter by items whose name is equally or lesser than a given input string. + /// Optional. Specify one or more sort orders, comma delimited. + /// Sort Order - Ascending,Descending. /// Optional, include image information in output. /// Total record count. /// Album artists returned. @@ -316,6 +318,8 @@ namespace Jellyfin.Api.Controllers [FromQuery] string? nameStartsWithOrGreater, [FromQuery] string? nameStartsWith, [FromQuery] string? nameLessThan, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy, + [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder, [FromQuery] bool? enableImages = true, [FromQuery] bool enableTotalRecordCount = true) { @@ -354,7 +358,8 @@ namespace Jellyfin.Api.Controllers MinCommunityRating = minCommunityRating, DtoOptions = dtoOptions, SearchTerm = searchTerm, - EnableTotalRecordCount = enableTotalRecordCount + EnableTotalRecordCount = enableTotalRecordCount, + OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder) }; if (parentId.HasValue) From 42a2cc1747c7859c63334a7a45792e0af1410e1a Mon Sep 17 00:00:00 2001 From: cvium Date: Mon, 24 May 2021 00:30:41 +0200 Subject: [PATCH 1687/1930] Remove some unnecessary allocations --- Emby.Naming/TV/EpisodeResolver.cs | 5 +- Emby.Naming/Video/ExtraResolver.cs | 2 +- Emby.Naming/Video/FlagParser.cs | 53 -- Emby.Naming/Video/Format3DParser.cs | 94 ++-- Emby.Naming/Video/Format3DResult.cs | 23 +- Emby.Naming/Video/StackResolver.cs | 4 +- Emby.Naming/Video/VideoFileInfo.cs | 7 +- Emby.Naming/Video/VideoListResolver.cs | 260 ++++++---- Emby.Naming/Video/VideoResolver.cs | 60 +-- .../AppBase/BaseConfigurationManager.cs | 36 +- .../Data/SqliteItemRepository.cs | 489 ++++++++++-------- .../Data/TypeMapper.cs | 16 +- .../IO/ManagedFileSystem.cs | 20 +- .../Library/CoreResolutionIgnoreRule.cs | 2 +- .../Library/LibraryManager.cs | 48 +- .../Library/MediaSourceManager.cs | 9 +- .../Library/Resolvers/BaseVideoResolver.cs | 17 +- .../Library/Resolvers/Movies/MovieResolver.cs | 12 +- .../Localization/LocalizationManager.cs | 34 +- .../Serialization/MyXmlSerializer.cs | 3 +- .../ServerApplicationPaths.cs | 10 +- .../BaseItemManager/BaseItemManager.cs | 9 +- MediaBrowser.Controller/Entities/BaseItem.cs | 31 +- .../Extensions/StringExtensions.cs | 21 + .../Library/ILibraryManager.cs | 7 + .../MediaBrowser.Controller.csproj | 5 +- .../Providers/DirectoryService.cs | 26 +- .../Providers/IDirectoryService.cs | 4 +- .../Providers/MetadataResult.cs | 18 +- .../Images/EpisodeLocalImageProvider.cs | 26 +- .../Manager/ItemImageProvider.cs | 42 +- .../Manager/MetadataService.cs | 18 +- .../MediaInfo/SubtitleResolver.cs | 25 +- RSSDP/SsdpCommunicationsServer.cs | 7 +- .../Video/CleanDateTimeTests.cs | 2 +- .../Video/CleanStringTests.cs | 6 +- .../Jellyfin.Naming.Tests/Video/ExtraTests.cs | 7 - .../Video/Format3DTests.cs | 9 +- .../Video/MultiVersionTests.cs | 208 ++++---- .../Jellyfin.Naming.Tests/Video/StubTests.cs | 3 +- .../Video/VideoListResolverTests.cs | 242 +++++---- .../Video/VideoResolverTests.cs | 32 +- .../Data/SqliteItemRepositoryTests.cs | 49 ++ 43 files changed, 1095 insertions(+), 906 deletions(-) delete mode 100644 Emby.Naming/Video/FlagParser.cs diff --git a/Emby.Naming/TV/EpisodeResolver.cs b/Emby.Naming/TV/EpisodeResolver.cs index c63aec64e4..5e952e47b7 100644 --- a/Emby.Naming/TV/EpisodeResolver.cs +++ b/Emby.Naming/TV/EpisodeResolver.cs @@ -16,7 +16,7 @@ namespace Emby.Naming.TV /// /// Initializes a new instance of the class. /// - /// object containing VideoFileExtensions and passed to , , and . + /// object containing VideoFileExtensions and passed to , and . public EpisodeResolver(NamingOptions options) { _options = options; @@ -62,8 +62,7 @@ namespace Emby.Naming.TV container = extension.TrimStart('.'); } - var flags = new FlagParser(_options).GetFlags(path); - var format3DResult = new Format3DParser(_options).Parse(flags); + var format3DResult = Format3DParser.Parse(path, _options); var parsingResult = new EpisodePathParser(_options) .Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo); diff --git a/Emby.Naming/Video/ExtraResolver.cs b/Emby.Naming/Video/ExtraResolver.cs index f9d06c09be..1fade985be 100644 --- a/Emby.Naming/Video/ExtraResolver.cs +++ b/Emby.Naming/Video/ExtraResolver.cs @@ -44,7 +44,7 @@ namespace Emby.Naming.Video } else if (rule.MediaType == MediaType.Video) { - if (!new VideoResolver(_options).IsVideoFile(path)) + if (!VideoResolver.IsVideoFile(path, _options)) { continue; } diff --git a/Emby.Naming/Video/FlagParser.cs b/Emby.Naming/Video/FlagParser.cs deleted file mode 100644 index 439de18138..0000000000 --- a/Emby.Naming/Video/FlagParser.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.IO; -using Emby.Naming.Common; - -namespace Emby.Naming.Video -{ - /// - /// Parses list of flags from filename based on delimiters. - /// - public class FlagParser - { - private readonly NamingOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// object containing VideoFlagDelimiters. - public FlagParser(NamingOptions options) - { - _options = options; - } - - /// - /// Calls GetFlags function with _options.VideoFlagDelimiters parameter. - /// - /// Path to file. - /// List of found flags. - public string[] GetFlags(string path) - { - return GetFlags(path, _options.VideoFlagDelimiters); - } - - /// - /// Parses flags from filename based on delimiters. - /// - /// Path to file. - /// Delimiters used to extract flags. - /// List of found flags. - public string[] GetFlags(string path, char[] delimiters) - { - if (string.IsNullOrEmpty(path)) - { - return Array.Empty(); - } - - // Note: the tags need be be surrounded be either a space ( ), hyphen -, dot . or underscore _. - - var file = Path.GetFileName(path); - - return file.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); - } - } -} diff --git a/Emby.Naming/Video/Format3DParser.cs b/Emby.Naming/Video/Format3DParser.cs index 4fd5d78ba7..190ff99184 100644 --- a/Emby.Naming/Video/Format3DParser.cs +++ b/Emby.Naming/Video/Format3DParser.cs @@ -1,45 +1,37 @@ using System; -using System.Linq; using Emby.Naming.Common; namespace Emby.Naming.Video { /// - /// Parste 3D format related flags. + /// Parse 3D format related flags. /// - public class Format3DParser + public static class Format3DParser { - private readonly NamingOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// object containing VideoFlagDelimiters and passes options to . - public Format3DParser(NamingOptions options) - { - _options = options; - } + // Static default result to save on allocation costs. + private static readonly Format3DResult _defaultResult = new (false, null); /// /// Parse 3D format related flags. /// /// Path to file. + /// The naming options. /// Returns object. - public Format3DResult Parse(string path) + public static Format3DResult Parse(string path, NamingOptions namingOptions) { - int oldLen = _options.VideoFlagDelimiters.Length; + int oldLen = namingOptions.VideoFlagDelimiters.Length; var delimiters = new char[oldLen + 1]; - _options.VideoFlagDelimiters.CopyTo(delimiters, 0); + namingOptions.VideoFlagDelimiters.CopyTo(delimiters, 0); delimiters[oldLen] = ' '; - return Parse(new FlagParser(_options).GetFlags(path, delimiters)); + return Parse(path, delimiters, namingOptions); } - internal Format3DResult Parse(string[] videoFlags) + private static Format3DResult Parse(ReadOnlySpan path, char[] delimiters, NamingOptions namingOptions) { - foreach (var rule in _options.Format3DRules) + foreach (var rule in namingOptions.Format3DRules) { - var result = Parse(videoFlags, rule); + var result = Parse(path, rule, delimiters); if (result.Is3D) { @@ -47,51 +39,43 @@ namespace Emby.Naming.Video } } - return new Format3DResult(); + return _defaultResult; } - private static Format3DResult Parse(string[] videoFlags, Format3DRule rule) + private static Format3DResult Parse(ReadOnlySpan path, Format3DRule rule, char[] delimiters) { - var result = new Format3DResult(); + bool is3D = false; + string? format3D = null; - if (string.IsNullOrEmpty(rule.PrecedingToken)) + // If there's no preceding token we just consider it found + var foundPrefix = string.IsNullOrEmpty(rule.PrecedingToken); + while (path.Length > 0) { - result.Format3D = new[] { rule.Token }.FirstOrDefault(i => videoFlags.Contains(i, StringComparer.OrdinalIgnoreCase)); - result.Is3D = !string.IsNullOrEmpty(result.Format3D); - - if (result.Is3D) + var index = path.IndexOfAny(delimiters); + if (index == -1) { - result.Tokens.Add(rule.Token); - } - } - else - { - var foundPrefix = false; - string? format = null; - - foreach (var flag in videoFlags) - { - if (foundPrefix) - { - result.Tokens.Add(rule.PrecedingToken); - - if (string.Equals(rule.Token, flag, StringComparison.OrdinalIgnoreCase)) - { - format = flag; - result.Tokens.Add(rule.Token); - } - - break; - } - - foundPrefix = string.Equals(flag, rule.PrecedingToken, StringComparison.OrdinalIgnoreCase); + index = path.Length - 1; } - result.Is3D = foundPrefix && !string.IsNullOrEmpty(format); - result.Format3D = format; + var currentSlice = path[..index]; + path = path[(index + 1)..]; + + if (!foundPrefix) + { + foundPrefix = currentSlice.Equals(rule.PrecedingToken, StringComparison.OrdinalIgnoreCase); + continue; + } + + is3D = foundPrefix && currentSlice.Equals(rule.Token, StringComparison.OrdinalIgnoreCase); + + if (is3D) + { + format3D = rule.Token; + break; + } } - return result; + return is3D ? new Format3DResult(true, format3D) : _defaultResult; } } } diff --git a/Emby.Naming/Video/Format3DResult.cs b/Emby.Naming/Video/Format3DResult.cs index ac935f2030..aac959c133 100644 --- a/Emby.Naming/Video/Format3DResult.cs +++ b/Emby.Naming/Video/Format3DResult.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Emby.Naming.Video { /// @@ -10,27 +8,24 @@ namespace Emby.Naming.Video /// /// Initializes a new instance of the class. /// - public Format3DResult() + /// A value indicating whether the parsed string contains 3D tokens. + /// The 3D format. Value might be null if [is3D] is false. + public Format3DResult(bool is3D, string? format3D) { - Tokens = new List(); + Is3D = is3D; + Format3D = format3D; } /// - /// Gets or sets a value indicating whether [is3 d]. + /// Gets a value indicating whether [is3 d]. /// /// true if [is3 d]; otherwise, false. - public bool Is3D { get; set; } + public bool Is3D { get; } /// - /// Gets or sets the format3 d. + /// Gets the format3 d. /// /// The format3 d. - public string? Format3D { get; set; } - - /// - /// Gets or sets the tokens. - /// - /// The tokens. - public List Tokens { get; set; } + public string? Format3D { get; } } } diff --git a/Emby.Naming/Video/StackResolver.cs b/Emby.Naming/Video/StackResolver.cs index 550c429614..36f65a5624 100644 --- a/Emby.Naming/Video/StackResolver.cs +++ b/Emby.Naming/Video/StackResolver.cs @@ -85,10 +85,8 @@ namespace Emby.Naming.Video /// Enumerable of videos. public IEnumerable Resolve(IEnumerable files) { - var resolver = new VideoResolver(_options); - var list = files - .Where(i => i.IsDirectory || resolver.IsVideoFile(i.FullName) || resolver.IsStubFile(i.FullName)) + .Where(i => i.IsDirectory || VideoResolver.IsVideoFile(i.FullName, _options) || VideoResolver.IsStubFile(i.FullName, _options)) .OrderBy(i => i.FullName) .ToList(); diff --git a/Emby.Naming/Video/VideoFileInfo.cs b/Emby.Naming/Video/VideoFileInfo.cs index 1457db7378..481773ff60 100644 --- a/Emby.Naming/Video/VideoFileInfo.cs +++ b/Emby.Naming/Video/VideoFileInfo.cs @@ -1,3 +1,4 @@ +using System; using MediaBrowser.Model.Entities; namespace Emby.Naming.Video @@ -106,9 +107,9 @@ namespace Emby.Naming.Video /// Gets the file name without extension. /// /// The file name without extension. - public string FileNameWithoutExtension => !IsDirectory - ? System.IO.Path.GetFileNameWithoutExtension(Path) - : System.IO.Path.GetFileName(Path); + public ReadOnlySpan FileNameWithoutExtension => !IsDirectory + ? System.IO.Path.GetFileNameWithoutExtension(Path.AsSpan()) + : System.IO.Path.GetFileName(Path.AsSpan()); /// public override string ToString() diff --git a/Emby.Naming/Video/VideoListResolver.cs b/Emby.Naming/Video/VideoListResolver.cs index 7b6a1705ba..65cf7c9284 100644 --- a/Emby.Naming/Video/VideoListResolver.cs +++ b/Emby.Naming/Video/VideoListResolver.cs @@ -12,31 +12,19 @@ namespace Emby.Naming.Video /// /// Resolves alternative versions and extras from list of video files. /// - public class VideoListResolver + public static class VideoListResolver { - private readonly NamingOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// object containing CleanStringRegexes and VideoFlagDelimiters and passes options to and . - public VideoListResolver(NamingOptions options) - { - _options = options; - } - /// /// Resolves alternative versions and extras from list of video files. /// /// List of related video files. + /// The naming options. /// Indication we should consider multi-versions of content. /// Returns enumerable of which groups files together when related. - public IEnumerable Resolve(List files, bool supportMultiVersion = true) + public static IEnumerable Resolve(List files, NamingOptions namingOptions, bool supportMultiVersion = true) { - var videoResolver = new VideoResolver(_options); - var videoInfos = files - .Select(i => videoResolver.Resolve(i.FullName, i.IsDirectory)) + .Select(i => VideoResolver.Resolve(i.FullName, i.IsDirectory, namingOptions)) .OfType() .ToList(); @@ -46,7 +34,7 @@ namespace Emby.Naming.Video .Where(i => i.ExtraType == null) .Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory }); - var stackResult = new StackResolver(_options) + var stackResult = new StackResolver(namingOptions) .Resolve(nonExtras).ToList(); var remainingFiles = videoInfos @@ -59,23 +47,17 @@ namespace Emby.Naming.Video { var info = new VideoInfo(stack.Name) { - Files = stack.Files.Select(i => videoResolver.Resolve(i, stack.IsDirectoryStack)) + Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions)) .OfType() .ToList() }; info.Year = info.Files[0].Year; - var extraBaseNames = new List { stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0]) }; - - var extras = GetExtras(remainingFiles, extraBaseNames); + var extras = ExtractExtras(remainingFiles, stack.Name, Path.GetFileNameWithoutExtension(stack.Files[0].AsSpan()), namingOptions.VideoFlagDelimiters); if (extras.Count > 0) { - remainingFiles = remainingFiles - .Except(extras) - .ToList(); - info.Extras = extras; } @@ -88,15 +70,12 @@ namespace Emby.Naming.Video foreach (var media in standaloneMedia) { - var info = new VideoInfo(media.Name) { Files = new List { media } }; + var info = new VideoInfo(media.Name) { Files = new[] { media } }; info.Year = info.Files[0].Year; - var extras = GetExtras(remainingFiles, new List { media.FileNameWithoutExtension }); - - remainingFiles = remainingFiles - .Except(extras.Concat(new[] { media })) - .ToList(); + remainingFiles.Remove(media); + var extras = ExtractExtras(remainingFiles, media.FileNameWithoutExtension, namingOptions.VideoFlagDelimiters); info.Extras = extras; @@ -105,8 +84,7 @@ namespace Emby.Naming.Video if (supportMultiVersion) { - list = GetVideosGroupedByVersion(list) - .ToList(); + list = GetVideosGroupedByVersion(list, namingOptions); } // If there's only one resolved video, use the folder name as well to find extras @@ -114,19 +92,14 @@ namespace Emby.Naming.Video { var info = list[0]; var videoPath = list[0].Files[0].Path; - var parentPath = Path.GetDirectoryName(videoPath); + var parentPath = Path.GetDirectoryName(videoPath.AsSpan()); - if (!string.IsNullOrEmpty(parentPath)) + if (!parentPath.IsEmpty) { var folderName = Path.GetFileName(parentPath); - if (!string.IsNullOrEmpty(folderName)) + if (!folderName.IsEmpty) { - var extras = GetExtras(remainingFiles, new List { folderName }); - - remainingFiles = remainingFiles - .Except(extras) - .ToList(); - + var extras = ExtractExtras(remainingFiles, folderName, namingOptions.VideoFlagDelimiters); extras.AddRange(info.Extras); info.Extras = extras; } @@ -164,96 +137,169 @@ namespace Emby.Naming.Video // Whatever files are left, just add them list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name) { - Files = new List { i }, + Files = new[] { i }, Year = i.Year })); return list; } - private IEnumerable GetVideosGroupedByVersion(List videos) + private static List GetVideosGroupedByVersion(List videos, NamingOptions namingOptions) { if (videos.Count == 0) { return videos; } - var list = new List(); + var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan())); - var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path)); - - if (!string.IsNullOrEmpty(folderName) - && folderName.Length > 1 - && videos.All(i => i.Files.Count == 1 - && IsEligibleForMultiVersion(folderName, i.Files[0].Path)) - && HaveSameYear(videos)) + if (folderName.Length <= 1 || !HaveSameYear(videos)) { - var ordered = videos.OrderBy(i => i.Name).ToList(); - - list.Add(ordered[0]); - - var alternateVersionsLen = ordered.Count - 1; - var alternateVersions = new VideoFileInfo[alternateVersionsLen]; - for (int i = 0; i < alternateVersionsLen; i++) - { - alternateVersions[i] = ordered[i + 1].Files[0]; - } - - list[0].AlternateVersions = alternateVersions; - list[0].Name = folderName; - var extras = ordered.Skip(1).SelectMany(i => i.Extras).ToList(); - extras.AddRange(list[0].Extras); - list[0].Extras = extras; - - return list; + return videos; } - return videos; - } - - private bool HaveSameYear(List videos) - { - return videos.Select(i => i.Year ?? -1).Distinct().Count() < 2; - } - - private bool IsEligibleForMultiVersion(string folderName, string testFilePath) - { - string testFilename = Path.GetFileNameWithoutExtension(testFilePath); - if (testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) + // Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if] + for (var i = 0; i < videos.Count; i++) { - // Remove the folder name before cleaning as we don't care about cleaning that part - if (folderName.Length <= testFilename.Length) + var video = videos[i]; + if (!IsEligibleForMultiVersion(folderName, video.Files[0].Path, namingOptions)) { - testFilename = testFilename.Substring(folderName.Length).Trim(); + return videos; } - - if (CleanStringParser.TryClean(testFilename, _options.CleanStringRegexes, out var cleanName)) - { - testFilename = cleanName.Trim().ToString(); - } - - // The CleanStringParser should have removed common keywords etc. - return string.IsNullOrEmpty(testFilename) - || testFilename[0] == '-' - || Regex.IsMatch(testFilename, @"^\[([^]]*)\]"); } - return false; - } + // The list is created and overwritten in the caller, so we are allowed to do in-place sorting + videos.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal)); - private List GetExtras(IEnumerable remainingFiles, List baseNames) - { - foreach (var name in baseNames.ToList()) + var list = new List { - var trimmedName = name.TrimEnd().TrimEnd(_options.VideoFlagDelimiters).TrimEnd(); - baseNames.Add(trimmedName); + videos[0] + }; + + var alternateVersionsLen = videos.Count - 1; + var alternateVersions = new VideoFileInfo[alternateVersionsLen]; + var extras = new List(list[0].Extras); + for (int i = 0; i < alternateVersionsLen; i++) + { + var video = videos[i + 1]; + alternateVersions[i] = video.Files[0]; + extras.AddRange(video.Extras); } - return remainingFiles - .Where(i => i.ExtraType != null) - .Where(i => baseNames.Any(b => - i.FileNameWithoutExtension.StartsWith(b, StringComparison.OrdinalIgnoreCase))) - .ToList(); + list[0].AlternateVersions = alternateVersions; + list[0].Name = folderName.ToString(); + list[0].Extras = extras; + + return list; + } + + private static bool HaveSameYear(IReadOnlyList videos) + { + if (videos.Count == 1) + { + return true; + } + + var firstYear = videos[0].Year ?? -1; + for (var i = 1; i < videos.Count; i++) + { + if ((videos[i].Year ?? -1) != firstYear) + { + return false; + } + } + + return true; + } + + private static bool IsEligibleForMultiVersion(ReadOnlySpan folderName, string testFilePath, NamingOptions namingOptions) + { + var testFilename = Path.GetFileNameWithoutExtension(testFilePath.AsSpan()); + if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // Remove the folder name before cleaning as we don't care about cleaning that part + if (folderName.Length <= testFilename.Length) + { + testFilename = testFilename[folderName.Length..].Trim(); + } + + // There are no span overloads for regex unfortunately + var tmpTestFilename = testFilename.ToString(); + if (CleanStringParser.TryClean(tmpTestFilename, namingOptions.CleanStringRegexes, out var cleanName)) + { + tmpTestFilename = cleanName.Trim().ToString(); + } + + // The CleanStringParser should have removed common keywords etc. + return string.IsNullOrEmpty(tmpTestFilename) + || testFilename[0] == '-' + || Regex.IsMatch(tmpTestFilename, @"^\[([^]]*)\]", RegexOptions.Compiled); + } + + private static ReadOnlySpan TrimFilenameDelimiters(ReadOnlySpan name, ReadOnlySpan videoFlagDelimiters) + { + return name.IsEmpty ? name : name.TrimEnd().TrimEnd(videoFlagDelimiters).TrimEnd(); + } + + private static bool StartsWith(ReadOnlySpan fileName, ReadOnlySpan baseName, ReadOnlySpan trimmedBaseName) + { + if (baseName.IsEmpty) + { + return false; + } + + return fileName.StartsWith(baseName, StringComparison.OrdinalIgnoreCase) + || (!trimmedBaseName.IsEmpty && fileName.StartsWith(trimmedBaseName, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Finds similar filenames to that of [baseName] and removes any matches from [remainingFiles]. + /// + /// The list of remaining filenames. + /// The base name to use for the comparison. + /// The video flag delimiters. + /// A list of video extras for [baseName]. + private static List ExtractExtras(IList remainingFiles, ReadOnlySpan baseName, ReadOnlySpan videoFlagDelimiters) + { + return ExtractExtras(remainingFiles, baseName, ReadOnlySpan.Empty, videoFlagDelimiters); + } + + /// + /// Finds similar filenames to that of [firstBaseName] and [secondBaseName] and removes any matches from [remainingFiles]. + /// + /// The list of remaining filenames. + /// The first base name to use for the comparison. + /// The second base name to use for the comparison. + /// The video flag delimiters. + /// A list of video extras for [firstBaseName] and [secondBaseName]. + private static List ExtractExtras(IList remainingFiles, ReadOnlySpan firstBaseName, ReadOnlySpan secondBaseName, ReadOnlySpan videoFlagDelimiters) + { + var trimmedFirstBaseName = TrimFilenameDelimiters(firstBaseName, videoFlagDelimiters); + var trimmedSecondBaseName = TrimFilenameDelimiters(secondBaseName, videoFlagDelimiters); + + var result = new List(); + var pos = remainingFiles.Count - 1; + for (; pos >= 0; pos--) + { + var file = remainingFiles[pos]; + if (file.ExtraType == null) + { + continue; + } + + var filename = file.FileNameWithoutExtension; + if (StartsWith(filename, firstBaseName, trimmedFirstBaseName) + || StartsWith(filename, secondBaseName, trimmedSecondBaseName)) + { + result.Add(file); + remainingFiles.RemoveAt(pos); + } + } + + return result; } } } diff --git a/Emby.Naming/Video/VideoResolver.cs b/Emby.Naming/Video/VideoResolver.cs index 27e73208c6..c4ac5fdc60 100644 --- a/Emby.Naming/Video/VideoResolver.cs +++ b/Emby.Naming/Video/VideoResolver.cs @@ -9,38 +9,28 @@ namespace Emby.Naming.Video /// /// Resolves from file path. /// - public class VideoResolver + public static class VideoResolver { - private readonly NamingOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// object containing VideoFileExtensions, StubFileExtensions, CleanStringRegexes and CleanDateTimeRegexes - /// and passes options in , , and . - public VideoResolver(NamingOptions options) - { - _options = options; - } - /// /// Resolves the directory. /// /// The path. + /// The naming options. /// VideoFileInfo. - public VideoFileInfo? ResolveDirectory(string? path) + public static VideoFileInfo? ResolveDirectory(string? path, NamingOptions namingOptions) { - return Resolve(path, true); + return Resolve(path, true, namingOptions); } /// /// Resolves the file. /// /// The path. + /// The naming options. /// VideoFileInfo. - public VideoFileInfo? ResolveFile(string? path) + public static VideoFileInfo? ResolveFile(string? path, NamingOptions namingOptions) { - return Resolve(path, false); + return Resolve(path, false, namingOptions); } /// @@ -48,10 +38,11 @@ namespace Emby.Naming.Video /// /// The path. /// if set to true [is folder]. + /// The naming options. /// Whether or not the name should be parsed for info. /// VideoFileInfo. /// path is null. - public VideoFileInfo? Resolve(string? path, bool isDirectory, bool parseName = true) + public static VideoFileInfo? Resolve(string? path, bool isDirectory, NamingOptions namingOptions, bool parseName = true) { if (string.IsNullOrEmpty(path)) { @@ -67,10 +58,10 @@ namespace Emby.Naming.Video var extension = Path.GetExtension(path.AsSpan()); // Check supported extensions - if (!_options.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase)) + if (!namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase)) { // It's not supported. Check stub extensions - if (!StubResolver.TryResolveFile(path, _options, out stubType)) + if (!StubResolver.TryResolveFile(path, namingOptions, out stubType)) { return null; } @@ -81,10 +72,9 @@ namespace Emby.Naming.Video container = extension.TrimStart('.'); } - var flags = new FlagParser(_options).GetFlags(path); - var format3DResult = new Format3DParser(_options).Parse(flags); + var format3DResult = Format3DParser.Parse(path, namingOptions); - var extraResult = new ExtraResolver(_options).GetExtraInfo(path); + var extraResult = new ExtraResolver(namingOptions).GetExtraInfo(path); var name = Path.GetFileNameWithoutExtension(path); @@ -92,12 +82,12 @@ namespace Emby.Naming.Video if (parseName) { - var cleanDateTimeResult = CleanDateTime(name); + var cleanDateTimeResult = CleanDateTime(name, namingOptions); name = cleanDateTimeResult.Name; year = cleanDateTimeResult.Year; if (extraResult.ExtraType == null - && TryCleanString(name, out ReadOnlySpan newName)) + && TryCleanString(name, namingOptions, out ReadOnlySpan newName)) { name = newName.ToString(); } @@ -121,43 +111,47 @@ namespace Emby.Naming.Video /// Determines if path is video file based on extension. /// /// Path to file. + /// The naming options. /// True if is video file. - public bool IsVideoFile(string path) + public static bool IsVideoFile(string path, NamingOptions namingOptions) { var extension = Path.GetExtension(path.AsSpan()); - return _options.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); + return namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); } /// /// Determines if path is video file stub based on extension. /// /// Path to file. + /// The naming options. /// True if is video file stub. - public bool IsStubFile(string path) + public static bool IsStubFile(string path, NamingOptions namingOptions) { var extension = Path.GetExtension(path.AsSpan()); - return _options.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); + return namingOptions.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase); } /// /// Tries to clean name of clutter. /// /// Raw name. + /// The naming options. /// Clean name. /// True if cleaning of name was successful. - public bool TryCleanString([NotNullWhen(true)] string? name, out ReadOnlySpan newName) + public static bool TryCleanString([NotNullWhen(true)] string? name, NamingOptions namingOptions, out ReadOnlySpan newName) { - return CleanStringParser.TryClean(name, _options.CleanStringRegexes, out newName); + return CleanStringParser.TryClean(name, namingOptions.CleanStringRegexes, out newName); } /// /// Tries to get name and year from raw name. /// /// Raw name. + /// The naming options. /// Returns with name and optional year. - public CleanDateTimeResult CleanDateTime(string name) + public static CleanDateTimeResult CleanDateTime(string name, NamingOptions namingOptions) { - return CleanDateTimeParser.Clean(name, _options.CleanDateTimeRegexes); + return CleanDateTimeParser.Clean(name, namingOptions.CleanDateTimeRegexes); } } } diff --git a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs index 8c919db431..fab085dbcb 100644 --- a/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs +++ b/Emby.Server.Implementations/AppBase/BaseConfigurationManager.cs @@ -299,25 +299,29 @@ namespace Emby.Server.Implementations.AppBase /// public object GetConfiguration(string key) { - return _configurations.GetOrAdd(key, k => - { - var file = GetConfigurationFile(key); - - var configurationInfo = _configurationStores - .FirstOrDefault(i => string.Equals(i.Key, key, StringComparison.OrdinalIgnoreCase)); - - if (configurationInfo == null) + return _configurations.GetOrAdd( + key, + (k, configurationManager) => { - throw new ResourceNotFoundException("Configuration with key " + key + " not found."); - } + var file = configurationManager.GetConfigurationFile(k); - var configurationType = configurationInfo.ConfigurationType; + var configurationInfo = Array.Find( + configurationManager._configurationStores, + i => string.Equals(i.Key, k, StringComparison.OrdinalIgnoreCase)); - lock (_configurationSyncLock) - { - return LoadConfiguration(file, configurationType); - } - }); + if (configurationInfo == null) + { + throw new ResourceNotFoundException("Configuration with key " + k + " not found."); + } + + var configurationType = configurationInfo.ConfigurationType; + + lock (configurationManager._configurationSyncLock) + { + return configurationManager.LoadConfiguration(file, configurationType); + } + }, + this); } private object LoadConfiguration(string path, Type configurationType) diff --git a/Emby.Server.Implementations/Data/SqliteItemRepository.cs b/Emby.Server.Implementations/Data/SqliteItemRepository.cs index 2d060dd652..1480600cfb 100644 --- a/Emby.Server.Implementations/Data/SqliteItemRepository.cs +++ b/Emby.Server.Implementations/Data/SqliteItemRepository.cs @@ -43,6 +43,7 @@ namespace Emby.Server.Implementations.Data ///
public class SqliteItemRepository : BaseSqliteRepository, IItemRepository { + private const string FromText = " from TypedBaseItems A"; private const string ChaptersTableName = "Chapters2"; private readonly IServerConfigurationManager _config; @@ -1045,18 +1046,37 @@ namespace Emby.Server.Implementations.Data return Array.Empty(); } - var list = new List(); - foreach (var part in value.SpanSplit('|')) + // TODO The following is an ugly performance optimization, but it's extremely unlikely that the data in the database would be malformed + var valueSpan = value.AsSpan(); + var count = valueSpan.CountOccurrences('|') + 1; + + var position = 0; + var result = new ItemImageInfo[count]; + foreach (var part in valueSpan.Split('|')) { var image = ItemImageInfoFromValueString(part); if (image != null) { - list.Add(image); + result[position++] = image; } } - return list.ToArray(); + if (position == count) + { + return result; + } + + if (position == 0) + { + return Array.Empty(); + } + + // Extremely unlikely, but somehow one or more of the image strings were malformed. Cut the array. + var newResult = new ItemImageInfo[position]; + Array.Copy(result, newResult, position); + + return newResult; } private void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image) @@ -2250,10 +2270,8 @@ namespace Emby.Server.Implementations.Data return query.IncludeItemTypes.Any(x => _seriesTypes.Contains(x)); } - private List GetFinalColumnsToSelect(InternalItemsQuery query, IEnumerable startColumns) + private List GetFinalColumnsToSelect(InternalItemsQuery query, List columns) { - var list = startColumns.ToList(); - foreach (var field in _allFields) { if (!HasField(query, field)) @@ -2261,28 +2279,28 @@ namespace Emby.Server.Implementations.Data switch (field) { case ItemFields.Settings: - list.Remove("IsLocked"); - list.Remove("PreferredMetadataCountryCode"); - list.Remove("PreferredMetadataLanguage"); - list.Remove("LockedFields"); + columns.Remove("IsLocked"); + columns.Remove("PreferredMetadataCountryCode"); + columns.Remove("PreferredMetadataLanguage"); + columns.Remove("LockedFields"); break; case ItemFields.ServiceName: - list.Remove("ExternalServiceId"); + columns.Remove("ExternalServiceId"); break; case ItemFields.SortName: - list.Remove("ForcedSortName"); + columns.Remove("ForcedSortName"); break; case ItemFields.Taglines: - list.Remove("Tagline"); + columns.Remove("Tagline"); break; case ItemFields.Tags: - list.Remove("Tags"); + columns.Remove("Tags"); break; case ItemFields.IsHD: // do nothing break; default: - list.Remove(field.ToString()); + columns.Remove(field.ToString()); break; } } @@ -2290,60 +2308,60 @@ namespace Emby.Server.Implementations.Data if (!HasProgramAttributes(query)) { - list.Remove("IsMovie"); - list.Remove("IsSeries"); - list.Remove("EpisodeTitle"); - list.Remove("IsRepeat"); - list.Remove("ShowId"); + columns.Remove("IsMovie"); + columns.Remove("IsSeries"); + columns.Remove("EpisodeTitle"); + columns.Remove("IsRepeat"); + columns.Remove("ShowId"); } if (!HasEpisodeAttributes(query)) { - list.Remove("SeasonName"); - list.Remove("SeasonId"); + columns.Remove("SeasonName"); + columns.Remove("SeasonId"); } if (!HasStartDate(query)) { - list.Remove("StartDate"); + columns.Remove("StartDate"); } if (!HasTrailerTypes(query)) { - list.Remove("TrailerTypes"); + columns.Remove("TrailerTypes"); } if (!HasArtistFields(query)) { - list.Remove("AlbumArtists"); - list.Remove("Artists"); + columns.Remove("AlbumArtists"); + columns.Remove("Artists"); } if (!HasSeriesFields(query)) { - list.Remove("SeriesId"); + columns.Remove("SeriesId"); } if (!HasEpisodeAttributes(query)) { - list.Remove("SeasonName"); - list.Remove("SeasonId"); + columns.Remove("SeasonName"); + columns.Remove("SeasonId"); } if (!query.DtoOptions.EnableImages) { - list.Remove("Images"); + columns.Remove("Images"); } if (EnableJoinUserData(query)) { - list.Add("UserDatas.UserId"); - list.Add("UserDatas.lastPlayedDate"); - list.Add("UserDatas.playbackPositionTicks"); - list.Add("UserDatas.playcount"); - list.Add("UserDatas.isFavorite"); - list.Add("UserDatas.played"); - list.Add("UserDatas.rating"); + columns.Add("UserDatas.UserId"); + columns.Add("UserDatas.lastPlayedDate"); + columns.Add("UserDatas.playbackPositionTicks"); + columns.Add("UserDatas.playcount"); + columns.Add("UserDatas.isFavorite"); + columns.Add("UserDatas.played"); + columns.Add("UserDatas.rating"); } if (query.SimilarTo != null) @@ -2391,7 +2409,7 @@ namespace Emby.Server.Implementations.Data builder.Append(") as SimilarityScore"); - list.Add(builder.ToString()); + columns.Add(builder.ToString()); var oldLen = query.ExcludeItemIds.Length; var newLen = oldLen + item.ExtraIds.Length + 1; @@ -2418,10 +2436,10 @@ namespace Emby.Server.Implementations.Data builder.Append(") as SearchScore"); - list.Add(builder.ToString()); + columns.Add(builder.ToString()); } - return list; + return columns; } private void BindSearchParams(InternalItemsQuery query, IStatement statement) @@ -2487,31 +2505,25 @@ namespace Emby.Server.Implementations.Data private string GetGroupBy(InternalItemsQuery query) { - var groups = new List(); - - if (EnableGroupByPresentationUniqueKey(query)) + var enableGroupByPresentationUniqueKey = EnableGroupByPresentationUniqueKey(query); + if (enableGroupByPresentationUniqueKey && query.GroupBySeriesPresentationUniqueKey) { - groups.Add("PresentationUniqueKey"); + return " Group by PresentationUniqueKey, SeriesPresentationUniqueKey"; + } + + if (enableGroupByPresentationUniqueKey) + { + return " Group by PresentationUniqueKey"; } if (query.GroupBySeriesPresentationUniqueKey) { - groups.Add("SeriesPresentationUniqueKey"); - } - - if (groups.Count > 0) - { - return " Group by " + string.Join(',', groups); + return " Group by SeriesPresentationUniqueKey"; } return string.Empty; } - private string GetFromText(string alias = "A") - { - return " from TypedBaseItems " + alias; - } - public int GetCount(InternalItemsQuery query) { if (query == null) @@ -2529,17 +2541,19 @@ namespace Emby.Server.Implementations.Data query.Limit = query.Limit.Value + 4; } - var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count(distinct PresentationUniqueKey)" })) - + GetFromText() - + GetJoinUserDataText(query); + var commandTextBuilder = new StringBuilder("select ") + .AppendJoin(',', GetFinalColumnsToSelect(query, new List { "count(distinct PresentationUniqueKey)" })) + .Append(FromText) + .Append(GetJoinUserDataText(query)); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) { - commandText += " where " + string.Join(" AND ", whereClauses); + commandTextBuilder.Append(" where ") + .AppendJoin(" AND ", whereClauses); } + var commandText = commandTextBuilder.ToString(); int count; using (var connection = GetConnection(true)) { @@ -2581,20 +2595,21 @@ namespace Emby.Server.Implementations.Data query.Limit = query.Limit.Value + 4; } - var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, _retriveItemColumns)) - + GetFromText() - + GetJoinUserDataText(query); + var commandTextBuilder = new StringBuilder("select ") + .AppendJoin(',', GetFinalColumnsToSelect(query, _retriveItemColumns.ToList())) + .Append(FromText) + .Append(GetJoinUserDataText(query)); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) { - commandText += " where " + string.Join(" AND ", whereClauses); + commandTextBuilder.Append(" where ") + .AppendJoin(" AND ", whereClauses); } - commandText += GetGroupBy(query) - + GetOrderByText(query); + commandTextBuilder.Append(GetGroupBy(query)) + .Append(GetOrderByText(query)); if (query.Limit.HasValue || query.StartIndex.HasValue) { @@ -2602,15 +2617,18 @@ namespace Emby.Server.Implementations.Data if (query.Limit.HasValue || offset > 0) { - commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" LIMIT ") + .Append((query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture)); } if (offset > 0) { - commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" OFFSET ") + .Append(offset.ToString(CultureInfo.InvariantCulture)); } } + var commandText = commandTextBuilder.ToString(); var items = new List(); using (var connection = GetConnection(true)) { @@ -2766,20 +2784,25 @@ namespace Emby.Server.Implementations.Data query.Limit = query.Limit.Value + 4; } - var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, _retriveItemColumns)) - + GetFromText() - + GetJoinUserDataText(query); + var commandTextBuilder = new StringBuilder("select ") + .AppendJoin(',', GetFinalColumnsToSelect(query, _retriveItemColumns.ToList())) + .Append(FromText) + .Append(GetJoinUserDataText(query)); var whereClauses = GetWhereClauses(query, null); var whereText = whereClauses.Count == 0 ? string.Empty : - " where " + string.Join(" AND ", whereClauses); + string.Join(" AND ", whereClauses); - commandText += whereText - + GetGroupBy(query) - + GetOrderByText(query); + if (!string.IsNullOrEmpty(whereText)) + { + commandTextBuilder.Append(" where ") + .Append(whereText); + } + + commandTextBuilder.Append(GetGroupBy(query)) + .Append(GetOrderByText(query)); if (query.Limit.HasValue || query.StartIndex.HasValue) { @@ -2787,43 +2810,54 @@ namespace Emby.Server.Implementations.Data if (query.Limit.HasValue || offset > 0) { - commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" LIMIT ") + .Append((query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture)); } if (offset > 0) { - commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" OFFSET ") + .Append(offset.ToString(CultureInfo.InvariantCulture)); } } var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; - var statementTexts = new List(); + var itemQuery = string.Empty; + var totalRecordCountQuery = string.Empty; if (!isReturningZeroItems) { - statementTexts.Add(commandText); + itemQuery = commandTextBuilder.ToString(); } if (query.EnableTotalRecordCount) { - commandText = string.Empty; + commandTextBuilder.Clear(); + + commandTextBuilder.Append(" select "); if (EnableGroupByPresentationUniqueKey(query)) { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); + commandTextBuilder.AppendJoin(',', GetFinalColumnsToSelect(query, new List { "count (distinct PresentationUniqueKey)" })); } else if (query.GroupBySeriesPresentationUniqueKey) { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); + commandTextBuilder.AppendJoin(',', GetFinalColumnsToSelect(query, new List { "count (distinct SeriesPresentationUniqueKey)" })); } else { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); + commandTextBuilder.AppendJoin(',', GetFinalColumnsToSelect(query, new List { "count (guid)" })); } - commandText += GetJoinUserDataText(query) - + whereText; - statementTexts.Add(commandText); + commandTextBuilder.Append(FromText) + .Append(GetJoinUserDataText(query)); + if (!string.IsNullOrEmpty(whereText)) + { + commandTextBuilder.Append(" where ") + .Append(whereText); + } + + totalRecordCountQuery = commandTextBuilder.ToString(); } var list = new List(); @@ -2833,11 +2867,12 @@ namespace Emby.Server.Implementations.Data connection.RunInTransaction( db => { - var statements = PrepareAll(db, statementTexts); + var itemQueryStatement = PrepareStatement(db, itemQuery); + var totalRecordCountQueryStatement = PrepareStatement(db, totalRecordCountQuery); if (!isReturningZeroItems) { - using (var statement = statements[0]) + using (var statement = itemQueryStatement) { if (EnableJoinUserData(query)) { @@ -2867,11 +2902,14 @@ namespace Emby.Server.Implementations.Data } } } + + LogQueryTime("GetItems.ItemQuery", itemQuery, now); } + now = DateTime.UtcNow; if (query.EnableTotalRecordCount) { - using (var statement = statements[statements.Length - 1]) + using (var statement = totalRecordCountQueryStatement) { if (EnableJoinUserData(query)) { @@ -2886,11 +2924,12 @@ namespace Emby.Server.Implementations.Data result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First(); } + + LogQueryTime("GetItems.TotalRecordCount", totalRecordCountQuery, now); } }, ReadTransactionMode); } - LogQueryTime("GetItems", commandText, now); result.Items = list; return result; } @@ -3023,19 +3062,20 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; - var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid" })) - + GetFromText() - + GetJoinUserDataText(query); + var commandTextBuilder = new StringBuilder("select ") + .AppendJoin(',', GetFinalColumnsToSelect(query, new List { "guid" })) + .Append(FromText) + .Append(GetJoinUserDataText(query)); var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) { - commandText += " where " + string.Join(" AND ", whereClauses); + commandTextBuilder.Append(" where ") + .AppendJoin(" AND ", whereClauses); } - commandText += GetGroupBy(query) - + GetOrderByText(query); + commandTextBuilder.Append(GetGroupBy(query)) + .Append(GetOrderByText(query)); if (query.Limit.HasValue || query.StartIndex.HasValue) { @@ -3043,15 +3083,18 @@ namespace Emby.Server.Implementations.Data if (query.Limit.HasValue || offset > 0) { - commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" LIMIT ") + .Append((query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture)); } if (offset > 0) { - commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture); + commandTextBuilder.Append(" OFFSET ") + .Append(offset.ToString(CultureInfo.InvariantCulture)); } } + var commandText = commandTextBuilder.ToString(); var list = new List(); using (var connection = GetConnection(true)) { @@ -3090,7 +3133,7 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; - var commandText = "select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid", "path" })) + GetFromText(); + var commandText = "select " + string.Join(',', GetFinalColumnsToSelect(query, new List { "guid", "path" })) + FromText; var whereClauses = GetWhereClauses(query, null); if (whereClauses.Count != 0) @@ -3167,8 +3210,8 @@ namespace Emby.Server.Implementations.Data var now = DateTime.UtcNow; var commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "guid" })) - + GetFromText() + + string.Join(',', GetFinalColumnsToSelect(query, new List { "guid" })) + + FromText + GetJoinUserDataText(query); var whereClauses = GetWhereClauses(query, null); @@ -3210,15 +3253,15 @@ namespace Emby.Server.Implementations.Data if (EnableGroupByPresentationUniqueKey(query)) { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new List { "count (distinct PresentationUniqueKey)" })) + FromText; } else if (query.GroupBySeriesPresentationUniqueKey) { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct SeriesPresentationUniqueKey)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new List { "count (distinct SeriesPresentationUniqueKey)" })) + FromText; } else { - commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (guid)" })) + GetFromText(); + commandText += " select " + string.Join(',', GetFinalColumnsToSelect(query, new List { "count (guid)" })) + FromText; } commandText += GetJoinUserDataText(query) @@ -4415,56 +4458,50 @@ namespace Emby.Server.Implementations.Data whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb")); } - var includedItemByNameTypes = GetItemByNameTypesInQuery(query); - var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0; - var queryTopParentIds = query.TopParentIds; - if (queryTopParentIds.Length == 1) + if (queryTopParentIds.Length > 0) { - if (enableItemsByName && includedItemByNameTypes.Count == 1) - { - whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)"); - if (statement != null) - { - statement.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]); - } - } - else if (enableItemsByName && includedItemByNameTypes.Count > 1) - { - var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); - whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))"); - } - else - { - whereClauses.Add("(TopParentId=@TopParentId)"); - } + var includedItemByNameTypes = GetItemByNameTypesInQuery(query); + var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0; - if (statement != null) + if (queryTopParentIds.Length == 1) { - statement.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture)); - } - } - else if (queryTopParentIds.Length > 1) - { - var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); - - if (enableItemsByName && includedItemByNameTypes.Count == 1) - { - whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))"); - if (statement != null) + if (enableItemsByName && includedItemByNameTypes.Count == 1) { - statement.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]); + whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)"); + statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]); } + else if (enableItemsByName && includedItemByNameTypes.Count > 1) + { + var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); + whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))"); + } + else + { + whereClauses.Add("(TopParentId=@TopParentId)"); + } + + statement?.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture)); } - else if (enableItemsByName && includedItemByNameTypes.Count > 1) + else if (queryTopParentIds.Length > 1) { - var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); - whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))"); - } - else - { - whereClauses.Add("TopParentId in (" + val + ")"); + var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'")); + + if (enableItemsByName && includedItemByNameTypes.Count == 1) + { + whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))"); + statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]); + } + else if (enableItemsByName && includedItemByNameTypes.Count > 1) + { + var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'")); + whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))"); + } + else + { + whereClauses.Add("TopParentId in (" + val + ")"); + } } } @@ -4746,17 +4783,12 @@ namespace Emby.Server.Implementations.Data return true; } - var types = new[] - { - nameof(Episode), - nameof(Video), - nameof(Movie), - nameof(MusicVideo), - nameof(Series), - nameof(Season) - }; - - if (types.Any(i => query.IncludeItemTypes.Contains(i, StringComparer.OrdinalIgnoreCase))) + if (query.IncludeItemTypes.Contains(nameof(Episode), StringComparer.OrdinalIgnoreCase) + || query.IncludeItemTypes.Contains(nameof(Video), StringComparer.OrdinalIgnoreCase) + || query.IncludeItemTypes.Contains(nameof(Movie), StringComparer.OrdinalIgnoreCase) + || query.IncludeItemTypes.Contains(nameof(MusicVideo), StringComparer.OrdinalIgnoreCase) + || query.IncludeItemTypes.Contains(nameof(Series), StringComparer.OrdinalIgnoreCase) + || query.IncludeItemTypes.Contains(nameof(Season), StringComparer.OrdinalIgnoreCase)) { return true; } @@ -5200,37 +5232,45 @@ AND Type = @InternalPersonType)"); var now = DateTime.UtcNow; - var typeClause = itemValueTypes.Length == 1 ? - ("Type=" + itemValueTypes[0].ToString(CultureInfo.InvariantCulture)) : - ("Type in (" + string.Join(',', itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + ")"); - - var commandText = "Select Value From ItemValues where " + typeClause; + var stringBuilder = new StringBuilder("Select Value From ItemValues where Type"); + if (itemValueTypes.Length == 1) + { + stringBuilder.Append('=') + .Append(itemValueTypes[0].ToString(CultureInfo.InvariantCulture)); + } + else + { + stringBuilder.Append(" in (") + .AppendJoin(',', itemValueTypes.Select(i => i.ToString(CultureInfo.InvariantCulture))) + .Append(')'); + } if (withItemTypes.Count > 0) { - var typeString = string.Join(',', withItemTypes.Select(i => "'" + i + "'")); - commandText += " AND ItemId In (select guid from typedbaseitems where type in (" + typeString + "))"; + stringBuilder.Append(" AND ItemId In (select guid from typedbaseitems where type in (") + .AppendJoin(',', withItemTypes.Select(i => "'" + i + "'")) + .Append("))"); } if (excludeItemTypes.Count > 0) { - var typeString = string.Join(',', excludeItemTypes.Select(i => "'" + i + "'")); - commandText += " AND ItemId not In (select guid from typedbaseitems where type in (" + typeString + "))"; + stringBuilder.Append(" AND ItemId not In (select guid from typedbaseitems where type in (") + .AppendJoin(',', excludeItemTypes.Select(i => "'" + i + "'")) + .Append("))"); } - commandText += " Group By CleanValue"; + stringBuilder.Append(" Group By CleanValue"); + var commandText = stringBuilder.ToString(); var list = new List(); using (var connection = GetConnection(true)) + using (var statement = PrepareStatement(connection, commandText)) { - using (var statement = PrepareStatement(connection, commandText)) + foreach (var row in statement.ExecuteQuery()) { - foreach (var row in statement.ExecuteQuery()) + if (row.TryGetString(0, out var result)) { - if (row.TryGetString(0, out var result)) - { - list.Add(result); - } + list.Add(result); } } } @@ -5261,13 +5301,14 @@ AND Type = @InternalPersonType)"); InternalItemsQuery typeSubQuery = null; - Dictionary itemCountColumns = null; + string itemCountColumns = null; + var stringBuilder = new StringBuilder(); var typesToCount = query.IncludeItemTypes; if (typesToCount.Length > 0) { - var itemCountColumnQuery = "select group_concat(type, '|')" + GetFromText("B"); + stringBuilder.Append("(select group_concat(type, '|') from TypedBaseItems B"); typeSubQuery = new InternalItemsQuery(query.User) { @@ -5283,20 +5324,21 @@ AND Type = @InternalPersonType)"); }; var whereClauses = GetWhereClauses(typeSubQuery, null); - whereClauses.Add("guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND " + typeClause + ")"); + stringBuilder.Append(" where ") + .AppendJoin(" AND ", whereClauses) + .Append("guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND ") + .Append(typeClause) + .Append(")) as itemTypes"); - itemCountColumnQuery += " where " + string.Join(" AND ", whereClauses); - - itemCountColumns = new Dictionary() - { - { "itemTypes", "(" + itemCountColumnQuery + ") as itemTypes" } - }; + itemCountColumns = stringBuilder.ToString(); + stringBuilder.Clear(); } List columns = _retriveItemColumns.ToList(); - if (itemCountColumns != null) + // Unfortunately we need to add it to columns to ensure the order of the columns in the select + if (!string.IsNullOrEmpty(itemCountColumns)) { - columns.AddRange(itemCountColumns.Values); + columns.Add(itemCountColumns); } // do this first before calling GetFinalColumnsToSelect, otherwise ExcludeItemIds will be set by SimilarTo @@ -5319,18 +5361,18 @@ AND Type = @InternalPersonType)"); columns = GetFinalColumnsToSelect(query, columns); - var commandText = "select " - + string.Join(',', columns) - + GetFromText() - + GetJoinUserDataText(query); - var innerWhereClauses = GetWhereClauses(innerQuery, null); - var innerWhereText = innerWhereClauses.Count == 0 ? - string.Empty : - " where " + string.Join(" AND ", innerWhereClauses); + stringBuilder.Append(" where Type=@SelectType And CleanName In (Select CleanValue from ItemValues where ") + .Append(typeClause) + .Append(" AND ItemId in (select guid from TypedBaseItems"); + if (innerWhereClauses.Count > 0) + { + stringBuilder.Append(" where ") + .AppendJoin(" AND ", innerWhereClauses); + } - var whereText = " where Type=@SelectType And CleanName In (Select CleanValue from ItemValues where " + typeClause + " AND ItemId in (select guid from TypedBaseItems" + innerWhereText + "))"; + stringBuilder.Append("))"); var outerQuery = new InternalItemsQuery(query.User) { @@ -5355,23 +5397,31 @@ AND Type = @InternalPersonType)"); }; var outerWhereClauses = GetWhereClauses(outerQuery, null); - if (outerWhereClauses.Count != 0) { - whereText += " AND " + string.Join(" AND ", outerWhereClauses); + stringBuilder.Append(" AND ") + .AppendJoin(" AND ", outerWhereClauses); } - commandText += whereText + " group by PresentationUniqueKey"; + var whereText = stringBuilder.ToString(); + stringBuilder.Clear(); + + stringBuilder.Append("select ") + .AppendJoin(',', columns) + .Append(FromText) + .Append(GetJoinUserDataText(query)) + .Append(whereText) + .Append(" group by PresentationUniqueKey"); if (query.OrderBy.Count != 0 || query.SimilarTo != null || !string.IsNullOrEmpty(query.SearchTerm)) { - commandText += GetOrderByText(query); + stringBuilder.Append(GetOrderByText(query)); } else { - commandText += " order by SortName"; + stringBuilder.Append(" order by SortName"); } if (query.Limit.HasValue || query.StartIndex.HasValue) @@ -5380,32 +5430,37 @@ AND Type = @InternalPersonType)"); if (query.Limit.HasValue || offset > 0) { - commandText += " LIMIT " + (query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture); + stringBuilder.Append(" LIMIT ") + .Append((query.Limit ?? int.MaxValue).ToString(CultureInfo.InvariantCulture)); } if (offset > 0) { - commandText += " OFFSET " + offset.ToString(CultureInfo.InvariantCulture); + stringBuilder.Append(" OFFSET ") + .Append(offset.ToString(CultureInfo.InvariantCulture)); } } var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; - var statementTexts = new List(); + string commandText = string.Empty; + if (!isReturningZeroItems) { - statementTexts.Add(commandText); + commandText = stringBuilder.ToString(); } + string countText = string.Empty; if (query.EnableTotalRecordCount) { - var countText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) - + GetFromText() - + GetJoinUserDataText(query) - + whereText; + stringBuilder.Clear(); + stringBuilder.Append("select ") + .AppendJoin(',', GetFinalColumnsToSelect(query, new List { "count (distinct PresentationUniqueKey)" })) + .Append(FromText) + .Append(GetJoinUserDataText(query)) + .Append(whereText); - statementTexts.Add(countText); + countText = stringBuilder.ToString(); } var list = new List<(BaseItem, ItemCounts)>(); @@ -5415,11 +5470,9 @@ AND Type = @InternalPersonType)"); connection.RunInTransaction( db => { - var statements = PrepareAll(db, statementTexts); - if (!isReturningZeroItems) { - using (var statement = statements[0]) + using (var statement = PrepareStatement(db, commandText)) { statement.TryBind("@SelectType", returnType); if (EnableJoinUserData(query)) @@ -5460,13 +5513,7 @@ AND Type = @InternalPersonType)"); if (query.EnableTotalRecordCount) { - commandText = "select " - + string.Join(',', GetFinalColumnsToSelect(query, new[] { "count (distinct PresentationUniqueKey)" })) - + GetFromText() - + GetJoinUserDataText(query) - + whereText; - - using (var statement = statements[statements.Length - 1]) + using (var statement = PrepareStatement(db, countText)) { statement.TryBind("@SelectType", returnType); if (EnableJoinUserData(query)) diff --git a/Emby.Server.Implementations/Data/TypeMapper.cs b/Emby.Server.Implementations/Data/TypeMapper.cs index 7f1306d15a..064664e1fe 100644 --- a/Emby.Server.Implementations/Data/TypeMapper.cs +++ b/Emby.Server.Implementations/Data/TypeMapper.cs @@ -28,19 +28,9 @@ namespace Emby.Server.Implementations.Data throw new ArgumentNullException(nameof(typeName)); } - return _typeMap.GetOrAdd(typeName, LookupType); - } - - /// - /// Lookups the type. - /// - /// Name of the type. - /// Type. - private Type? LookupType(string typeName) - { - return AppDomain.CurrentDomain.GetAssemblies() - .Select(a => a.GetType(typeName)) - .FirstOrDefault(t => t != null); + return _typeMap.GetOrAdd(typeName, k => AppDomain.CurrentDomain.GetAssemblies() + .Select(a => a.GetType(k)) + .FirstOrDefault(t => t != null)); } } } diff --git a/Emby.Server.Implementations/IO/ManagedFileSystem.cs b/Emby.Server.Implementations/IO/ManagedFileSystem.cs index 6a554e68ab..64d802457e 100644 --- a/Emby.Server.Implementations/IO/ManagedFileSystem.cs +++ b/Emby.Server.Implementations/IO/ManagedFileSystem.cs @@ -7,6 +7,7 @@ using System.IO; using System.Linq; using System.Runtime.InteropServices; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.IO; using MediaBrowser.Model.System; using Microsoft.Extensions.Logging; @@ -243,8 +244,8 @@ namespace Emby.Server.Implementations.IO { result.Length = fileInfo.Length; - // Issue #2354 get the size of files behind symbolic links - if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint)) + // Issue #2354 get the size of files behind symbolic links. Also Enum.HasFlag is bad as it boxes! + if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) { try { @@ -618,13 +619,13 @@ namespace Emby.Server.Implementations.IO { files = files.Where(i => { - var ext = i.Extension; - if (ext == null) + var ext = i.Extension.AsSpan(); + if (ext.IsEmpty) { return false; } - return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase); + return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase); }); } @@ -636,8 +637,7 @@ namespace Emby.Server.Implementations.IO var directoryInfo = new DirectoryInfo(path); var enumerationOptions = GetEnumerationOptions(recursive); - return ToMetadata(directoryInfo.EnumerateDirectories("*", enumerationOptions)) - .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", enumerationOptions))); + return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", enumerationOptions)); } private IEnumerable ToMetadata(IEnumerable infos) @@ -672,13 +672,13 @@ namespace Emby.Server.Implementations.IO { files = files.Where(i => { - var ext = Path.GetExtension(i); - if (ext == null) + var ext = Path.GetExtension(i.AsSpan()); + if (ext.IsEmpty) { return false; } - return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase); + return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase); }); } diff --git a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index 3380e29d48..c7d1139639 100644 --- a/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -77,7 +77,7 @@ namespace Emby.Server.Implementations.Library if (parent != null) { // Don't resolve these into audio files - if (string.Equals(Path.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename, StringComparison.Ordinal) + if (Path.GetFileNameWithoutExtension(filename.AsSpan()).Equals(BaseItem.ThemeSongFilename, StringComparison.Ordinal) && _libraryManager.IsAudioFile(filename)) { return true; diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index f8d8197d46..ffff3cfc51 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -696,25 +696,32 @@ namespace Emby.Server.Implementations.Library } private IEnumerable ResolveFileList( - IEnumerable fileList, + IReadOnlyList fileList, IDirectoryService directoryService, Folder parent, string collectionType, IItemResolver[] resolvers, LibraryOptions libraryOptions) { - return fileList.Select(f => + // Given that fileList is a list we can save enumerator allocations by indexing + for (var i = 0; i < fileList.Count; i++) { + var file = fileList[i]; + BaseItem result = null; try { - return ResolvePath(f, directoryService, resolvers, parent, collectionType, libraryOptions); + result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions); } catch (Exception ex) { - _logger.LogError(ex, "Error resolving path {path}", f.FullName); - return null; + _logger.LogError(ex, "Error resolving path {Path}", file.FullName); } - }).Where(i => i != null); + + if (result != null) + { + yield return result; + } + } } /// @@ -2076,7 +2083,7 @@ namespace Emby.Server.Implementations.Library return new List(); } - return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType().ToList()); + return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType()); } public List GetCollectionFolders(BaseItem item, List allUserRootChildren) @@ -2101,10 +2108,10 @@ namespace Emby.Server.Implementations.Library return GetCollectionFoldersInternal(item, allUserRootChildren); } - private static List GetCollectionFoldersInternal(BaseItem item, List allUserRootChildren) + private static List GetCollectionFoldersInternal(BaseItem item, IEnumerable allUserRootChildren) { return allUserRootChildren - .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase)) + .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path.AsSpan(), StringComparison.OrdinalIgnoreCase)) .ToList(); } @@ -2112,9 +2119,9 @@ namespace Emby.Server.Implementations.Library { if (!(item is CollectionFolder collectionFolder)) { + // List.Find is more performant than FirstOrDefault due to enumerator allocation collectionFolder = GetCollectionFolders(item) - .OfType() - .FirstOrDefault(); + .Find(folder => folder is CollectionFolder) as CollectionFolder; } return collectionFolder == null ? new LibraryOptions() : collectionFolder.GetLibraryOptions(); @@ -2500,8 +2507,7 @@ namespace Emby.Server.Implementations.Library /// public bool IsVideoFile(string path) { - var resolver = new VideoResolver(GetNamingOptions()); - return resolver.IsVideoFile(path); + return VideoResolver.IsVideoFile(path, GetNamingOptions()); } /// @@ -2679,6 +2685,7 @@ namespace Emby.Server.Implementations.Library return changed; } + /// public NamingOptions GetNamingOptions() { if (_namingOptions == null) @@ -2692,13 +2699,12 @@ namespace Emby.Server.Implementations.Library public ItemLookupInfo ParseName(string name) { - var resolver = new VideoResolver(GetNamingOptions()); - - var result = resolver.CleanDateTime(name); + var namingOptions = GetNamingOptions(); + var result = VideoResolver.CleanDateTime(name, namingOptions); return new ItemLookupInfo { - Name = resolver.TryCleanString(result.Name, out var newName) ? newName.ToString() : result.Name, + Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName.ToString() : result.Name, Year = result.Year }; } @@ -2712,9 +2718,7 @@ namespace Emby.Server.Implementations.Library .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false)) .ToList(); - var videoListResolver = new VideoListResolver(namingOptions); - - var videos = videoListResolver.Resolve(fileSystemChildren); + var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions); var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase)); @@ -2758,9 +2762,7 @@ namespace Emby.Server.Implementations.Library .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false)) .ToList(); - var videoListResolver = new VideoListResolver(namingOptions); - - var videos = videoListResolver.Resolve(fileSystemChildren); + var videos = VideoListResolver.Resolve(fileSystemChildren, namingOptions); var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files[0].Path, StringComparison.OrdinalIgnoreCase)); diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index 38e81d14c4..b812b6b61b 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -352,7 +352,7 @@ namespace Emby.Server.Implementations.Library private string[] NormalizeLanguage(string language) { - if (language == null) + if (string.IsNullOrEmpty(language)) { return Array.Empty(); } @@ -381,8 +381,7 @@ namespace Emby.Server.Implementations.Library } } - var preferredSubs = string.IsNullOrEmpty(user.SubtitleLanguagePreference) - ? Array.Empty() : NormalizeLanguage(user.SubtitleLanguagePreference); + var preferredSubs = NormalizeLanguage(user.SubtitleLanguagePreference); var defaultAudioIndex = source.DefaultAudioStreamIndex; var audioLangage = defaultAudioIndex == null @@ -411,9 +410,7 @@ namespace Emby.Server.Implementations.Library } } - var preferredAudio = string.IsNullOrEmpty(user.AudioLanguagePreference) - ? Array.Empty() - : NormalizeLanguage(user.AudioLanguagePreference); + var preferredAudio = NormalizeLanguage(user.AudioLanguagePreference); source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.PlayDefaultAudioTrack); } diff --git a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index a3dcdc9441..cdb492022b 100644 --- a/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -47,11 +47,9 @@ namespace Emby.Server.Implementations.Library.Resolvers protected virtual TVideoType ResolveVideo(ItemResolveArgs args, bool parseName) where TVideoType : Video, new() { - var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); + var namingOptions = LibraryManager.GetNamingOptions(); // If the path is a file check for a matching extensions - var parser = new VideoResolver(namingOptions); - if (args.IsDirectory) { TVideoType video = null; @@ -66,7 +64,7 @@ namespace Emby.Server.Implementations.Library.Resolvers { if (IsDvdDirectory(child.FullName, filename, args.DirectoryService)) { - videoInfo = parser.ResolveDirectory(args.Path); + videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions); if (videoInfo == null) { @@ -84,7 +82,7 @@ namespace Emby.Server.Implementations.Library.Resolvers if (IsBluRayDirectory(child.FullName, filename, args.DirectoryService)) { - videoInfo = parser.ResolveDirectory(args.Path); + videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions); if (videoInfo == null) { @@ -102,7 +100,7 @@ namespace Emby.Server.Implementations.Library.Resolvers } else if (IsDvdFile(filename)) { - videoInfo = parser.ResolveDirectory(args.Path); + videoInfo = VideoResolver.ResolveDirectory(args.Path, namingOptions); if (videoInfo == null) { @@ -132,7 +130,7 @@ namespace Emby.Server.Implementations.Library.Resolvers } else { - var videoInfo = parser.Resolve(args.Path, false, false); + var videoInfo = VideoResolver.Resolve(args.Path, false, namingOptions, false); if (videoInfo == null) { @@ -252,10 +250,7 @@ namespace Emby.Server.Implementations.Library.Resolvers protected void Set3DFormat(Video video) { - var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); - - var resolver = new Format3DParser(namingOptions); - var result = resolver.Parse(video.Path); + var result = Format3DParser.Parse(video.Path, LibraryManager.GetNamingOptions()); Set3DFormat(video, result.Is3D, result.Format3D); } diff --git a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 02c5287646..97f96f7469 100644 --- a/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/Emby.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using Emby.Naming.Video; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -257,10 +258,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies } } - var namingOptions = ((LibraryManager)LibraryManager).GetNamingOptions(); + var namingOptions = LibraryManager.GetNamingOptions(); - var resolver = new VideoListResolver(namingOptions); - var resolverResult = resolver.Resolve(files, suppportMultiEditions).ToList(); + var resolverResult = VideoListResolver.Resolve(files, namingOptions, suppportMultiEditions).ToList(); var result = new MultiItemResolverResult { @@ -537,7 +537,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies return returnVideo; } - private bool IsInvalid(Folder parent, string collectionType) + private bool IsInvalid(Folder parent, ReadOnlySpan collectionType) { if (parent != null) { @@ -547,12 +547,12 @@ namespace Emby.Server.Implementations.Library.Resolvers.Movies } } - if (string.IsNullOrEmpty(collectionType)) + if (collectionType.IsEmpty) { return false; } - return !_validCollectionTypes.Contains(collectionType, StringComparer.OrdinalIgnoreCase); + return !_validCollectionTypes.Contains(collectionType, StringComparison.OrdinalIgnoreCase); } } } diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index dd5dee1d16..b1ff28c2c5 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -5,7 +5,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Linq; using System.Reflection; using System.Text.Json; using System.Threading.Tasks; @@ -169,12 +168,22 @@ namespace Emby.Server.Implementations.Localization /// public CultureDto FindLanguageInfo(string language) - => GetCultures() - .FirstOrDefault(i => - string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase) - || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase) - || i.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase) - || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase)); + { + // TODO language should ideally be a ReadOnlySpan but moq cannot mock ref structs + for (var i = 0; i < _cultures.Count; i++) + { + var culture = _cultures[i]; + if (language.Equals(culture.DisplayName, StringComparison.OrdinalIgnoreCase) + || language.Equals(culture.Name, StringComparison.OrdinalIgnoreCase) + || culture.ThreeLetterISOLanguageNames.Contains(language, StringComparison.OrdinalIgnoreCase) + || language.Equals(culture.TwoLetterISOLanguageName, StringComparison.OrdinalIgnoreCase)) + { + return culture; + } + } + + return default; + } /// public IEnumerable GetCountries() @@ -224,7 +233,7 @@ namespace Emby.Server.Implementations.Localization throw new ArgumentNullException(nameof(rating)); } - if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase)) + if (_unratedValues.Contains(rating.AsSpan(), StringComparison.OrdinalIgnoreCase)) { return null; } @@ -252,11 +261,11 @@ namespace Emby.Server.Implementations.Localization var index = rating.IndexOf(':', StringComparison.Ordinal); if (index != -1) { - rating = rating.Substring(index).TrimStart(':').Trim(); + var trimmedRating = rating.AsSpan(index).TrimStart(':').Trim(); - if (!string.IsNullOrWhiteSpace(rating)) + if (!trimmedRating.IsEmpty) { - return GetRatingLevel(rating); + return GetRatingLevel(trimmedRating.ToString()); } } @@ -318,7 +327,8 @@ namespace Emby.Server.Implementations.Localization return _dictionaries.GetOrAdd( culture, - f => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult()); + (key, localizationManager) => localizationManager.GetDictionary(Prefix, key, DefaultCulture + ".json").GetAwaiter().GetResult(), + this); } private async Task> GetDictionary(string prefix, string culture, string baseFilename) diff --git a/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs index 8d8b82f0a4..5ff73de819 100644 --- a/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs +++ b/Emby.Server.Implementations/Serialization/MyXmlSerializer.cs @@ -21,7 +21,8 @@ namespace Emby.Server.Implementations.Serialization private static XmlSerializer GetSerializer(Type type) => _serializers.GetOrAdd( type.FullName ?? throw new ArgumentException($"Invalid type {type}."), - _ => new XmlSerializer(type)); + (_, t) => new XmlSerializer(t), + type); /// /// Serializes to writer. diff --git a/Emby.Server.Implementations/ServerApplicationPaths.cs b/Emby.Server.Implementations/ServerApplicationPaths.cs index ac589b03cf..d5483bf40b 100644 --- a/Emby.Server.Implementations/ServerApplicationPaths.cs +++ b/Emby.Server.Implementations/ServerApplicationPaths.cs @@ -26,19 +26,23 @@ namespace Emby.Server.Implementations webDirectoryPath) { InternalMetadataPath = DefaultInternalMetadataPath; + // ProgramDataPath cannot change when the server is running, so cache these to avoid allocations. + RootFolderPath = Path.Join(ProgramDataPath, "root"); + DefaultUserViewsPath = Path.Combine(RootFolderPath, "default"); + DefaultInternalMetadataPath = Path.Combine(ProgramDataPath, "metadata"); } /// /// Gets the path to the base root media directory. /// /// The root folder path. - public string RootFolderPath => Path.Combine(ProgramDataPath, "root"); + public string RootFolderPath { get; } /// /// Gets the path to the default user view directory. Used if no specific user view is defined. /// /// The default user views path. - public string DefaultUserViewsPath => Path.Combine(RootFolderPath, "default"); + public string DefaultUserViewsPath { get; } /// /// Gets the path to the People directory. @@ -98,7 +102,7 @@ namespace Emby.Server.Implementations public string UserConfigurationDirectoryPath => Path.Combine(ConfigurationDirectoryPath, "users"); /// - public string DefaultInternalMetadataPath => Path.Combine(ProgramDataPath, "metadata"); + public string DefaultInternalMetadataPath { get; } /// public string InternalMetadataPath { get; set; } diff --git a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs index 68119cfed6..ffc274c5de 100644 --- a/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs +++ b/MediaBrowser.Controller/BaseItemManager/BaseItemManager.cs @@ -3,6 +3,7 @@ using System; using System.Linq; using System.Threading; +using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; @@ -52,7 +53,7 @@ namespace MediaBrowser.Controller.BaseItemManager var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name); if (typeOptions != null) { - return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return typeOptions.MetadataFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } if (!libraryOptions.EnableInternetProviders) @@ -62,7 +63,7 @@ namespace MediaBrowser.Controller.BaseItemManager var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); - return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } /// @@ -83,7 +84,7 @@ namespace MediaBrowser.Controller.BaseItemManager var typeOptions = libraryOptions.GetTypeOptions(baseItem.GetType().Name); if (typeOptions != null) { - return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return typeOptions.ImageFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } if (!libraryOptions.EnableInternetProviders) @@ -93,7 +94,7 @@ namespace MediaBrowser.Controller.BaseItemManager var itemConfig = _serverConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase)); - return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase); + return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name.AsSpan(), StringComparison.OrdinalIgnoreCase); } /// diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 6e46b4cec8..2574961b86 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -666,14 +666,12 @@ namespace MediaBrowser.Controller.Entities { if (SourceType == SourceType.Channel) { - return System.IO.Path.Combine(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture)); + return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture)); } ReadOnlySpan idString = Id.ToString("N", CultureInfo.InvariantCulture); - basePath = System.IO.Path.Combine(basePath, "library"); - - return System.IO.Path.Join(basePath, idString.Slice(0, 2), idString); + return System.IO.Path.Join(basePath, "library", idString.Slice(0, 2), idString); } /// @@ -1258,7 +1256,7 @@ namespace MediaBrowser.Controller.Entities // Support plex/xbmc convention files.AddRange(fileSystemChildren - .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))); + .Where(i => !i.IsDirectory && System.IO.Path.GetFileNameWithoutExtension(i.FullName.AsSpan()).Equals(ThemeSongFilename, StringComparison.OrdinalIgnoreCase))); return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions()) .OfType() @@ -1319,14 +1317,16 @@ namespace MediaBrowser.Controller.Entities { var extras = new List